blob: cd7d603a09a2e42f51119204b5d6553093c6100d [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 ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100657 result == ErrorCode::INVALID_KEY_BLOB)
658 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000659 } else {
660 // The KeyMint implementation detected that the generated key
661 // is unusable.
662 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
663 }
664 }
665 }
666 }
667}
668
669/*
670 * NewKeyGenerationTest.AesGcmMissingMinMac
671 *
672 * Verifies that specifying an invalid key size for AES key generation returns
673 * UNSUPPORTED_KEY_SIZE.
674 */
675TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
676 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
677 BlockMode block_mode = BlockMode::GCM;
678 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
679 SCOPED_TRACE(testing::Message()
680 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
681 vector<uint8_t> key_blob;
682 vector<KeyCharacteristics> key_characteristics;
683 // No MIN_MAC_LENGTH provided.
684 auto builder = AuthorizationSetBuilder()
685 .AesEncryptionKey(key_size)
686 .BlockMode(block_mode)
687 .Padding(padding_mode)
688 .SetDefaultValidity();
689 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
690 GenerateKey(builder, &key_blob, &key_characteristics));
691 }
692 }
693}
694
695/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100696 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
697 *
698 * Verifies that specifying an invalid min MAC size for AES key generation returns
699 * UNSUPPORTED_MIN_MAC_LENGTH.
700 */
701TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
702 for (size_t min_mac_len : {88, 136}) {
703 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
704 BlockMode block_mode = BlockMode::GCM;
705 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
706 SCOPED_TRACE(testing::Message()
707 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
708 vector<uint8_t> key_blob;
709 vector<KeyCharacteristics> key_characteristics;
710 auto builder = AuthorizationSetBuilder()
711 .AesEncryptionKey(key_size)
712 .BlockMode(block_mode)
713 .Padding(padding_mode)
714 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
715 .SetDefaultValidity();
716 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
717 GenerateKey(builder, &key_blob, &key_characteristics));
718 }
719 }
720 }
721}
722
723/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000724 * NewKeyGenerationTest.TripleDes
725 *
726 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
727 * have correct characteristics.
728 */
729TEST_P(NewKeyGenerationTest, TripleDes) {
730 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
731 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
732 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
733 SCOPED_TRACE(testing::Message()
734 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
735 vector<uint8_t> key_blob;
736 vector<KeyCharacteristics> key_characteristics;
737 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
738 .TripleDesEncryptionKey(key_size)
739 .BlockMode(block_mode)
740 .Padding(padding_mode)
741 .Authorization(TAG_NO_AUTH_REQUIRED)
742 .SetDefaultValidity(),
743 &key_blob, &key_characteristics));
744
745 EXPECT_GT(key_blob.size(), 0U);
746 CheckSymmetricParams(key_characteristics);
747
748 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
749
750 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
751 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
752 << "Key size " << key_size << "missing";
753
754 CheckedDeleteKey(&key_blob);
755 }
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.TripleDesWithAttestation
762 *
763 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
764 * have correct characteristics.
765 *
766 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
767 * put in a certificate) but which isn't an error.
768 */
769TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
770 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
771 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
772 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
773 SCOPED_TRACE(testing::Message()
774 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
775
776 auto challenge = "hello";
777 auto app_id = "foo";
778
779 vector<uint8_t> key_blob;
780 vector<KeyCharacteristics> key_characteristics;
781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
782 .TripleDesEncryptionKey(key_size)
783 .BlockMode(block_mode)
784 .Padding(padding_mode)
785 .Authorization(TAG_NO_AUTH_REQUIRED)
786 .AttestationChallenge(challenge)
787 .AttestationApplicationId(app_id)
788 .SetDefaultValidity(),
789 &key_blob, &key_characteristics));
790
791 EXPECT_GT(key_blob.size(), 0U);
792 CheckSymmetricParams(key_characteristics);
793
794 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
795
796 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
797 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
798 << "Key size " << key_size << "missing";
799
800 CheckedDeleteKey(&key_blob);
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.TripleDesInvalidSize
808 *
809 * Verifies that specifying an invalid key size for 3-DES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
813 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
814 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
821 GenerateKey(AuthorizationSetBuilder()
822 .TripleDesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .Authorization(TAG_NO_AUTH_REQUIRED)
826 .SetDefaultValidity(),
827 &key_blob, &key_characteristics));
828 }
829 }
830 }
831
832 // Omitting the key size fails.
833 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
834 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
835 SCOPED_TRACE(testing::Message()
836 << "3DES-default-" << block_mode << "-" << padding_mode);
837 vector<uint8_t> key_blob;
838 vector<KeyCharacteristics> key_characteristics;
839 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
840 GenerateKey(AuthorizationSetBuilder()
841 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
842 .BlockMode(block_mode)
843 .Padding(padding_mode)
844 .Authorization(TAG_NO_AUTH_REQUIRED)
845 .SetDefaultValidity(),
846 &key_blob, &key_characteristics));
847 }
848 }
849}
850
851/*
Selene Huang31ab4042020-04-29 04:22:39 -0700852 * NewKeyGenerationTest.Rsa
853 *
854 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
855 * have correct characteristics.
856 */
857TEST_P(NewKeyGenerationTest, Rsa) {
858 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
859 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700860 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
862 .RsaSigningKey(key_size, 65537)
863 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800864 .Padding(PaddingMode::NONE)
865 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700866 &key_blob, &key_characteristics));
867
868 ASSERT_GT(key_blob.size(), 0U);
869 CheckBaseParams(key_characteristics);
870
Shawn Willden7f424372021-01-10 18:06:50 -0700871 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700872
873 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
874 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
875 << "Key size " << key_size << "missing";
876 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
877
878 CheckedDeleteKey(&key_blob);
879 }
880}
881
882/*
Qi Wud22ec842020-11-26 13:27:53 +0800883 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700884 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100885 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
886 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700887 */
888TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700889 auto challenge = "hello";
890 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891
Selene Huang6e46f142021-04-20 19:20:11 -0700892 auto subject = "cert subj 2";
893 vector<uint8_t> subject_der(make_name_from_str(subject));
894
895 uint64_t serial_int = 66;
896 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
897
Selene Huang4f64c222021-04-13 19:54:36 -0700898 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700899 vector<uint8_t> key_blob;
900 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700901 ASSERT_EQ(ErrorCode::OK,
902 GenerateKey(AuthorizationSetBuilder()
903 .RsaSigningKey(key_size, 65537)
904 .Digest(Digest::NONE)
905 .Padding(PaddingMode::NONE)
906 .AttestationChallenge(challenge)
907 .AttestationApplicationId(app_id)
908 .Authorization(TAG_NO_AUTH_REQUIRED)
909 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
910 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
911 .SetDefaultValidity(),
912 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700913
914 ASSERT_GT(key_blob.size(), 0U);
915 CheckBaseParams(key_characteristics);
916
917 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
918
919 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
920 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
921 << "Key size " << key_size << "missing";
922 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
923
Selene Huang6e46f142021-04-20 19:20:11 -0700924 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700925 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700926 ASSERT_GT(cert_chain_.size(), 0);
927
928 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
929 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
930 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
931 sw_enforced, hw_enforced, SecLevel(),
932 cert_chain_[0].encodedCertificate));
933
934 CheckedDeleteKey(&key_blob);
935 }
936}
937
938/*
David Drysdale4dc01072021-04-01 12:17:35 +0100939 * NewKeyGenerationTest.RsaWithRpkAttestation
940 *
941 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
942 * that has been generated using an associate IRemotelyProvisionedComponent.
943 */
944TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
945 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
946 // instance.
947 std::shared_ptr<IRemotelyProvisionedComponent> rp;
948 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
949 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
950
951 // Generate a P-256 keypair to use as an attestation key.
952 MacedPublicKey macedPubKey;
953 std::vector<uint8_t> privateKeyBlob;
954 auto status =
955 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
956 ASSERT_TRUE(status.isOk());
957 vector<uint8_t> coseKeyData;
958 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
959
960 AttestationKey attestation_key;
961 attestation_key.keyBlob = std::move(privateKeyBlob);
962 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
963
964 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
965 auto challenge = "hello";
966 auto app_id = "foo";
967
968 vector<uint8_t> key_blob;
969 vector<KeyCharacteristics> key_characteristics;
970 ASSERT_EQ(ErrorCode::OK,
971 GenerateKey(AuthorizationSetBuilder()
972 .RsaSigningKey(key_size, 65537)
973 .Digest(Digest::NONE)
974 .Padding(PaddingMode::NONE)
975 .AttestationChallenge(challenge)
976 .AttestationApplicationId(app_id)
977 .Authorization(TAG_NO_AUTH_REQUIRED)
978 .SetDefaultValidity(),
979 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
980
981 ASSERT_GT(key_blob.size(), 0U);
982 CheckBaseParams(key_characteristics);
983
984 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
985
986 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
987 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
988 << "Key size " << key_size << "missing";
989 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
990
991 // Attestation by itself is not valid (last entry is not self-signed).
992 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
993
994 // The signature over the attested key should correspond to the P256 public key.
995 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
996 ASSERT_TRUE(key_cert.get());
997 EVP_PKEY_Ptr signing_pubkey;
998 p256_pub_key(coseKeyData, &signing_pubkey);
999 ASSERT_TRUE(signing_pubkey.get());
1000
1001 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1002 << "Verification of attested certificate failed "
1003 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1004
1005 CheckedDeleteKey(&key_blob);
1006 }
1007}
1008
1009/*
Selene Huang4f64c222021-04-13 19:54:36 -07001010 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1011 *
1012 * Verifies that keymint attestation for RSA encryption keys with challenge and
1013 * app id is also successful.
1014 */
1015TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1016 auto key_size = 2048;
1017 auto challenge = "hello";
1018 auto app_id = "foo";
1019
Selene Huang6e46f142021-04-20 19:20:11 -07001020 auto subject = "subj 2";
1021 vector<uint8_t> subject_der(make_name_from_str(subject));
1022
1023 uint64_t serial_int = 111166;
1024 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1025
Selene Huang4f64c222021-04-13 19:54:36 -07001026 vector<uint8_t> key_blob;
1027 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001028 ASSERT_EQ(ErrorCode::OK,
1029 GenerateKey(AuthorizationSetBuilder()
1030 .RsaEncryptionKey(key_size, 65537)
1031 .Padding(PaddingMode::NONE)
1032 .AttestationChallenge(challenge)
1033 .AttestationApplicationId(app_id)
1034 .Authorization(TAG_NO_AUTH_REQUIRED)
1035 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1036 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1037 .SetDefaultValidity(),
1038 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001039
1040 ASSERT_GT(key_blob.size(), 0U);
1041 AuthorizationSet auths;
1042 for (auto& entry : key_characteristics) {
1043 auths.push_back(AuthorizationSet(entry.authorizations));
1044 }
1045
1046 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1047 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1048
1049 // Verify that App data and ROT are NOT included.
1050 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1051 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1052
1053 // Check that some unexpected tags/values are NOT present.
1054 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1055 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1056
1057 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1058
1059 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1060 ASSERT_TRUE(os_ver);
1061 EXPECT_EQ(*os_ver, os_version());
1062
1063 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1064
1065 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1066 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1067 << "Key size " << key_size << "missing";
1068 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1069
Selene Huang6e46f142021-04-20 19:20:11 -07001070 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001071 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1072 ASSERT_GT(cert_chain_.size(), 0);
1073
1074 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1075 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1076 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1077 sw_enforced, hw_enforced, SecLevel(),
1078 cert_chain_[0].encodedCertificate));
1079
1080 CheckedDeleteKey(&key_blob);
1081}
1082
1083/*
1084 * NewKeyGenerationTest.RsaWithSelfSign
1085 *
1086 * Verifies that attesting to RSA key generation is successful, and returns
1087 * self signed certificate if no challenge is provided. And signing etc
1088 * works as expected.
1089 */
1090TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001091 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1092 vector<uint8_t> subject_der(make_name_from_str(subject));
1093
1094 uint64_t serial_int = 0;
1095 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1096
Selene Huang4f64c222021-04-13 19:54:36 -07001097 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1098 vector<uint8_t> key_blob;
1099 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001100 ASSERT_EQ(ErrorCode::OK,
1101 GenerateKey(AuthorizationSetBuilder()
1102 .RsaSigningKey(key_size, 65537)
1103 .Digest(Digest::NONE)
1104 .Padding(PaddingMode::NONE)
1105 .Authorization(TAG_NO_AUTH_REQUIRED)
1106 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1107 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1108 .SetDefaultValidity(),
1109 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001110
1111 ASSERT_GT(key_blob.size(), 0U);
1112 CheckBaseParams(key_characteristics);
1113
1114 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1115
1116 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1117 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1118 << "Key size " << key_size << "missing";
1119 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1120
Selene Huang6e46f142021-04-20 19:20:11 -07001121 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001122 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1123 ASSERT_EQ(cert_chain_.size(), 1);
1124
1125 CheckedDeleteKey(&key_blob);
1126 }
1127}
1128
1129/*
1130 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1131 *
1132 * Verifies that attesting to RSA checks for missing app ID.
1133 */
1134TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1135 auto challenge = "hello";
1136 vector<uint8_t> key_blob;
1137 vector<KeyCharacteristics> key_characteristics;
1138
1139 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1140 GenerateKey(AuthorizationSetBuilder()
1141 .RsaSigningKey(2048, 65537)
1142 .Digest(Digest::NONE)
1143 .Padding(PaddingMode::NONE)
1144 .AttestationChallenge(challenge)
1145 .Authorization(TAG_NO_AUTH_REQUIRED)
1146 .SetDefaultValidity(),
1147 &key_blob, &key_characteristics));
1148}
1149
1150/*
1151 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1152 *
1153 * Verifies that attesting to RSA ignores app id if challenge is missing.
1154 */
1155TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1156 auto key_size = 2048;
1157 auto app_id = "foo";
1158
Selene Huang6e46f142021-04-20 19:20:11 -07001159 auto subject = "cert subj 2";
1160 vector<uint8_t> subject_der(make_name_from_str(subject));
1161
1162 uint64_t serial_int = 1;
1163 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1164
Selene Huang4f64c222021-04-13 19:54:36 -07001165 vector<uint8_t> key_blob;
1166 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001167 ASSERT_EQ(ErrorCode::OK,
1168 GenerateKey(AuthorizationSetBuilder()
1169 .RsaSigningKey(key_size, 65537)
1170 .Digest(Digest::NONE)
1171 .Padding(PaddingMode::NONE)
1172 .AttestationApplicationId(app_id)
1173 .Authorization(TAG_NO_AUTH_REQUIRED)
1174 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1175 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1176 .SetDefaultValidity(),
1177 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001178
1179 ASSERT_GT(key_blob.size(), 0U);
1180 CheckBaseParams(key_characteristics);
1181
1182 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1183
1184 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1185 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1186 << "Key size " << key_size << "missing";
1187 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1188
Selene Huang6e46f142021-04-20 19:20:11 -07001189 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001190 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1191 ASSERT_EQ(cert_chain_.size(), 1);
1192
1193 CheckedDeleteKey(&key_blob);
1194}
1195
1196/*
Qi Wud22ec842020-11-26 13:27:53 +08001197 * NewKeyGenerationTest.LimitedUsageRsa
1198 *
1199 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1200 * resulting keys have correct characteristics.
1201 */
1202TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1203 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1204 vector<uint8_t> key_blob;
1205 vector<KeyCharacteristics> key_characteristics;
1206 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1207 .RsaSigningKey(key_size, 65537)
1208 .Digest(Digest::NONE)
1209 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001210 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1211 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001212 &key_blob, &key_characteristics));
1213
1214 ASSERT_GT(key_blob.size(), 0U);
1215 CheckBaseParams(key_characteristics);
1216
1217 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1218
1219 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1220 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1221 << "Key size " << key_size << "missing";
1222 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1223
1224 // Check the usage count limit tag appears in the authorizations.
1225 AuthorizationSet auths;
1226 for (auto& entry : key_characteristics) {
1227 auths.push_back(AuthorizationSet(entry.authorizations));
1228 }
1229 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1230 << "key usage count limit " << 1U << " missing";
1231
1232 CheckedDeleteKey(&key_blob);
1233 }
1234}
1235
1236/*
Qi Wubeefae42021-01-28 23:16:37 +08001237 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1238 *
1239 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1240 * resulting keys have correct characteristics and attestation.
1241 */
1242TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001243 auto challenge = "hello";
1244 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001245
Selene Huang6e46f142021-04-20 19:20:11 -07001246 auto subject = "cert subj 2";
1247 vector<uint8_t> subject_der(make_name_from_str(subject));
1248
1249 uint64_t serial_int = 66;
1250 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1251
Selene Huang4f64c222021-04-13 19:54:36 -07001252 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001253 vector<uint8_t> key_blob;
1254 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001255 ASSERT_EQ(ErrorCode::OK,
1256 GenerateKey(AuthorizationSetBuilder()
1257 .RsaSigningKey(key_size, 65537)
1258 .Digest(Digest::NONE)
1259 .Padding(PaddingMode::NONE)
1260 .AttestationChallenge(challenge)
1261 .AttestationApplicationId(app_id)
1262 .Authorization(TAG_NO_AUTH_REQUIRED)
1263 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1264 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1265 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1266 .SetDefaultValidity(),
1267 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001268
1269 ASSERT_GT(key_blob.size(), 0U);
1270 CheckBaseParams(key_characteristics);
1271
1272 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1273
1274 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1275 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1276 << "Key size " << key_size << "missing";
1277 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1278
1279 // Check the usage count limit tag appears in the authorizations.
1280 AuthorizationSet auths;
1281 for (auto& entry : key_characteristics) {
1282 auths.push_back(AuthorizationSet(entry.authorizations));
1283 }
1284 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1285 << "key usage count limit " << 1U << " missing";
1286
1287 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001288 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001289 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001290 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001291
1292 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1293 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1294 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1295 sw_enforced, hw_enforced, SecLevel(),
1296 cert_chain_[0].encodedCertificate));
1297
1298 CheckedDeleteKey(&key_blob);
1299 }
1300}
1301
1302/*
Selene Huang31ab4042020-04-29 04:22:39 -07001303 * NewKeyGenerationTest.NoInvalidRsaSizes
1304 *
1305 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1306 */
1307TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1308 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1309 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001310 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001311 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1312 GenerateKey(AuthorizationSetBuilder()
1313 .RsaSigningKey(key_size, 65537)
1314 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001315 .Padding(PaddingMode::NONE)
1316 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001317 &key_blob, &key_characteristics));
1318 }
1319}
1320
1321/*
1322 * NewKeyGenerationTest.RsaNoDefaultSize
1323 *
1324 * Verifies that failing to specify a key size for RSA key generation returns
1325 * UNSUPPORTED_KEY_SIZE.
1326 */
1327TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1328 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1329 GenerateKey(AuthorizationSetBuilder()
1330 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1331 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001332 .SigningKey()
1333 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001334}
1335
1336/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001337 * NewKeyGenerationTest.RsaMissingParams
1338 *
1339 * Verifies that omitting optional tags works.
1340 */
1341TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1342 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1343 ASSERT_EQ(ErrorCode::OK,
1344 GenerateKey(
1345 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1346 CheckedDeleteKey();
1347 }
1348}
1349
1350/*
Selene Huang31ab4042020-04-29 04:22:39 -07001351 * NewKeyGenerationTest.Ecdsa
1352 *
1353 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1354 * have correct characteristics.
1355 */
1356TEST_P(NewKeyGenerationTest, Ecdsa) {
1357 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1358 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001359 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1361 .EcdsaSigningKey(key_size)
1362 .Digest(Digest::NONE)
1363 .SetDefaultValidity(),
1364 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001365 ASSERT_GT(key_blob.size(), 0U);
1366 CheckBaseParams(key_characteristics);
1367
Shawn Willden7f424372021-01-10 18:06:50 -07001368 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001369
1370 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1371 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1372 << "Key size " << key_size << "missing";
1373
1374 CheckedDeleteKey(&key_blob);
1375 }
1376}
1377
1378/*
Selene Huang4f64c222021-04-13 19:54:36 -07001379 * NewKeyGenerationTest.EcdsaAttestation
1380 *
1381 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1382 * an attestation will be generated.
1383 */
1384TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1385 auto challenge = "hello";
1386 auto app_id = "foo";
1387
Selene Huang6e46f142021-04-20 19:20:11 -07001388 auto subject = "cert subj 2";
1389 vector<uint8_t> subject_der(make_name_from_str(subject));
1390
1391 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1392 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1393
Selene Huang4f64c222021-04-13 19:54:36 -07001394 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1395 vector<uint8_t> key_blob;
1396 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001397 ASSERT_EQ(ErrorCode::OK,
1398 GenerateKey(AuthorizationSetBuilder()
1399 .Authorization(TAG_NO_AUTH_REQUIRED)
1400 .EcdsaSigningKey(key_size)
1401 .Digest(Digest::NONE)
1402 .AttestationChallenge(challenge)
1403 .AttestationApplicationId(app_id)
1404 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1405 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1406 .SetDefaultValidity(),
1407 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001408 ASSERT_GT(key_blob.size(), 0U);
1409 CheckBaseParams(key_characteristics);
1410
1411 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1412
1413 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1414 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1415 << "Key size " << key_size << "missing";
1416
1417 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1418 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001419 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001420
1421 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1422 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1423 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1424 sw_enforced, hw_enforced, SecLevel(),
1425 cert_chain_[0].encodedCertificate));
1426
1427 CheckedDeleteKey(&key_blob);
1428 }
1429}
1430
1431/*
1432 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1433 *
1434 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1435 * the key will generate a self signed attestation.
1436 */
1437TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001438 auto subject = "cert subj 2";
1439 vector<uint8_t> subject_der(make_name_from_str(subject));
1440
1441 uint64_t serial_int = 0x123456FFF1234;
1442 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1443
Selene Huang4f64c222021-04-13 19:54:36 -07001444 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1445 vector<uint8_t> key_blob;
1446 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001447 ASSERT_EQ(ErrorCode::OK,
1448 GenerateKey(AuthorizationSetBuilder()
1449 .EcdsaSigningKey(key_size)
1450 .Digest(Digest::NONE)
1451 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1452 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1453 .SetDefaultValidity(),
1454 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001455 ASSERT_GT(key_blob.size(), 0U);
1456 CheckBaseParams(key_characteristics);
1457
1458 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1459
1460 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1461 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1462 << "Key size " << key_size << "missing";
1463
1464 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001465 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001466 ASSERT_EQ(cert_chain_.size(), 1);
1467
1468 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1469 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1470
1471 CheckedDeleteKey(&key_blob);
1472 }
1473}
1474
1475/*
1476 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1477 *
1478 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1479 * app id must also be provided or else it will fail.
1480 */
1481TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1482 auto challenge = "hello";
1483 vector<uint8_t> key_blob;
1484 vector<KeyCharacteristics> key_characteristics;
1485
1486 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1487 GenerateKey(AuthorizationSetBuilder()
1488 .EcdsaSigningKey(EcCurve::P_256)
1489 .Digest(Digest::NONE)
1490 .AttestationChallenge(challenge)
1491 .SetDefaultValidity(),
1492 &key_blob, &key_characteristics));
1493}
1494
1495/*
1496 * NewKeyGenerationTest.EcdsaIgnoreAppId
1497 *
1498 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1499 * any appid will be ignored, and keymint will generate a self sign certificate.
1500 */
1501TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1502 auto app_id = "foo";
1503
1504 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1505 vector<uint8_t> key_blob;
1506 vector<KeyCharacteristics> key_characteristics;
1507 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1508 .EcdsaSigningKey(key_size)
1509 .Digest(Digest::NONE)
1510 .AttestationApplicationId(app_id)
1511 .SetDefaultValidity(),
1512 &key_blob, &key_characteristics));
1513
1514 ASSERT_GT(key_blob.size(), 0U);
1515 CheckBaseParams(key_characteristics);
1516
1517 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1518
1519 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1520 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1521 << "Key size " << key_size << "missing";
1522
1523 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1524 ASSERT_EQ(cert_chain_.size(), 1);
1525
1526 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1527 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1528
1529 CheckedDeleteKey(&key_blob);
1530 }
1531}
1532
1533/*
1534 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1535 *
1536 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1537 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1538 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1539 * to specify how many following bytes will be used to encode the length.
1540 */
1541TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1542 auto challenge = "hello";
1543 auto key_size = 256;
1544 std::vector<uint32_t> app_id_lengths{143, 258};
1545
1546 for (uint32_t length : app_id_lengths) {
1547 const string app_id(length, 'a');
1548 vector<uint8_t> key_blob;
1549 vector<KeyCharacteristics> key_characteristics;
1550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1551 .Authorization(TAG_NO_AUTH_REQUIRED)
1552 .EcdsaSigningKey(key_size)
1553 .Digest(Digest::NONE)
1554 .AttestationChallenge(challenge)
1555 .AttestationApplicationId(app_id)
1556 .SetDefaultValidity(),
1557 &key_blob, &key_characteristics));
1558 ASSERT_GT(key_blob.size(), 0U);
1559 CheckBaseParams(key_characteristics);
1560
1561 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1562
1563 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1564 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1565 << "Key size " << key_size << "missing";
1566
1567 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1568 ASSERT_GT(cert_chain_.size(), 0);
1569
1570 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1571 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1572 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1573 sw_enforced, hw_enforced, SecLevel(),
1574 cert_chain_[0].encodedCertificate));
1575
1576 CheckedDeleteKey(&key_blob);
1577 }
1578}
1579
1580/*
Qi Wud22ec842020-11-26 13:27:53 +08001581 * NewKeyGenerationTest.LimitedUsageEcdsa
1582 *
1583 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1584 * resulting keys have correct characteristics.
1585 */
1586TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1587 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1588 vector<uint8_t> key_blob;
1589 vector<KeyCharacteristics> key_characteristics;
1590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1591 .EcdsaSigningKey(key_size)
1592 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001593 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1594 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001595 &key_blob, &key_characteristics));
1596
1597 ASSERT_GT(key_blob.size(), 0U);
1598 CheckBaseParams(key_characteristics);
1599
1600 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1601
1602 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1603 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1604 << "Key size " << key_size << "missing";
1605
1606 // Check the usage count limit tag appears in the authorizations.
1607 AuthorizationSet auths;
1608 for (auto& entry : key_characteristics) {
1609 auths.push_back(AuthorizationSet(entry.authorizations));
1610 }
1611 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1612 << "key usage count limit " << 1U << " missing";
1613
1614 CheckedDeleteKey(&key_blob);
1615 }
1616}
1617
1618/*
Selene Huang31ab4042020-04-29 04:22:39 -07001619 * NewKeyGenerationTest.EcdsaDefaultSize
1620 *
1621 * Verifies that failing to specify a key size for EC key generation returns
1622 * UNSUPPORTED_KEY_SIZE.
1623 */
1624TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1625 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1626 GenerateKey(AuthorizationSetBuilder()
1627 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1628 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001629 .Digest(Digest::NONE)
1630 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001631}
1632
1633/*
1634 * NewKeyGenerationTest.EcdsaInvalidSize
1635 *
1636 * Verifies that specifying an invalid key size for EC key generation returns
1637 * UNSUPPORTED_KEY_SIZE.
1638 */
1639TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1640 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1641 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001642 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001643 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1644 .EcdsaSigningKey(key_size)
1645 .Digest(Digest::NONE)
1646 .SetDefaultValidity(),
1647 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001648 }
1649
Janis Danisevskis164bb872021-02-09 11:30:25 -08001650 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1651 .EcdsaSigningKey(190)
1652 .Digest(Digest::NONE)
1653 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001654}
1655
1656/*
1657 * NewKeyGenerationTest.EcdsaMismatchKeySize
1658 *
1659 * Verifies that specifying mismatched key size and curve for EC key generation returns
1660 * INVALID_ARGUMENT.
1661 */
1662TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1663 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1664
1665 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1666 GenerateKey(AuthorizationSetBuilder()
1667 .EcdsaSigningKey(224)
1668 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001669 .Digest(Digest::NONE)
1670 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001671}
1672
1673/*
1674 * NewKeyGenerationTest.EcdsaAllValidSizes
1675 *
1676 * Verifies that keymint supports all required EC key sizes.
1677 */
1678TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1679 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1680 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001681 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1682 .EcdsaSigningKey(size)
1683 .Digest(Digest::NONE)
1684 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001685 << "Failed to generate size: " << size;
1686 CheckedDeleteKey();
1687 }
1688}
1689
1690/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001691 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001692 *
1693 * Verifies that keymint does not support any curve designated as unsupported.
1694 */
1695TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1696 Digest digest;
1697 if (SecLevel() == SecurityLevel::STRONGBOX) {
1698 digest = Digest::SHA_2_256;
1699 } else {
1700 digest = Digest::SHA_2_512;
1701 }
1702 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001703 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1704 .EcdsaSigningKey(curve)
1705 .Digest(digest)
1706 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001707 << "Failed to generate key on curve: " << curve;
1708 CheckedDeleteKey();
1709 }
1710}
1711
1712/*
1713 * NewKeyGenerationTest.Hmac
1714 *
1715 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1716 * characteristics.
1717 */
1718TEST_P(NewKeyGenerationTest, Hmac) {
1719 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1720 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001721 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001722 constexpr size_t key_size = 128;
1723 ASSERT_EQ(ErrorCode::OK,
1724 GenerateKey(
1725 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1726 TAG_MIN_MAC_LENGTH, 128),
1727 &key_blob, &key_characteristics));
1728
1729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
1731
Shawn Willden7f424372021-01-10 18:06:50 -07001732 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1733 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1734 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1735 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001736
1737 CheckedDeleteKey(&key_blob);
1738 }
1739}
1740
1741/*
Selene Huang4f64c222021-04-13 19:54:36 -07001742 * NewKeyGenerationTest.HmacNoAttestation
1743 *
1744 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1745 * and app id are provided.
1746 */
1747TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1748 auto challenge = "hello";
1749 auto app_id = "foo";
1750
1751 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1752 vector<uint8_t> key_blob;
1753 vector<KeyCharacteristics> key_characteristics;
1754 constexpr size_t key_size = 128;
1755 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1756 .HmacKey(key_size)
1757 .Digest(digest)
1758 .AttestationChallenge(challenge)
1759 .AttestationApplicationId(app_id)
1760 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1761 &key_blob, &key_characteristics));
1762
1763 ASSERT_GT(key_blob.size(), 0U);
1764 ASSERT_EQ(cert_chain_.size(), 0);
1765 CheckBaseParams(key_characteristics);
1766
1767 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1768 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1769 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1770 << "Key size " << key_size << "missing";
1771
1772 CheckedDeleteKey(&key_blob);
1773 }
1774}
1775
1776/*
Qi Wud22ec842020-11-26 13:27:53 +08001777 * NewKeyGenerationTest.LimitedUsageHmac
1778 *
1779 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1780 * resulting keys have correct characteristics.
1781 */
1782TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1783 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1784 vector<uint8_t> key_blob;
1785 vector<KeyCharacteristics> key_characteristics;
1786 constexpr size_t key_size = 128;
1787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1788 .HmacKey(key_size)
1789 .Digest(digest)
1790 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1791 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1792 &key_blob, &key_characteristics));
1793
1794 ASSERT_GT(key_blob.size(), 0U);
1795 CheckBaseParams(key_characteristics);
1796
1797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1798 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1799 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1800 << "Key size " << key_size << "missing";
1801
1802 // Check the usage count limit tag appears in the authorizations.
1803 AuthorizationSet auths;
1804 for (auto& entry : key_characteristics) {
1805 auths.push_back(AuthorizationSet(entry.authorizations));
1806 }
1807 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1808 << "key usage count limit " << 1U << " missing";
1809
1810 CheckedDeleteKey(&key_blob);
1811 }
1812}
1813
1814/*
Selene Huang31ab4042020-04-29 04:22:39 -07001815 * NewKeyGenerationTest.HmacCheckKeySizes
1816 *
1817 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1818 */
1819TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1820 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1821 if (key_size < 64 || key_size % 8 != 0) {
1822 // To keep this test from being very slow, we only test a random fraction of
1823 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1824 // them, we expect to run ~40 of them in each run.
1825 if (key_size % 8 == 0 || random() % 10 == 0) {
1826 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1827 GenerateKey(AuthorizationSetBuilder()
1828 .HmacKey(key_size)
1829 .Digest(Digest::SHA_2_256)
1830 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1831 << "HMAC key size " << key_size << " invalid";
1832 }
1833 } else {
1834 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1835 .HmacKey(key_size)
1836 .Digest(Digest::SHA_2_256)
1837 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1838 << "Failed to generate HMAC key of size " << key_size;
1839 CheckedDeleteKey();
1840 }
1841 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001842 if (SecLevel() == SecurityLevel::STRONGBOX) {
1843 // STRONGBOX devices must not support keys larger than 512 bits.
1844 size_t key_size = 520;
1845 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1846 GenerateKey(AuthorizationSetBuilder()
1847 .HmacKey(key_size)
1848 .Digest(Digest::SHA_2_256)
1849 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1850 << "HMAC key size " << key_size << " unexpectedly valid";
1851 }
Selene Huang31ab4042020-04-29 04:22:39 -07001852}
1853
1854/*
1855 * NewKeyGenerationTest.HmacCheckMinMacLengths
1856 *
1857 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1858 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1859 * specific MAC length that failed, so reproducing a failed run will be easy.
1860 */
1861TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1862 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1863 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1864 // To keep this test from being very long, we only test a random fraction of
1865 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1866 // we expect to run ~17 of them in each run.
1867 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1868 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1869 GenerateKey(AuthorizationSetBuilder()
1870 .HmacKey(128)
1871 .Digest(Digest::SHA_2_256)
1872 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1873 << "HMAC min mac length " << min_mac_length << " invalid.";
1874 }
1875 } else {
1876 EXPECT_EQ(ErrorCode::OK,
1877 GenerateKey(AuthorizationSetBuilder()
1878 .HmacKey(128)
1879 .Digest(Digest::SHA_2_256)
1880 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1881 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1882 CheckedDeleteKey();
1883 }
1884 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01001885
1886 // Minimum MAC length must be no more than 512 bits.
1887 size_t min_mac_length = 520;
1888 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1889 GenerateKey(AuthorizationSetBuilder()
1890 .HmacKey(128)
1891 .Digest(Digest::SHA_2_256)
1892 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1893 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07001894}
1895
1896/*
1897 * NewKeyGenerationTest.HmacMultipleDigests
1898 *
1899 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1900 */
1901TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1902 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1903
1904 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1905 GenerateKey(AuthorizationSetBuilder()
1906 .HmacKey(128)
1907 .Digest(Digest::SHA1)
1908 .Digest(Digest::SHA_2_256)
1909 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1910}
1911
1912/*
1913 * NewKeyGenerationTest.HmacDigestNone
1914 *
1915 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1916 */
1917TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1918 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1919 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1920 128)));
1921
1922 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1923 GenerateKey(AuthorizationSetBuilder()
1924 .HmacKey(128)
1925 .Digest(Digest::NONE)
1926 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1927}
1928
Selene Huang4f64c222021-04-13 19:54:36 -07001929/*
1930 * NewKeyGenerationTest.AesNoAttestation
1931 *
1932 * Verifies that attestation parameters to AES keys are ignored and generateKey
1933 * will succeed.
1934 */
1935TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1936 auto challenge = "hello";
1937 auto app_id = "foo";
1938
1939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1940 .Authorization(TAG_NO_AUTH_REQUIRED)
1941 .AesEncryptionKey(128)
1942 .EcbMode()
1943 .Padding(PaddingMode::PKCS7)
1944 .AttestationChallenge(challenge)
1945 .AttestationApplicationId(app_id)));
1946
1947 ASSERT_EQ(cert_chain_.size(), 0);
1948}
1949
1950/*
1951 * NewKeyGenerationTest.TripleDesNoAttestation
1952 *
1953 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1954 * will be successful. No attestation should be generated.
1955 */
1956TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1957 auto challenge = "hello";
1958 auto app_id = "foo";
1959
1960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1961 .TripleDesEncryptionKey(168)
1962 .BlockMode(BlockMode::ECB)
1963 .Authorization(TAG_NO_AUTH_REQUIRED)
1964 .Padding(PaddingMode::NONE)
1965 .AttestationChallenge(challenge)
1966 .AttestationApplicationId(app_id)));
1967 ASSERT_EQ(cert_chain_.size(), 0);
1968}
1969
Selene Huang31ab4042020-04-29 04:22:39 -07001970INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1971
1972typedef KeyMintAidlTestBase SigningOperationsTest;
1973
1974/*
1975 * SigningOperationsTest.RsaSuccess
1976 *
1977 * Verifies that raw RSA signature operations succeed.
1978 */
1979TEST_P(SigningOperationsTest, RsaSuccess) {
1980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1981 .RsaSigningKey(2048, 65537)
1982 .Digest(Digest::NONE)
1983 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001984 .Authorization(TAG_NO_AUTH_REQUIRED)
1985 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001986 string message = "12345678901234567890123456789012";
1987 string signature = SignMessage(
1988 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1989}
1990
1991/*
1992 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1993 *
Shawn Willden7f424372021-01-10 18:06:50 -07001994 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001995 */
1996TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1997 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1998 .Authorization(TAG_NO_AUTH_REQUIRED)
1999 .RsaSigningKey(2048, 65537)
2000 .Digest(Digest::NONE)
2001 .Padding(PaddingMode::NONE)
2002 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002003 .Authorization(TAG_APPLICATION_DATA, "appdata")
2004 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002005 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2006 Begin(KeyPurpose::SIGN,
2007 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2008 AbortIfNeeded();
2009 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2010 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2011 .Digest(Digest::NONE)
2012 .Padding(PaddingMode::NONE)
2013 .Authorization(TAG_APPLICATION_ID, "clientid")));
2014 AbortIfNeeded();
2015 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2016 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2017 .Digest(Digest::NONE)
2018 .Padding(PaddingMode::NONE)
2019 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2020 AbortIfNeeded();
2021 EXPECT_EQ(ErrorCode::OK,
2022 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2023 .Digest(Digest::NONE)
2024 .Padding(PaddingMode::NONE)
2025 .Authorization(TAG_APPLICATION_DATA, "appdata")
2026 .Authorization(TAG_APPLICATION_ID, "clientid")));
2027 AbortIfNeeded();
2028}
2029
2030/*
2031 * SigningOperationsTest.RsaPssSha256Success
2032 *
2033 * Verifies that RSA-PSS signature operations succeed.
2034 */
2035TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2037 .RsaSigningKey(2048, 65537)
2038 .Digest(Digest::SHA_2_256)
2039 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002040 .Authorization(TAG_NO_AUTH_REQUIRED)
2041 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002042 // Use large message, which won't work without digesting.
2043 string message(1024, 'a');
2044 string signature = SignMessage(
2045 message,
2046 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2047}
2048
2049/*
2050 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2051 *
2052 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2053 * supports only unpadded operations.
2054 */
2055TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2057 .RsaSigningKey(2048, 65537)
2058 .Digest(Digest::NONE)
2059 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002060 .Padding(PaddingMode::NONE)
2061 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002062 string message = "12345678901234567890123456789012";
2063 string signature;
2064
2065 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2066 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2067 .Digest(Digest::NONE)
2068 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2069}
2070
2071/*
2072 * SigningOperationsTest.NoUserConfirmation
2073 *
2074 * Verifies that keymint rejects signing operations for keys with
2075 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2076 * presented.
2077 */
2078TEST_P(SigningOperationsTest, NoUserConfirmation) {
2079 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2081 .RsaSigningKey(1024, 65537)
2082 .Digest(Digest::NONE)
2083 .Padding(PaddingMode::NONE)
2084 .Authorization(TAG_NO_AUTH_REQUIRED)
2085 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2086 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002087
2088 const string message = "12345678901234567890123456789012";
2089 EXPECT_EQ(ErrorCode::OK,
2090 Begin(KeyPurpose::SIGN,
2091 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2092 string signature;
2093 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2094}
2095
2096/*
2097 * SigningOperationsTest.RsaPkcs1Sha256Success
2098 *
2099 * Verifies that digested RSA-PKCS1 signature operations succeed.
2100 */
2101TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2103 .RsaSigningKey(2048, 65537)
2104 .Digest(Digest::SHA_2_256)
2105 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002106 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2107 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002108 string message(1024, 'a');
2109 string signature = SignMessage(message, AuthorizationSetBuilder()
2110 .Digest(Digest::SHA_2_256)
2111 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2112}
2113
2114/*
2115 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2116 *
2117 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2118 */
2119TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2121 .RsaSigningKey(2048, 65537)
2122 .Digest(Digest::NONE)
2123 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002124 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2125 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002126 string message(53, 'a');
2127 string signature = SignMessage(message, AuthorizationSetBuilder()
2128 .Digest(Digest::NONE)
2129 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2130}
2131
2132/*
2133 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2134 *
2135 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2136 * given a too-long message.
2137 */
2138TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2139 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2140 .RsaSigningKey(2048, 65537)
2141 .Digest(Digest::NONE)
2142 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002143 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2144 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002145 string message(257, 'a');
2146
2147 EXPECT_EQ(ErrorCode::OK,
2148 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2149 .Digest(Digest::NONE)
2150 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2151 string signature;
2152 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2153}
2154
2155/*
2156 * SigningOperationsTest.RsaPssSha512TooSmallKey
2157 *
2158 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2159 * used with a key that is too small for the message.
2160 *
2161 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2162 * keymint specification requires that salt_size == digest_size, so the message will be
2163 * digest_size * 2 +
2164 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2165 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2166 * for a 1024-bit key.
2167 */
2168TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2169 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2171 .RsaSigningKey(1024, 65537)
2172 .Digest(Digest::SHA_2_512)
2173 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002174 .Padding(PaddingMode::RSA_PSS)
2175 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002176 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2177 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2178 .Digest(Digest::SHA_2_512)
2179 .Padding(PaddingMode::RSA_PSS)));
2180}
2181
2182/*
2183 * SigningOperationsTest.RsaNoPaddingTooLong
2184 *
2185 * Verifies that raw RSA signature operations fail with the correct error code when
2186 * given a too-long message.
2187 */
2188TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2189 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2190 .RsaSigningKey(2048, 65537)
2191 .Digest(Digest::NONE)
2192 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002193 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2194 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002195 // One byte too long
2196 string message(2048 / 8 + 1, 'a');
2197 ASSERT_EQ(ErrorCode::OK,
2198 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2199 .Digest(Digest::NONE)
2200 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2201 string result;
2202 ErrorCode finish_error_code = Finish(message, &result);
2203 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2204 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2205
2206 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2207 message = string(128 * 1024, 'a');
2208 ASSERT_EQ(ErrorCode::OK,
2209 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2210 .Digest(Digest::NONE)
2211 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2212 finish_error_code = Finish(message, &result);
2213 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2214 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2215}
2216
2217/*
2218 * SigningOperationsTest.RsaAbort
2219 *
2220 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2221 * test, but the behavior should be algorithm and purpose-independent.
2222 */
2223TEST_P(SigningOperationsTest, RsaAbort) {
2224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2225 .RsaSigningKey(2048, 65537)
2226 .Digest(Digest::NONE)
2227 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002228 .Padding(PaddingMode::NONE)
2229 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002230
2231 ASSERT_EQ(ErrorCode::OK,
2232 Begin(KeyPurpose::SIGN,
2233 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2234 EXPECT_EQ(ErrorCode::OK, Abort());
2235
2236 // Another abort should fail
2237 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2238
2239 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002240 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002241}
2242
2243/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002244 * SigningOperationsTest.RsaNonUniqueParams
2245 *
2246 * Verifies that an operation with multiple padding modes is rejected.
2247 */
2248TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2249 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2250 .RsaSigningKey(2048, 65537)
2251 .Digest(Digest::NONE)
2252 .Digest(Digest::SHA1)
2253 .Authorization(TAG_NO_AUTH_REQUIRED)
2254 .Padding(PaddingMode::NONE)
2255 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2256 .SetDefaultValidity()));
2257
2258 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2259 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2260 .Digest(Digest::NONE)
2261 .Padding(PaddingMode::NONE)
2262 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2263
2264 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2265 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2266 .Digest(Digest::NONE)
2267 .Digest(Digest::SHA1)
2268 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2269
2270 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2271 Begin(KeyPurpose::SIGN,
2272 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2273}
2274
2275/*
Selene Huang31ab4042020-04-29 04:22:39 -07002276 * SigningOperationsTest.RsaUnsupportedPadding
2277 *
2278 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2279 * with a padding mode inappropriate for RSA.
2280 */
2281TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2283 .RsaSigningKey(2048, 65537)
2284 .Authorization(TAG_NO_AUTH_REQUIRED)
2285 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002286 .Padding(PaddingMode::PKCS7)
2287 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002288 ASSERT_EQ(
2289 ErrorCode::UNSUPPORTED_PADDING_MODE,
2290 Begin(KeyPurpose::SIGN,
2291 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002292 CheckedDeleteKey();
2293
2294 ASSERT_EQ(ErrorCode::OK,
2295 GenerateKey(
2296 AuthorizationSetBuilder()
2297 .RsaSigningKey(2048, 65537)
2298 .Authorization(TAG_NO_AUTH_REQUIRED)
2299 .Digest(Digest::SHA_2_256 /* supported digest */)
2300 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2301 .SetDefaultValidity()));
2302 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2303 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2304 .Digest(Digest::SHA_2_256)
2305 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002306}
2307
2308/*
2309 * SigningOperationsTest.RsaPssNoDigest
2310 *
2311 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2312 */
2313TEST_P(SigningOperationsTest, RsaNoDigest) {
2314 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2315 .RsaSigningKey(2048, 65537)
2316 .Authorization(TAG_NO_AUTH_REQUIRED)
2317 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002318 .Padding(PaddingMode::RSA_PSS)
2319 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002320 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2321 Begin(KeyPurpose::SIGN,
2322 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2323
2324 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2325 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2326}
2327
2328/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002329 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002330 *
2331 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2332 * supported in some cases (as validated in other tests), but a mode must be specified.
2333 */
2334TEST_P(SigningOperationsTest, RsaNoPadding) {
2335 // Padding must be specified
2336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2337 .RsaKey(2048, 65537)
2338 .Authorization(TAG_NO_AUTH_REQUIRED)
2339 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002340 .Digest(Digest::NONE)
2341 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002342 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2343 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2344}
2345
2346/*
2347 * SigningOperationsTest.RsaShortMessage
2348 *
2349 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2350 */
2351TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2353 .Authorization(TAG_NO_AUTH_REQUIRED)
2354 .RsaSigningKey(2048, 65537)
2355 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002356 .Padding(PaddingMode::NONE)
2357 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002358
2359 // Barely shorter
2360 string message(2048 / 8 - 1, 'a');
2361 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2362
2363 // Much shorter
2364 message = "a";
2365 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2366}
2367
2368/*
2369 * SigningOperationsTest.RsaSignWithEncryptionKey
2370 *
2371 * Verifies that RSA encryption keys cannot be used to sign.
2372 */
2373TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2375 .Authorization(TAG_NO_AUTH_REQUIRED)
2376 .RsaEncryptionKey(2048, 65537)
2377 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002378 .Padding(PaddingMode::NONE)
2379 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002380 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2381 Begin(KeyPurpose::SIGN,
2382 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2383}
2384
2385/*
2386 * SigningOperationsTest.RsaSignTooLargeMessage
2387 *
2388 * Verifies that attempting a raw signature of a message which is the same length as the key,
2389 * but numerically larger than the public modulus, fails with the correct error.
2390 */
2391TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2393 .Authorization(TAG_NO_AUTH_REQUIRED)
2394 .RsaSigningKey(2048, 65537)
2395 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002396 .Padding(PaddingMode::NONE)
2397 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002398
2399 // Largest possible message will always be larger than the public modulus.
2400 string message(2048 / 8, static_cast<char>(0xff));
2401 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2402 .Authorization(TAG_NO_AUTH_REQUIRED)
2403 .Digest(Digest::NONE)
2404 .Padding(PaddingMode::NONE)));
2405 string signature;
2406 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2407}
2408
2409/*
2410 * SigningOperationsTest.EcdsaAllSizesAndHashes
2411 *
2412 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2413 */
2414TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2415 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2416 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2417 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2418 .Authorization(TAG_NO_AUTH_REQUIRED)
2419 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002420 .Digest(digest)
2421 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002422 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2423 << " and digest " << digest;
2424 if (error != ErrorCode::OK) continue;
2425
2426 string message(1024, 'a');
2427 if (digest == Digest::NONE) message.resize(key_size / 8);
2428 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2429 CheckedDeleteKey();
2430 }
2431 }
2432}
2433
2434/*
2435 * SigningOperationsTest.EcdsaAllCurves
2436 *
2437 * Verifies that ECDSA operations succeed with all possible curves.
2438 */
2439TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2440 for (auto curve : ValidCurves()) {
2441 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2442 .Authorization(TAG_NO_AUTH_REQUIRED)
2443 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002444 .Digest(Digest::SHA_2_256)
2445 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002446 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2447 if (error != ErrorCode::OK) continue;
2448
2449 string message(1024, 'a');
2450 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2451 CheckedDeleteKey();
2452 }
2453}
2454
2455/*
2456 * SigningOperationsTest.EcdsaNoDigestHugeData
2457 *
2458 * Verifies that ECDSA operations support very large messages, even without digesting. This
2459 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2460 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2461 * the framework.
2462 */
2463TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2464 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2465 .Authorization(TAG_NO_AUTH_REQUIRED)
2466 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002467 .Digest(Digest::NONE)
2468 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002469 string message(1 * 1024, 'a');
2470 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2471}
2472
2473/*
2474 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2475 *
2476 * Verifies that using an EC key requires the correct app ID/data.
2477 */
2478TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2480 .Authorization(TAG_NO_AUTH_REQUIRED)
2481 .EcdsaSigningKey(256)
2482 .Digest(Digest::NONE)
2483 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002484 .Authorization(TAG_APPLICATION_DATA, "appdata")
2485 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002486 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2487 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2488 AbortIfNeeded();
2489 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2490 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2491 .Digest(Digest::NONE)
2492 .Authorization(TAG_APPLICATION_ID, "clientid")));
2493 AbortIfNeeded();
2494 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2495 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2496 .Digest(Digest::NONE)
2497 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2498 AbortIfNeeded();
2499 EXPECT_EQ(ErrorCode::OK,
2500 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2501 .Digest(Digest::NONE)
2502 .Authorization(TAG_APPLICATION_DATA, "appdata")
2503 .Authorization(TAG_APPLICATION_ID, "clientid")));
2504 AbortIfNeeded();
2505}
2506
2507/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002508 * SigningOperationsTest.EcdsaIncompatibleDigest
2509 *
2510 * Verifies that using an EC key requires compatible digest.
2511 */
2512TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2513 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2514 .Authorization(TAG_NO_AUTH_REQUIRED)
2515 .EcdsaSigningKey(256)
2516 .Digest(Digest::NONE)
2517 .Digest(Digest::SHA1)
2518 .SetDefaultValidity()));
2519 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2520 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2521 AbortIfNeeded();
2522}
2523
2524/*
Selene Huang31ab4042020-04-29 04:22:39 -07002525 * SigningOperationsTest.AesEcbSign
2526 *
2527 * Verifies that attempts to use AES keys to sign fail in the correct way.
2528 */
2529TEST_P(SigningOperationsTest, AesEcbSign) {
2530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2531 .Authorization(TAG_NO_AUTH_REQUIRED)
2532 .SigningKey()
2533 .AesEncryptionKey(128)
2534 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2535
2536 AuthorizationSet out_params;
2537 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2538 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2539 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2540 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2541}
2542
2543/*
2544 * SigningOperationsTest.HmacAllDigests
2545 *
2546 * Verifies that HMAC works with all digests.
2547 */
2548TEST_P(SigningOperationsTest, HmacAllDigests) {
2549 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2551 .Authorization(TAG_NO_AUTH_REQUIRED)
2552 .HmacKey(128)
2553 .Digest(digest)
2554 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2555 << "Failed to create HMAC key with digest " << digest;
2556 string message = "12345678901234567890123456789012";
2557 string signature = MacMessage(message, digest, 160);
2558 EXPECT_EQ(160U / 8U, signature.size())
2559 << "Failed to sign with HMAC key with digest " << digest;
2560 CheckedDeleteKey();
2561 }
2562}
2563
2564/*
2565 * SigningOperationsTest.HmacSha256TooLargeMacLength
2566 *
2567 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2568 * digest size.
2569 */
2570TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2571 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2572 .Authorization(TAG_NO_AUTH_REQUIRED)
2573 .HmacKey(128)
2574 .Digest(Digest::SHA_2_256)
2575 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2576 AuthorizationSet output_params;
2577 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2578 AuthorizationSetBuilder()
2579 .Digest(Digest::SHA_2_256)
2580 .Authorization(TAG_MAC_LENGTH, 264),
2581 &output_params));
2582}
2583
2584/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002585 * SigningOperationsTest.HmacSha256InvalidMacLength
2586 *
2587 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2588 * not a multiple of 8.
2589 */
2590TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2592 .Authorization(TAG_NO_AUTH_REQUIRED)
2593 .HmacKey(128)
2594 .Digest(Digest::SHA_2_256)
2595 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2596 AuthorizationSet output_params;
2597 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2598 AuthorizationSetBuilder()
2599 .Digest(Digest::SHA_2_256)
2600 .Authorization(TAG_MAC_LENGTH, 161),
2601 &output_params));
2602}
2603
2604/*
Selene Huang31ab4042020-04-29 04:22:39 -07002605 * SigningOperationsTest.HmacSha256TooSmallMacLength
2606 *
2607 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2608 * specified minimum MAC length.
2609 */
2610TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2612 .Authorization(TAG_NO_AUTH_REQUIRED)
2613 .HmacKey(128)
2614 .Digest(Digest::SHA_2_256)
2615 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2616 AuthorizationSet output_params;
2617 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2618 AuthorizationSetBuilder()
2619 .Digest(Digest::SHA_2_256)
2620 .Authorization(TAG_MAC_LENGTH, 120),
2621 &output_params));
2622}
2623
2624/*
2625 * SigningOperationsTest.HmacRfc4231TestCase3
2626 *
2627 * Validates against the test vectors from RFC 4231 test case 3.
2628 */
2629TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2630 string key(20, 0xaa);
2631 string message(50, 0xdd);
2632 uint8_t sha_224_expected[] = {
2633 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2634 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2635 };
2636 uint8_t sha_256_expected[] = {
2637 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2638 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2639 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2640 };
2641 uint8_t sha_384_expected[] = {
2642 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2643 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2644 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2645 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2646 };
2647 uint8_t sha_512_expected[] = {
2648 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2649 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2650 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2651 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2652 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2653 };
2654
2655 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2656 if (SecLevel() != SecurityLevel::STRONGBOX) {
2657 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2658 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2659 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2660 }
2661}
2662
2663/*
2664 * SigningOperationsTest.HmacRfc4231TestCase5
2665 *
2666 * Validates against the test vectors from RFC 4231 test case 5.
2667 */
2668TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2669 string key(20, 0x0c);
2670 string message = "Test With Truncation";
2671
2672 uint8_t sha_224_expected[] = {
2673 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2674 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2675 };
2676 uint8_t sha_256_expected[] = {
2677 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2678 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2679 };
2680 uint8_t sha_384_expected[] = {
2681 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2682 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2683 };
2684 uint8_t sha_512_expected[] = {
2685 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2686 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2687 };
2688
2689 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2690 if (SecLevel() != SecurityLevel::STRONGBOX) {
2691 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2692 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2693 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2694 }
2695}
2696
2697INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2698
2699typedef KeyMintAidlTestBase VerificationOperationsTest;
2700
2701/*
2702 * VerificationOperationsTest.RsaSuccess
2703 *
2704 * Verifies that a simple RSA signature/verification sequence succeeds.
2705 */
2706TEST_P(VerificationOperationsTest, RsaSuccess) {
2707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2708 .Authorization(TAG_NO_AUTH_REQUIRED)
2709 .RsaSigningKey(2048, 65537)
2710 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002711 .Padding(PaddingMode::NONE)
2712 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002713 string message = "12345678901234567890123456789012";
2714 string signature = SignMessage(
2715 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2716 VerifyMessage(message, signature,
2717 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2718}
2719
2720/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002721 * VerificationOperationsTest.RsaAllPaddingsAndDigests
Selene Huang31ab4042020-04-29 04:22:39 -07002722 *
2723 * Verifies RSA signature/verification for all padding modes and digests.
2724 */
2725TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2726 auto authorizations = AuthorizationSetBuilder()
2727 .Authorization(TAG_NO_AUTH_REQUIRED)
2728 .RsaSigningKey(2048, 65537)
2729 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2730 .Padding(PaddingMode::NONE)
2731 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002732 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2733 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002734
2735 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2736
2737 string message(128, 'a');
2738 string corrupt_message(message);
2739 ++corrupt_message[corrupt_message.size() / 2];
2740
2741 for (auto padding :
2742 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2743 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2744 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2745 // Digesting only makes sense with padding.
2746 continue;
2747 }
2748
2749 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2750 // PSS requires digesting.
2751 continue;
2752 }
2753
2754 string signature =
2755 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2756 VerifyMessage(message, signature,
2757 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2758
2759 /* TODO(seleneh) add exportkey tests back later when we have decided on
2760 * the new api.
2761 if (digest != Digest::NONE) {
2762 // Verify with OpenSSL.
2763 vector<uint8_t> pubkey;
2764 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2765
2766 const uint8_t* p = pubkey.data();
2767 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2768 ASSERT_TRUE(pkey.get());
2769
2770 EVP_MD_CTX digest_ctx;
2771 EVP_MD_CTX_init(&digest_ctx);
2772 EVP_PKEY_CTX* pkey_ctx;
2773 const EVP_MD* md = openssl_digest(digest);
2774 ASSERT_NE(md, nullptr);
2775 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2776 nullptr, pkey.get()));
2777
2778 switch (padding) {
2779 case PaddingMode::RSA_PSS:
2780 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2781 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2782 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2783 // PKCS1 is the default; don't need to set anything.
2784 break;
2785 default:
2786 FAIL();
2787 break;
2788 }
2789
2790 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2791 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2792 reinterpret_cast<const
2793 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2794 }
2795 */
2796
2797 // Corrupt signature shouldn't verify.
2798 string corrupt_signature(signature);
2799 ++corrupt_signature[corrupt_signature.size() / 2];
2800
2801 EXPECT_EQ(ErrorCode::OK,
2802 Begin(KeyPurpose::VERIFY,
2803 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2804 string result;
2805 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2806
2807 // Corrupt message shouldn't verify
2808 EXPECT_EQ(ErrorCode::OK,
2809 Begin(KeyPurpose::VERIFY,
2810 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2811 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2812 }
2813 }
2814}
2815
2816/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002817 * VerificationOperationsTest.RsaAllDigestsAndCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002818 *
2819 * Verifies ECDSA signature/verification for all digests and curves.
2820 */
2821TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2822 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2823
2824 string message = "1234567890";
2825 string corrupt_message = "2234567890";
2826 for (auto curve : ValidCurves()) {
2827 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2828 .Authorization(TAG_NO_AUTH_REQUIRED)
2829 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002830 .Digest(digests)
2831 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002832 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2833 if (error != ErrorCode::OK) {
2834 continue;
2835 }
2836
2837 for (auto digest : digests) {
2838 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2839 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2840
2841 /* TODO(seleneh) add exportkey tests back later when we have decided on
2842 * the new api.
2843
2844 // Verify with OpenSSL
2845 if (digest != Digest::NONE) {
2846 vector<uint8_t> pubkey;
2847 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2848 << curve << ' ' << digest;
2849
2850 const uint8_t* p = pubkey.data();
2851 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2852 ASSERT_TRUE(pkey.get());
2853
2854 EVP_MD_CTX digest_ctx;
2855 EVP_MD_CTX_init(&digest_ctx);
2856 EVP_PKEY_CTX* pkey_ctx;
2857 const EVP_MD* md = openssl_digest(digest);
2858
2859 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2860 nullptr, pkey.get()))
2861 << curve << ' ' << digest;
2862
2863 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2864 message.size()))
2865 << curve << ' ' << digest;
2866
2867 EXPECT_EQ(1,
2868 EVP_DigestVerifyFinal(&digest_ctx,
2869 reinterpret_cast<const
2870 uint8_t*>(signature.data()), signature.size()))
2871 << curve << ' ' << digest;
2872
2873 EVP_MD_CTX_cleanup(&digest_ctx);
2874 }
2875 */
2876 // Corrupt signature shouldn't verify.
2877 string corrupt_signature(signature);
2878 ++corrupt_signature[corrupt_signature.size() / 2];
2879
2880 EXPECT_EQ(ErrorCode::OK,
2881 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2882 << curve << ' ' << digest;
2883
2884 string result;
2885 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2886 << curve << ' ' << digest;
2887
2888 // Corrupt message shouldn't verify
2889 EXPECT_EQ(ErrorCode::OK,
2890 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2891 << curve << ' ' << digest;
2892
2893 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2894 << curve << ' ' << digest;
2895 }
2896
2897 auto rc = DeleteKey();
2898 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2899 }
2900}
2901
2902/*
2903 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2904 *
2905 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2906 */
2907TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2908 string key_material = "HelloThisIsAKey";
2909
2910 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002911 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002912 EXPECT_EQ(ErrorCode::OK,
2913 ImportKey(AuthorizationSetBuilder()
2914 .Authorization(TAG_NO_AUTH_REQUIRED)
2915 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2916 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2917 .Digest(Digest::SHA_2_256)
2918 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2919 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2920 EXPECT_EQ(ErrorCode::OK,
2921 ImportKey(AuthorizationSetBuilder()
2922 .Authorization(TAG_NO_AUTH_REQUIRED)
2923 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2924 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2925 .Digest(Digest::SHA_2_256)
2926 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2927 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2928
2929 string message = "This is a message.";
2930 string signature = SignMessage(
2931 signing_key, message,
2932 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2933
2934 // Signing key should not work.
2935 AuthorizationSet out_params;
2936 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2937 Begin(KeyPurpose::VERIFY, signing_key,
2938 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2939
2940 // Verification key should work.
2941 VerifyMessage(verification_key, message, signature,
2942 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2943
2944 CheckedDeleteKey(&signing_key);
2945 CheckedDeleteKey(&verification_key);
2946}
2947
2948INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2949
2950typedef KeyMintAidlTestBase ExportKeyTest;
2951
2952/*
2953 * ExportKeyTest.RsaUnsupportedKeyFormat
2954 *
2955 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2956 */
2957// TODO(seleneh) add ExportKey to GenerateKey
2958// check result
2959
2960class ImportKeyTest : public KeyMintAidlTestBase {
2961 public:
2962 template <TagType tag_type, Tag tag, typename ValueT>
2963 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2964 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002965 for (auto& entry : key_characteristics_) {
2966 if (entry.securityLevel == SecLevel()) {
2967 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2968 << "Tag " << tag << " with value " << expected
2969 << " not found at security level" << entry.securityLevel;
2970 } else {
2971 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2972 << "Tag " << tag << " found at security level " << entry.securityLevel;
2973 }
Selene Huang31ab4042020-04-29 04:22:39 -07002974 }
2975 }
2976
2977 void CheckOrigin() {
2978 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002979 // Origin isn't a crypto param, but it always lives with them.
2980 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002981 }
2982};
2983
2984/*
2985 * ImportKeyTest.RsaSuccess
2986 *
2987 * Verifies that importing and using an RSA key pair works correctly.
2988 */
2989TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002990 uint32_t key_size;
2991 string key;
2992
2993 if (SecLevel() == SecurityLevel::STRONGBOX) {
2994 key_size = 2048;
2995 key = rsa_2048_key;
2996 } else {
2997 key_size = 1024;
2998 key = rsa_key;
2999 }
3000
Selene Huang31ab4042020-04-29 04:22:39 -07003001 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3002 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003003 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003004 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003005 .Padding(PaddingMode::RSA_PSS)
3006 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003007 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003008
3009 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003010 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003011 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3012 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3013 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3014 CheckOrigin();
3015
3016 string message(1024 / 8, 'a');
3017 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3018 string signature = SignMessage(message, params);
3019 VerifyMessage(message, signature, params);
3020}
3021
3022/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003023 * ImportKeyTest.RsaSuccessWithoutParams
3024 *
3025 * Verifies that importing and using an RSA key pair without specifying parameters
3026 * works correctly.
3027 */
3028TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3029 uint32_t key_size;
3030 string key;
3031
3032 if (SecLevel() == SecurityLevel::STRONGBOX) {
3033 key_size = 2048;
3034 key = rsa_2048_key;
3035 } else {
3036 key_size = 1024;
3037 key = rsa_key;
3038 }
3039
3040 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3041 .Authorization(TAG_NO_AUTH_REQUIRED)
3042 .SigningKey()
3043 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3044 .Digest(Digest::SHA_2_256)
3045 .Padding(PaddingMode::RSA_PSS)
3046 .SetDefaultValidity(),
3047 KeyFormat::PKCS8, key));
3048
3049 // Key size and public exponent are determined from the imported key material.
3050 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3051 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3052
3053 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3054 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3055 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3056 CheckOrigin();
3057
3058 string message(1024 / 8, 'a');
3059 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3060 string signature = SignMessage(message, params);
3061 VerifyMessage(message, signature, params);
3062}
3063
3064/*
Selene Huang31ab4042020-04-29 04:22:39 -07003065 * ImportKeyTest.RsaKeySizeMismatch
3066 *
3067 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3068 * correct way.
3069 */
3070TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3071 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3072 ImportKey(AuthorizationSetBuilder()
3073 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3074 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003075 .Padding(PaddingMode::NONE)
3076 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003077 KeyFormat::PKCS8, rsa_key));
3078}
3079
3080/*
3081 * ImportKeyTest.RsaPublicExponentMismatch
3082 *
3083 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3084 * fails in the correct way.
3085 */
3086TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3087 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3088 ImportKey(AuthorizationSetBuilder()
3089 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3090 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003091 .Padding(PaddingMode::NONE)
3092 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003093 KeyFormat::PKCS8, rsa_key));
3094}
3095
3096/*
3097 * ImportKeyTest.EcdsaSuccess
3098 *
3099 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3100 */
3101TEST_P(ImportKeyTest, EcdsaSuccess) {
3102 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3103 .Authorization(TAG_NO_AUTH_REQUIRED)
3104 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003105 .Digest(Digest::SHA_2_256)
3106 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003107 KeyFormat::PKCS8, ec_256_key));
3108
3109 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3110 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3111 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3112 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3113
3114 CheckOrigin();
3115
3116 string message(32, 'a');
3117 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3118 string signature = SignMessage(message, params);
3119 VerifyMessage(message, signature, params);
3120}
3121
3122/*
3123 * ImportKeyTest.EcdsaP256RFC5915Success
3124 *
3125 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3126 * correctly.
3127 */
3128TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3129 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3130 .Authorization(TAG_NO_AUTH_REQUIRED)
3131 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003132 .Digest(Digest::SHA_2_256)
3133 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003134 KeyFormat::PKCS8, ec_256_key_rfc5915));
3135
3136 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3137 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3138 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3139 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3140
3141 CheckOrigin();
3142
3143 string message(32, 'a');
3144 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3145 string signature = SignMessage(message, params);
3146 VerifyMessage(message, signature, params);
3147}
3148
3149/*
3150 * ImportKeyTest.EcdsaP256SEC1Success
3151 *
3152 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3153 */
3154TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3155 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3156 .Authorization(TAG_NO_AUTH_REQUIRED)
3157 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003158 .Digest(Digest::SHA_2_256)
3159 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003160 KeyFormat::PKCS8, ec_256_key_sec1));
3161
3162 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3163 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3164 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3165 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3166
3167 CheckOrigin();
3168
3169 string message(32, 'a');
3170 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3171 string signature = SignMessage(message, params);
3172 VerifyMessage(message, signature, params);
3173}
3174
3175/*
3176 * ImportKeyTest.Ecdsa521Success
3177 *
3178 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3179 */
3180TEST_P(ImportKeyTest, Ecdsa521Success) {
3181 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3182 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3183 .Authorization(TAG_NO_AUTH_REQUIRED)
3184 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003185 .Digest(Digest::SHA_2_256)
3186 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003187 KeyFormat::PKCS8, ec_521_key));
3188
3189 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3190 CheckCryptoParam(TAG_KEY_SIZE, 521U);
3191 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3192 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3193 CheckOrigin();
3194
3195 string message(32, 'a');
3196 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3197 string signature = SignMessage(message, params);
3198 VerifyMessage(message, signature, params);
3199}
3200
3201/*
3202 * ImportKeyTest.EcdsaSizeMismatch
3203 *
3204 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
3205 * correct way.
3206 */
3207TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
3208 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3209 ImportKey(AuthorizationSetBuilder()
3210 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003211 .Digest(Digest::NONE)
3212 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003213 KeyFormat::PKCS8, ec_256_key));
3214}
3215
3216/*
3217 * ImportKeyTest.EcdsaCurveMismatch
3218 *
3219 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3220 * the correct way.
3221 */
3222TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3223 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3224 ImportKey(AuthorizationSetBuilder()
3225 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003226 .Digest(Digest::NONE)
3227 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003228 KeyFormat::PKCS8, ec_256_key));
3229}
3230
3231/*
3232 * ImportKeyTest.AesSuccess
3233 *
3234 * Verifies that importing and using an AES key works.
3235 */
3236TEST_P(ImportKeyTest, AesSuccess) {
3237 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3238 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .AesEncryptionKey(key.size() * 8)
3241 .EcbMode()
3242 .Padding(PaddingMode::PKCS7),
3243 KeyFormat::RAW, key));
3244
3245 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3246 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3247 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3248 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3249 CheckOrigin();
3250
3251 string message = "Hello World!";
3252 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3253 string ciphertext = EncryptMessage(message, params);
3254 string plaintext = DecryptMessage(ciphertext, params);
3255 EXPECT_EQ(message, plaintext);
3256}
3257
3258/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003259 * ImportKeyTest.AesFailure
3260 *
3261 * Verifies that importing an invalid AES key fails.
3262 */
3263TEST_P(ImportKeyTest, AesFailure) {
3264 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3265 uint32_t bitlen = key.size() * 8;
3266 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003267 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003268 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003269 .Authorization(TAG_NO_AUTH_REQUIRED)
3270 .AesEncryptionKey(key_size)
3271 .EcbMode()
3272 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003273 KeyFormat::RAW, key);
3274 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003275 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3276 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003277 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003278
3279 // Explicit key size matches that of the provided key, but it's not a valid size.
3280 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3281 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3282 ImportKey(AuthorizationSetBuilder()
3283 .Authorization(TAG_NO_AUTH_REQUIRED)
3284 .AesEncryptionKey(long_key.size() * 8)
3285 .EcbMode()
3286 .Padding(PaddingMode::PKCS7),
3287 KeyFormat::RAW, long_key));
3288 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3289 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3290 ImportKey(AuthorizationSetBuilder()
3291 .Authorization(TAG_NO_AUTH_REQUIRED)
3292 .AesEncryptionKey(short_key.size() * 8)
3293 .EcbMode()
3294 .Padding(PaddingMode::PKCS7),
3295 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003296}
3297
3298/*
3299 * ImportKeyTest.TripleDesSuccess
3300 *
3301 * Verifies that importing and using a 3DES key works.
3302 */
3303TEST_P(ImportKeyTest, TripleDesSuccess) {
3304 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3305 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3306 .Authorization(TAG_NO_AUTH_REQUIRED)
3307 .TripleDesEncryptionKey(168)
3308 .EcbMode()
3309 .Padding(PaddingMode::PKCS7),
3310 KeyFormat::RAW, key));
3311
3312 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3313 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3314 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3315 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3316 CheckOrigin();
3317
3318 string message = "Hello World!";
3319 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3320 string ciphertext = EncryptMessage(message, params);
3321 string plaintext = DecryptMessage(ciphertext, params);
3322 EXPECT_EQ(message, plaintext);
3323}
3324
3325/*
3326 * ImportKeyTest.TripleDesFailure
3327 *
3328 * Verifies that importing an invalid 3DES key fails.
3329 */
3330TEST_P(ImportKeyTest, TripleDesFailure) {
3331 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3332 uint32_t bitlen = key.size() * 8;
3333 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003334 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003335 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003336 .Authorization(TAG_NO_AUTH_REQUIRED)
3337 .TripleDesEncryptionKey(key_size)
3338 .EcbMode()
3339 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003340 KeyFormat::RAW, key);
3341 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003342 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3343 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003344 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003345 // Explicit key size matches that of the provided key, but it's not a valid size.
3346 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3347 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3348 ImportKey(AuthorizationSetBuilder()
3349 .Authorization(TAG_NO_AUTH_REQUIRED)
3350 .TripleDesEncryptionKey(long_key.size() * 8)
3351 .EcbMode()
3352 .Padding(PaddingMode::PKCS7),
3353 KeyFormat::RAW, long_key));
3354 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3355 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3356 ImportKey(AuthorizationSetBuilder()
3357 .Authorization(TAG_NO_AUTH_REQUIRED)
3358 .TripleDesEncryptionKey(short_key.size() * 8)
3359 .EcbMode()
3360 .Padding(PaddingMode::PKCS7),
3361 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003362}
3363
3364/*
3365 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003366 *
3367 * Verifies that importing and using an HMAC key works.
3368 */
3369TEST_P(ImportKeyTest, HmacKeySuccess) {
3370 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3371 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3372 .Authorization(TAG_NO_AUTH_REQUIRED)
3373 .HmacKey(key.size() * 8)
3374 .Digest(Digest::SHA_2_256)
3375 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3376 KeyFormat::RAW, key));
3377
3378 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3379 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3380 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3381 CheckOrigin();
3382
3383 string message = "Hello World!";
3384 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3385 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3386}
3387
3388INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3389
3390auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003391 // IKeyMintDevice.aidl
3392 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3393 "020100" // INTEGER length 1 value 0x00 (version)
3394 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3395 "934bf94e2aa28a3f83c9f79297250262"
3396 "fbe3276b5a1c91159bbfa3ef8957aac8"
3397 "4b59b30b455a79c2973480823d8b3863"
3398 "c3deef4a8e243590268d80e18751a0e1"
3399 "30f67ce6a1ace9f79b95e097474febc9"
3400 "81195b1d13a69086c0863f66a7b7fdb4"
3401 "8792227b1ac5e2489febdf087ab54864"
3402 "83033a6f001ca5d1ec1e27f5c30f4cec"
3403 "2642074a39ae68aee552e196627a8e3d"
3404 "867e67a8c01b11e75f13cca0a97ab668"
3405 "b50cda07a8ecb7cd8e3dd7009c963653"
3406 "4f6f239cffe1fc8daa466f78b676c711"
3407 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3408 "99b801597d5220e307eaa5bee507fb94"
3409 "d1fa69f9e519b2de315bac92c36f2ea1"
3410 "fa1df4478c0ddedeae8c70e0233cd098"
3411 "040c" // OCTET STRING length 0x0c (initializationVector)
3412 "d796b02c370f1fa4cc0124f1"
3413 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3414 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3415 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3416 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3417 "3106" // SET length 0x06
3418 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3419 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3420 // } end SET
3421 // } end [1]
3422 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3423 "020120" // INTEGER length 1 value 0x20 (AES)
3424 // } end [2]
3425 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3426 "02020100" // INTEGER length 2 value 0x100
3427 // } end [3]
3428 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3429 "3103" // SET length 0x03 {
3430 "020101" // INTEGER length 1 value 0x01 (ECB)
3431 // } end SET
3432 // } end [4]
3433 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3434 "3103" // SET length 0x03 {
3435 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3436 // } end SET
3437 // } end [5]
3438 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3439 // (noAuthRequired)
3440 "0500" // NULL
3441 // } end [503]
3442 // } end SEQUENCE (AuthorizationList)
3443 // } end SEQUENCE (KeyDescription)
3444 "0420" // OCTET STRING length 0x20 (encryptedKey)
3445 "ccd540855f833a5e1480bfd2d36faf3a"
3446 "eee15df5beabe2691bc82dde2a7aa910"
3447 "0410" // OCTET STRING length 0x10 (tag)
3448 "64c9f689c60ff6223ab6e6999e0eb6e5"
3449 // } SEQUENCE (SecureKeyWrapper)
3450);
Selene Huang31ab4042020-04-29 04:22:39 -07003451
3452auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003453 // IKeyMintDevice.aidl
3454 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3455 "020100" // INTEGER length 1 value 0x00 (version)
3456 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3457 "aad93ed5924f283b4bb5526fbe7a1412"
3458 "f9d9749ec30db9062b29e574a8546f33"
3459 "c88732452f5b8e6a391ee76c39ed1712"
3460 "c61d8df6213dec1cffbc17a8c6d04c7b"
3461 "30893d8daa9b2015213e219468215532"
3462 "07f8f9931c4caba23ed3bee28b36947e"
3463 "47f10e0a5c3dc51c988a628daad3e5e1"
3464 "f4005e79c2d5a96c284b4b8d7e4948f3"
3465 "31e5b85dd5a236f85579f3ea1d1b8484"
3466 "87470bdb0ab4f81a12bee42c99fe0df4"
3467 "bee3759453e69ad1d68a809ce06b949f"
3468 "7694a990429b2fe81e066ff43e56a216"
3469 "02db70757922a4bcc23ab89f1e35da77"
3470 "586775f423e519c2ea394caf48a28d0c"
3471 "8020f1dcf6b3a68ec246f615ae96dae9"
3472 "a079b1f6eb959033c1af5c125fd94168"
3473 "040c" // OCTET STRING length 0x0c (initializationVector)
3474 "6d9721d08589581ab49204a3"
3475 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3476 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3477 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3478 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3479 "3106" // SET length 0x06
3480 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3481 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3482 // } end SET
3483 // } end [1]
3484 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3485 "020120" // INTEGER length 1 value 0x20 (AES)
3486 // } end [2]
3487 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3488 "02020100" // INTEGER length 2 value 0x100
3489 // } end [3]
3490 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3491 "3103" // SET length 0x03 {
3492 "020101" // INTEGER length 1 value 0x01 (ECB)
3493 // } end SET
3494 // } end [4]
3495 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3496 "3103" // SET length 0x03 {
3497 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3498 // } end SET
3499 // } end [5]
3500 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3501 // (noAuthRequired)
3502 "0500" // NULL
3503 // } end [503]
3504 // } end SEQUENCE (AuthorizationList)
3505 // } end SEQUENCE (KeyDescription)
3506 "0420" // OCTET STRING length 0x20 (encryptedKey)
3507 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3508 "c20d1f99a9a024a76f35c8e2cab9b68d"
3509 "0410" // OCTET STRING length 0x10 (tag)
3510 "2560c70109ae67c030f00b98b512a670"
3511 // } SEQUENCE (SecureKeyWrapper)
3512);
Selene Huang31ab4042020-04-29 04:22:39 -07003513
3514auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003515 // RFC 5208 s5
3516 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3517 "020100" // INTEGER length 1 value 0x00 (version)
3518 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3519 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3520 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3521 "0500" // NULL (parameters)
3522 // } SEQUENCE (AlgorithmIdentifier)
3523 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3524 // RFC 8017 A.1.2
3525 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3526 "020100" // INTEGER length 1 value 0x00 (version)
3527 "02820101" // INTEGER length 0x0101 (modulus) value...
3528 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3529 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3530 "7b06e673a837313d56b1c725150a3fef" // 0x30
3531 "86acbddc41bb759c2854eae32d35841e" // 0x40
3532 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3533 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3534 "312d7bd5921ffaea1347c157406fef71" // 0x70
3535 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3536 "f4645c11f5c1374c3886427411c44979" // 0x90
3537 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3538 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3539 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3540 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3541 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3542 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3543 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3544 "55" // 0x101
3545 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3546 "02820100" // INTEGER length 0x100 (privateExponent) value...
3547 "431447b6251908112b1ee76f99f3711a" // 0x10
3548 "52b6630960046c2de70de188d833f8b8" // 0x20
3549 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3550 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3551 "e710b630a03adc683b5d2c43080e52be" // 0x50
3552 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3553 "822bccff087d63c940ba8a45f670feb2" // 0x70
3554 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3555 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3556 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3557 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3558 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3559 "52659d5a5ba05b663737a8696281865b" // 0xd0
3560 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3561 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3562 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3563 "028181" // INTEGER length 0x81 (prime1) value...
3564 "00de392e18d682c829266cc3454e1d61" // 0x10
3565 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3566 "ff841be5bac82a164c5970007047b8c5" // 0x30
3567 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3568 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3569 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3570 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3571 "9e91346130748a6e3c124f9149d71c74" // 0x80
3572 "35"
3573 "028181" // INTEGER length 0x81 (prime2) value...
3574 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3575 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3576 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3577 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3578 "9ed39a2d934c880440aed8832f984316" // 0x50
3579 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3580 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3581 "b880677c068e1be936e81288815252a8" // 0x80
3582 "a1"
3583 "028180" // INTEGER length 0x80 (exponent1) value...
3584 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3585 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3586 "5a063212a4f105a3764743e53281988a" // 0x30
3587 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3588 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3589 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3590 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3591 "4719d6e2b9439823719cd08bcd031781" // 0x80
3592 "028181" // INTEGER length 0x81 (exponent2) value...
3593 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3594 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3595 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3596 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3597 "1254186af30b22c10582a8a43e34fe94" // 0x50
3598 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3599 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3600 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3601 "61"
3602 "028181" // INTEGER length 0x81 (coefficient) value...
3603 "00c931617c77829dfb1270502be9195c" // 0x10
3604 "8f2830885f57dba869536811e6864236" // 0x20
3605 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3606 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3607 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3608 "959356210723287b0affcc9f727044d4" // 0x60
3609 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3610 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3611 "22"
3612 // } SEQUENCE
3613 // } SEQUENCE ()
3614);
Selene Huang31ab4042020-04-29 04:22:39 -07003615
3616string zero_masking_key =
3617 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3618string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3619
3620class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3621
3622TEST_P(ImportWrappedKeyTest, Success) {
3623 auto wrapping_key_desc = AuthorizationSetBuilder()
3624 .RsaEncryptionKey(2048, 65537)
3625 .Digest(Digest::SHA_2_256)
3626 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003627 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3628 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003629
3630 ASSERT_EQ(ErrorCode::OK,
3631 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3632 AuthorizationSetBuilder()
3633 .Digest(Digest::SHA_2_256)
3634 .Padding(PaddingMode::RSA_OAEP)));
3635
3636 string message = "Hello World!";
3637 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3638 string ciphertext = EncryptMessage(message, params);
3639 string plaintext = DecryptMessage(ciphertext, params);
3640 EXPECT_EQ(message, plaintext);
3641}
3642
David Drysdaled2cc8c22021-04-15 13:29:45 +01003643/*
3644 * ImportWrappedKeyTest.SuccessSidsIgnored
3645 *
3646 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3647 * include Tag:USER_SECURE_ID.
3648 */
3649TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3650 auto wrapping_key_desc = AuthorizationSetBuilder()
3651 .RsaEncryptionKey(2048, 65537)
3652 .Digest(Digest::SHA_2_256)
3653 .Padding(PaddingMode::RSA_OAEP)
3654 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3655 .SetDefaultValidity();
3656
3657 int64_t password_sid = 42;
3658 int64_t biometric_sid = 24;
3659 ASSERT_EQ(ErrorCode::OK,
3660 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3661 AuthorizationSetBuilder()
3662 .Digest(Digest::SHA_2_256)
3663 .Padding(PaddingMode::RSA_OAEP),
3664 password_sid, biometric_sid));
3665
3666 string message = "Hello World!";
3667 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3668 string ciphertext = EncryptMessage(message, params);
3669 string plaintext = DecryptMessage(ciphertext, params);
3670 EXPECT_EQ(message, plaintext);
3671}
3672
Selene Huang31ab4042020-04-29 04:22:39 -07003673TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3674 auto wrapping_key_desc = AuthorizationSetBuilder()
3675 .RsaEncryptionKey(2048, 65537)
3676 .Digest(Digest::SHA_2_256)
3677 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003678 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3679 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003680
3681 ASSERT_EQ(ErrorCode::OK,
3682 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3683 AuthorizationSetBuilder()
3684 .Digest(Digest::SHA_2_256)
3685 .Padding(PaddingMode::RSA_OAEP)));
3686}
3687
3688TEST_P(ImportWrappedKeyTest, WrongMask) {
3689 auto wrapping_key_desc = AuthorizationSetBuilder()
3690 .RsaEncryptionKey(2048, 65537)
3691 .Digest(Digest::SHA_2_256)
3692 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003693 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3694 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003695
3696 ASSERT_EQ(
3697 ErrorCode::VERIFICATION_FAILED,
3698 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3699 AuthorizationSetBuilder()
3700 .Digest(Digest::SHA_2_256)
3701 .Padding(PaddingMode::RSA_OAEP)));
3702}
3703
3704TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3705 auto wrapping_key_desc = AuthorizationSetBuilder()
3706 .RsaEncryptionKey(2048, 65537)
3707 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003708 .Padding(PaddingMode::RSA_OAEP)
3709 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003710
3711 ASSERT_EQ(
3712 ErrorCode::INCOMPATIBLE_PURPOSE,
3713 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3714 AuthorizationSetBuilder()
3715 .Digest(Digest::SHA_2_256)
3716 .Padding(PaddingMode::RSA_OAEP)));
3717}
3718
David Drysdaled2cc8c22021-04-15 13:29:45 +01003719TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3720 auto wrapping_key_desc = AuthorizationSetBuilder()
3721 .RsaEncryptionKey(2048, 65537)
3722 .Digest(Digest::SHA_2_256)
3723 .Padding(PaddingMode::RSA_PSS)
3724 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3725 .SetDefaultValidity();
3726
3727 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3728 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3729 AuthorizationSetBuilder()
3730 .Digest(Digest::SHA_2_256)
3731 .Padding(PaddingMode::RSA_OAEP)));
3732}
3733
3734TEST_P(ImportWrappedKeyTest, WrongDigest) {
3735 auto wrapping_key_desc = AuthorizationSetBuilder()
3736 .RsaEncryptionKey(2048, 65537)
3737 .Digest(Digest::SHA_2_512)
3738 .Padding(PaddingMode::RSA_OAEP)
3739 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3740 .SetDefaultValidity();
3741
3742 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3743 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3744 AuthorizationSetBuilder()
3745 .Digest(Digest::SHA_2_256)
3746 .Padding(PaddingMode::RSA_OAEP)));
3747}
3748
Selene Huang31ab4042020-04-29 04:22:39 -07003749INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3750
3751typedef KeyMintAidlTestBase EncryptionOperationsTest;
3752
3753/*
3754 * EncryptionOperationsTest.RsaNoPaddingSuccess
3755 *
3756 * Verifies that raw RSA encryption works.
3757 */
3758TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003759 for (uint64_t exponent : {3, 65537}) {
3760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3761 .Authorization(TAG_NO_AUTH_REQUIRED)
3762 .RsaEncryptionKey(2048, exponent)
3763 .Padding(PaddingMode::NONE)
3764 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003765
David Drysdaled2cc8c22021-04-15 13:29:45 +01003766 string message = string(2048 / 8, 'a');
3767 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3768 string ciphertext1 = EncryptMessage(message, params);
3769 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003770
David Drysdaled2cc8c22021-04-15 13:29:45 +01003771 string ciphertext2 = EncryptMessage(message, params);
3772 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003773
David Drysdaled2cc8c22021-04-15 13:29:45 +01003774 // Unpadded RSA is deterministic
3775 EXPECT_EQ(ciphertext1, ciphertext2);
3776
3777 CheckedDeleteKey();
3778 }
Selene Huang31ab4042020-04-29 04:22:39 -07003779}
3780
3781/*
3782 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3783 *
3784 * Verifies that raw RSA encryption of short messages works.
3785 */
3786TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3788 .Authorization(TAG_NO_AUTH_REQUIRED)
3789 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003790 .Padding(PaddingMode::NONE)
3791 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003792
3793 string message = "1";
3794 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3795
3796 string ciphertext = EncryptMessage(message, params);
3797 EXPECT_EQ(2048U / 8, ciphertext.size());
3798
3799 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3800 string plaintext = DecryptMessage(ciphertext, params);
3801
3802 EXPECT_EQ(expected_plaintext, plaintext);
3803
3804 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3805 message = static_cast<char>(1);
3806 ciphertext = EncryptMessage(message, params);
3807 EXPECT_EQ(2048U / 8, ciphertext.size());
3808 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3809}
3810
3811/*
3812 * EncryptionOperationsTest.RsaNoPaddingTooLong
3813 *
3814 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3815 */
3816TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3818 .Authorization(TAG_NO_AUTH_REQUIRED)
3819 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003820 .Padding(PaddingMode::NONE)
3821 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003822
3823 string message(2048 / 8 + 1, 'a');
3824
3825 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3826 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3827
3828 string result;
3829 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3830}
3831
3832/*
3833 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3834 *
3835 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3836 * way.
3837 */
3838// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3839// version of ExportKey inside generateKey
3840
3841/*
3842 * EncryptionOperationsTest.RsaOaepSuccess
3843 *
3844 * Verifies that RSA-OAEP encryption operations work, with all digests.
3845 */
3846TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3847 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3848
3849 size_t key_size = 2048; // Need largish key for SHA-512 test.
3850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3851 .Authorization(TAG_NO_AUTH_REQUIRED)
3852 .RsaEncryptionKey(key_size, 65537)
3853 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003854 .Digest(digests)
3855 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003856
3857 string message = "Hello";
3858
3859 for (auto digest : digests) {
3860 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3861 string ciphertext1 = EncryptMessage(message, params);
3862 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3863 EXPECT_EQ(key_size / 8, ciphertext1.size());
3864
3865 string ciphertext2 = EncryptMessage(message, params);
3866 EXPECT_EQ(key_size / 8, ciphertext2.size());
3867
3868 // OAEP randomizes padding so every result should be different (with astronomically high
3869 // probability).
3870 EXPECT_NE(ciphertext1, ciphertext2);
3871
3872 string plaintext1 = DecryptMessage(ciphertext1, params);
3873 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3874 string plaintext2 = DecryptMessage(ciphertext2, params);
3875 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3876
3877 // Decrypting corrupted ciphertext should fail.
3878 size_t offset_to_corrupt = random() % ciphertext1.size();
3879 char corrupt_byte;
3880 do {
3881 corrupt_byte = static_cast<char>(random() % 256);
3882 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3883 ciphertext1[offset_to_corrupt] = corrupt_byte;
3884
3885 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3886 string result;
3887 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3888 EXPECT_EQ(0U, result.size());
3889 }
3890}
3891
3892/*
3893 * EncryptionOperationsTest.RsaOaepInvalidDigest
3894 *
3895 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3896 * without a digest.
3897 */
3898TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3899 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3900 .Authorization(TAG_NO_AUTH_REQUIRED)
3901 .RsaEncryptionKey(2048, 65537)
3902 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003903 .Digest(Digest::NONE)
3904 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003905
3906 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3907 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3908}
3909
3910/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003911 * EncryptionOperationsTest.RsaOaepInvalidPadding
3912 *
3913 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3914 * with a padding value that is only suitable for signing/verifying.
3915 */
3916TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3918 .Authorization(TAG_NO_AUTH_REQUIRED)
3919 .RsaEncryptionKey(2048, 65537)
3920 .Padding(PaddingMode::RSA_PSS)
3921 .Digest(Digest::NONE)
3922 .SetDefaultValidity()));
3923
3924 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
3925 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3926}
3927
3928/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003929 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003930 *
3931 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3932 * with a different digest than was used to encrypt.
3933 */
3934TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3935 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3936
3937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3938 .Authorization(TAG_NO_AUTH_REQUIRED)
3939 .RsaEncryptionKey(1024, 65537)
3940 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003941 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3942 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003943 string message = "Hello World!";
3944 string ciphertext = EncryptMessage(
3945 message,
3946 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3947
3948 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3949 .Digest(Digest::SHA_2_256)
3950 .Padding(PaddingMode::RSA_OAEP)));
3951 string result;
3952 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3953 EXPECT_EQ(0U, result.size());
3954}
3955
3956/*
3957 * EncryptionOperationsTest.RsaOaepTooLarge
3958 *
3959 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3960 * too-large message.
3961 */
3962TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3964 .Authorization(TAG_NO_AUTH_REQUIRED)
3965 .RsaEncryptionKey(2048, 65537)
3966 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003967 .Digest(Digest::SHA_2_256)
3968 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003969 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3970 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3971 string message(2048 / 8 - oaep_overhead + 1, 'a');
3972 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3973 .Padding(PaddingMode::RSA_OAEP)
3974 .Digest(Digest::SHA_2_256)));
3975 string result;
3976 ErrorCode error = Finish(message, &result);
3977 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3978 EXPECT_EQ(0U, result.size());
3979}
3980
3981/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003982 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3983 *
3984 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3985 * digests.
3986 */
3987TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3988 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3989
3990 size_t key_size = 2048; // Need largish key for SHA-512 test.
3991 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3992 .OaepMGFDigest(digests)
3993 .Authorization(TAG_NO_AUTH_REQUIRED)
3994 .RsaEncryptionKey(key_size, 65537)
3995 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003996 .Digest(Digest::SHA_2_256)
3997 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003998
3999 string message = "Hello";
4000
4001 for (auto digest : digests) {
4002 auto params = AuthorizationSetBuilder()
4003 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4004 .Digest(Digest::SHA_2_256)
4005 .Padding(PaddingMode::RSA_OAEP);
4006 string ciphertext1 = EncryptMessage(message, params);
4007 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4008 EXPECT_EQ(key_size / 8, ciphertext1.size());
4009
4010 string ciphertext2 = EncryptMessage(message, params);
4011 EXPECT_EQ(key_size / 8, ciphertext2.size());
4012
4013 // OAEP randomizes padding so every result should be different (with astronomically high
4014 // probability).
4015 EXPECT_NE(ciphertext1, ciphertext2);
4016
4017 string plaintext1 = DecryptMessage(ciphertext1, params);
4018 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4019 string plaintext2 = DecryptMessage(ciphertext2, params);
4020 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4021
4022 // Decrypting corrupted ciphertext should fail.
4023 size_t offset_to_corrupt = random() % ciphertext1.size();
4024 char corrupt_byte;
4025 do {
4026 corrupt_byte = static_cast<char>(random() % 256);
4027 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4028 ciphertext1[offset_to_corrupt] = corrupt_byte;
4029
4030 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4031 string result;
4032 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4033 EXPECT_EQ(0U, result.size());
4034 }
4035}
4036
4037/*
4038 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4039 *
4040 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4041 * with incompatible MGF digest.
4042 */
4043TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4044 ASSERT_EQ(ErrorCode::OK,
4045 GenerateKey(AuthorizationSetBuilder()
4046 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4047 .Authorization(TAG_NO_AUTH_REQUIRED)
4048 .RsaEncryptionKey(2048, 65537)
4049 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004050 .Digest(Digest::SHA_2_256)
4051 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004052 string message = "Hello World!";
4053
4054 auto params = AuthorizationSetBuilder()
4055 .Padding(PaddingMode::RSA_OAEP)
4056 .Digest(Digest::SHA_2_256)
4057 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
4058 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
4059}
4060
4061/*
4062 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4063 *
4064 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4065 * with unsupported MGF digest.
4066 */
4067TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4068 ASSERT_EQ(ErrorCode::OK,
4069 GenerateKey(AuthorizationSetBuilder()
4070 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4071 .Authorization(TAG_NO_AUTH_REQUIRED)
4072 .RsaEncryptionKey(2048, 65537)
4073 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004074 .Digest(Digest::SHA_2_256)
4075 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004076 string message = "Hello World!";
4077
4078 auto params = AuthorizationSetBuilder()
4079 .Padding(PaddingMode::RSA_OAEP)
4080 .Digest(Digest::SHA_2_256)
4081 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
4082 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
4083}
4084
4085/*
Selene Huang31ab4042020-04-29 04:22:39 -07004086 * EncryptionOperationsTest.RsaPkcs1Success
4087 *
4088 * Verifies that RSA PKCS encryption/decrypts works.
4089 */
4090TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
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
4097 string message = "Hello World!";
4098 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
4099 string ciphertext1 = EncryptMessage(message, params);
4100 EXPECT_EQ(2048U / 8, ciphertext1.size());
4101
4102 string ciphertext2 = EncryptMessage(message, params);
4103 EXPECT_EQ(2048U / 8, ciphertext2.size());
4104
4105 // PKCS1 v1.5 randomizes padding so every result should be different.
4106 EXPECT_NE(ciphertext1, ciphertext2);
4107
4108 string plaintext = DecryptMessage(ciphertext1, params);
4109 EXPECT_EQ(message, plaintext);
4110
4111 // Decrypting corrupted ciphertext should fail.
4112 size_t offset_to_corrupt = random() % ciphertext1.size();
4113 char corrupt_byte;
4114 do {
4115 corrupt_byte = static_cast<char>(random() % 256);
4116 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4117 ciphertext1[offset_to_corrupt] = corrupt_byte;
4118
4119 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4120 string result;
4121 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4122 EXPECT_EQ(0U, result.size());
4123}
4124
4125/*
4126 * EncryptionOperationsTest.RsaPkcs1TooLarge
4127 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01004128 * Verifies that RSA PKCS encryption fails in the correct way when the message is too large.
Selene Huang31ab4042020-04-29 04:22:39 -07004129 */
4130TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
4131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4132 .Authorization(TAG_NO_AUTH_REQUIRED)
4133 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004134 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4135 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004136 string message(2048 / 8 - 10, 'a');
4137
4138 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
4139 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4140 string result;
4141 ErrorCode error = Finish(message, &result);
4142 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
4143 EXPECT_EQ(0U, result.size());
4144}
4145
4146/*
4147 * EncryptionOperationsTest.EcdsaEncrypt
4148 *
4149 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4150 */
4151TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4153 .Authorization(TAG_NO_AUTH_REQUIRED)
4154 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004155 .Digest(Digest::NONE)
4156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004157 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4158 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4159 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4160}
4161
4162/*
4163 * EncryptionOperationsTest.HmacEncrypt
4164 *
4165 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4166 */
4167TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4168 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
4170 .HmacKey(128)
4171 .Digest(Digest::SHA_2_256)
4172 .Padding(PaddingMode::NONE)
4173 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4174 auto params = AuthorizationSetBuilder()
4175 .Digest(Digest::SHA_2_256)
4176 .Padding(PaddingMode::NONE)
4177 .Authorization(TAG_MAC_LENGTH, 128);
4178 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4179 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4180}
4181
4182/*
4183 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4184 *
4185 * Verifies that AES ECB mode works.
4186 */
4187TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4189 .Authorization(TAG_NO_AUTH_REQUIRED)
4190 .AesEncryptionKey(128)
4191 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4192 .Padding(PaddingMode::NONE)));
4193
4194 ASSERT_GT(key_blob_.size(), 0U);
4195 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4196
4197 // Two-block message.
4198 string message = "12345678901234567890123456789012";
4199 string ciphertext1 = EncryptMessage(message, params);
4200 EXPECT_EQ(message.size(), ciphertext1.size());
4201
4202 string ciphertext2 = EncryptMessage(string(message), params);
4203 EXPECT_EQ(message.size(), ciphertext2.size());
4204
4205 // ECB is deterministic.
4206 EXPECT_EQ(ciphertext1, ciphertext2);
4207
4208 string plaintext = DecryptMessage(ciphertext1, params);
4209 EXPECT_EQ(message, plaintext);
4210}
4211
4212/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004213 * EncryptionOperationsTest.AesEcbUnknownTag
4214 *
4215 * Verifies that AES ECB operations ignore unknown tags.
4216 */
4217TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4218 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4219 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4220 KeyParameter unknown_param;
4221 unknown_param.tag = unknown_tag;
4222
4223 vector<KeyCharacteristics> key_characteristics;
4224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4225 .Authorization(TAG_NO_AUTH_REQUIRED)
4226 .AesEncryptionKey(128)
4227 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4228 .Padding(PaddingMode::NONE)
4229 .Authorization(unknown_param),
4230 &key_blob_, &key_characteristics));
4231 ASSERT_GT(key_blob_.size(), 0U);
4232
4233 // Unknown tags should not be returned in key characteristics.
4234 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4235 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4236 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4237 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4238
4239 // Encrypt without mentioning the unknown parameter.
4240 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4241 string message = "12345678901234567890123456789012";
4242 string ciphertext = EncryptMessage(message, params);
4243 EXPECT_EQ(message.size(), ciphertext.size());
4244
4245 // Decrypt including the unknown parameter.
4246 auto decrypt_params = AuthorizationSetBuilder()
4247 .BlockMode(BlockMode::ECB)
4248 .Padding(PaddingMode::NONE)
4249 .Authorization(unknown_param);
4250 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4251 EXPECT_EQ(message, plaintext);
4252}
4253
4254/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004255 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004256 *
4257 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4258 */
4259TEST_P(EncryptionOperationsTest, AesWrongMode) {
4260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4261 .Authorization(TAG_NO_AUTH_REQUIRED)
4262 .AesEncryptionKey(128)
4263 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4264 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004265 ASSERT_GT(key_blob_.size(), 0U);
4266
Selene Huang31ab4042020-04-29 04:22:39 -07004267 EXPECT_EQ(
4268 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4269 Begin(KeyPurpose::ENCRYPT,
4270 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4271}
4272
4273/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004274 * EncryptionOperationsTest.AesWrongPadding
4275 *
4276 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4277 */
4278TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4280 .Authorization(TAG_NO_AUTH_REQUIRED)
4281 .AesEncryptionKey(128)
4282 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4283 .Padding(PaddingMode::NONE)));
4284 ASSERT_GT(key_blob_.size(), 0U);
4285
4286 EXPECT_EQ(
4287 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4288 Begin(KeyPurpose::ENCRYPT,
4289 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4290}
4291
4292/*
4293 * EncryptionOperationsTest.AesInvalidParams
4294 *
4295 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4296 */
4297TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4299 .Authorization(TAG_NO_AUTH_REQUIRED)
4300 .AesEncryptionKey(128)
4301 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4302 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4303 .Padding(PaddingMode::NONE)
4304 .Padding(PaddingMode::PKCS7)));
4305 ASSERT_GT(key_blob_.size(), 0U);
4306
4307 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4308 .BlockMode(BlockMode::CBC)
4309 .BlockMode(BlockMode::ECB)
4310 .Padding(PaddingMode::NONE));
4311 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4312 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4313
4314 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4315 .BlockMode(BlockMode::ECB)
4316 .Padding(PaddingMode::NONE)
4317 .Padding(PaddingMode::PKCS7));
4318 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4319 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4320}
4321
4322/*
Selene Huang31ab4042020-04-29 04:22:39 -07004323 * EncryptionOperationsTest.AesWrongPurpose
4324 *
4325 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4326 * specified.
4327 */
4328TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4329 auto err = GenerateKey(AuthorizationSetBuilder()
4330 .Authorization(TAG_NO_AUTH_REQUIRED)
4331 .AesKey(128)
4332 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4333 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4334 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4335 .Padding(PaddingMode::NONE));
4336 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4337 ASSERT_GT(key_blob_.size(), 0U);
4338
4339 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4340 .BlockMode(BlockMode::GCM)
4341 .Padding(PaddingMode::NONE)
4342 .Authorization(TAG_MAC_LENGTH, 128));
4343 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4344
4345 CheckedDeleteKey();
4346
4347 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4348 .Authorization(TAG_NO_AUTH_REQUIRED)
4349 .AesKey(128)
4350 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4351 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4352 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4353 .Padding(PaddingMode::NONE)));
4354
4355 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4356 .BlockMode(BlockMode::GCM)
4357 .Padding(PaddingMode::NONE)
4358 .Authorization(TAG_MAC_LENGTH, 128));
4359 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4360}
4361
4362/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004363 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004364 *
4365 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4366 * multiple of the block size and no padding is specified.
4367 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004368TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4369 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4371 .Authorization(TAG_NO_AUTH_REQUIRED)
4372 .AesEncryptionKey(128)
4373 .Authorization(TAG_BLOCK_MODE, blockMode)
4374 .Padding(PaddingMode::NONE)));
4375 // Message is slightly shorter than two blocks.
4376 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004377
David Drysdaled2cc8c22021-04-15 13:29:45 +01004378 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4379 AuthorizationSet out_params;
4380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4381 string ciphertext;
4382 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4383 EXPECT_EQ(0U, ciphertext.size());
4384
4385 CheckedDeleteKey();
4386 }
Selene Huang31ab4042020-04-29 04:22:39 -07004387}
4388
4389/*
4390 * EncryptionOperationsTest.AesEcbPkcs7Padding
4391 *
4392 * Verifies that AES PKCS7 padding works for any message length.
4393 */
4394TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(128)
4398 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4399 .Padding(PaddingMode::PKCS7)));
4400
4401 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4402
4403 // Try various message lengths; all should work.
4404 for (size_t i = 0; i < 32; ++i) {
4405 string message(i, 'a');
4406 string ciphertext = EncryptMessage(message, params);
4407 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4408 string plaintext = DecryptMessage(ciphertext, params);
4409 EXPECT_EQ(message, plaintext);
4410 }
4411}
4412
4413/*
4414 * EncryptionOperationsTest.AesEcbWrongPadding
4415 *
4416 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4417 * specified.
4418 */
4419TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4421 .Authorization(TAG_NO_AUTH_REQUIRED)
4422 .AesEncryptionKey(128)
4423 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4424 .Padding(PaddingMode::NONE)));
4425
4426 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4427
4428 // Try various message lengths; all should fail
4429 for (size_t i = 0; i < 32; ++i) {
4430 string message(i, 'a');
4431 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4432 }
4433}
4434
4435/*
4436 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4437 *
4438 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4439 */
4440TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4441 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4442 .Authorization(TAG_NO_AUTH_REQUIRED)
4443 .AesEncryptionKey(128)
4444 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4445 .Padding(PaddingMode::PKCS7)));
4446
4447 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4448
4449 string message = "a";
4450 string ciphertext = EncryptMessage(message, params);
4451 EXPECT_EQ(16U, ciphertext.size());
4452 EXPECT_NE(ciphertext, message);
4453 ++ciphertext[ciphertext.size() / 2];
4454
4455 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4456 string plaintext;
4457 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4458}
4459
4460vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4461 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004462 EXPECT_TRUE(iv);
4463 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004464}
4465
4466/*
4467 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4468 *
4469 * Verifies that AES CTR mode works.
4470 */
4471TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4473 .Authorization(TAG_NO_AUTH_REQUIRED)
4474 .AesEncryptionKey(128)
4475 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4476 .Padding(PaddingMode::NONE)));
4477
4478 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4479
4480 string message = "123";
4481 AuthorizationSet out_params;
4482 string ciphertext1 = EncryptMessage(message, params, &out_params);
4483 vector<uint8_t> iv1 = CopyIv(out_params);
4484 EXPECT_EQ(16U, iv1.size());
4485
4486 EXPECT_EQ(message.size(), ciphertext1.size());
4487
4488 out_params.Clear();
4489 string ciphertext2 = EncryptMessage(message, params, &out_params);
4490 vector<uint8_t> iv2 = CopyIv(out_params);
4491 EXPECT_EQ(16U, iv2.size());
4492
4493 // IVs should be random, so ciphertexts should differ.
4494 EXPECT_NE(ciphertext1, ciphertext2);
4495
4496 auto params_iv1 =
4497 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4498 auto params_iv2 =
4499 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4500
4501 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4502 EXPECT_EQ(message, plaintext);
4503 plaintext = DecryptMessage(ciphertext2, params_iv2);
4504 EXPECT_EQ(message, plaintext);
4505
4506 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4507 plaintext = DecryptMessage(ciphertext1, params_iv2);
4508 EXPECT_NE(message, plaintext);
4509 plaintext = DecryptMessage(ciphertext2, params_iv1);
4510 EXPECT_NE(message, plaintext);
4511}
4512
4513/*
4514 * EncryptionOperationsTest.AesIncremental
4515 *
4516 * Verifies that AES works, all modes, when provided data in various size increments.
4517 */
4518TEST_P(EncryptionOperationsTest, AesIncremental) {
4519 auto block_modes = {
4520 BlockMode::ECB,
4521 BlockMode::CBC,
4522 BlockMode::CTR,
4523 BlockMode::GCM,
4524 };
4525
4526 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4527 .Authorization(TAG_NO_AUTH_REQUIRED)
4528 .AesEncryptionKey(128)
4529 .BlockMode(block_modes)
4530 .Padding(PaddingMode::NONE)
4531 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4532
4533 for (int increment = 1; increment <= 240; ++increment) {
4534 for (auto block_mode : block_modes) {
4535 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004536 auto params =
4537 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4538 if (block_mode == BlockMode::GCM) {
4539 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4540 }
Selene Huang31ab4042020-04-29 04:22:39 -07004541
4542 AuthorizationSet output_params;
4543 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4544
4545 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004546 string to_send;
4547 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004548 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004549 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004550 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4551 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004552
4553 switch (block_mode) {
4554 case BlockMode::GCM:
4555 EXPECT_EQ(message.size() + 16, ciphertext.size());
4556 break;
4557 case BlockMode::CTR:
4558 EXPECT_EQ(message.size(), ciphertext.size());
4559 break;
4560 case BlockMode::CBC:
4561 case BlockMode::ECB:
4562 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4563 break;
4564 }
4565
4566 auto iv = output_params.GetTagValue(TAG_NONCE);
4567 switch (block_mode) {
4568 case BlockMode::CBC:
4569 case BlockMode::GCM:
4570 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004571 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4572 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4573 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004574 break;
4575
4576 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004577 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004578 break;
4579 }
4580
4581 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4582 << "Decrypt begin() failed for block mode " << block_mode;
4583
4584 string plaintext;
4585 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004586 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004587 }
4588 ErrorCode error = Finish(to_send, &plaintext);
4589 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4590 << " and increment " << increment;
4591 if (error == ErrorCode::OK) {
4592 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4593 << block_mode << " and increment " << increment;
4594 }
4595 }
4596 }
4597}
4598
4599struct AesCtrSp80038aTestVector {
4600 const char* key;
4601 const char* nonce;
4602 const char* plaintext;
4603 const char* ciphertext;
4604};
4605
4606// These test vectors are taken from
4607// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4608static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4609 // AES-128
4610 {
4611 "2b7e151628aed2a6abf7158809cf4f3c",
4612 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4613 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4614 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4615 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4616 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4617 },
4618 // AES-192
4619 {
4620 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4621 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4622 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4623 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4624 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4625 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4626 },
4627 // AES-256
4628 {
4629 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4630 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4631 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4632 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4633 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4634 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4635 },
4636};
4637
4638/*
4639 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4640 *
4641 * Verifies AES CTR implementation against SP800-38A test vectors.
4642 */
4643TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4644 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4645 for (size_t i = 0; i < 3; i++) {
4646 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4647 const string key = hex2str(test.key);
4648 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4649 InvalidSizes.end())
4650 continue;
4651 const string nonce = hex2str(test.nonce);
4652 const string plaintext = hex2str(test.plaintext);
4653 const string ciphertext = hex2str(test.ciphertext);
4654 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4655 }
4656}
4657
4658/*
4659 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4660 *
4661 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4662 */
4663TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4664 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4665 .Authorization(TAG_NO_AUTH_REQUIRED)
4666 .AesEncryptionKey(128)
4667 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4668 .Padding(PaddingMode::PKCS7)));
4669 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4670 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4671}
4672
4673/*
4674 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4675 *
4676 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4677 */
4678TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4680 .Authorization(TAG_NO_AUTH_REQUIRED)
4681 .AesEncryptionKey(128)
4682 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4683 .Authorization(TAG_CALLER_NONCE)
4684 .Padding(PaddingMode::NONE)));
4685
4686 auto params = AuthorizationSetBuilder()
4687 .BlockMode(BlockMode::CTR)
4688 .Padding(PaddingMode::NONE)
4689 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4690 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4691
4692 params = AuthorizationSetBuilder()
4693 .BlockMode(BlockMode::CTR)
4694 .Padding(PaddingMode::NONE)
4695 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4696 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4697
4698 params = AuthorizationSetBuilder()
4699 .BlockMode(BlockMode::CTR)
4700 .Padding(PaddingMode::NONE)
4701 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4702 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4703}
4704
4705/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004706 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004707 *
4708 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4709 */
4710TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4712 .Authorization(TAG_NO_AUTH_REQUIRED)
4713 .AesEncryptionKey(128)
4714 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4715 .Padding(PaddingMode::NONE)));
4716 // Two-block message.
4717 string message = "12345678901234567890123456789012";
4718 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4719 AuthorizationSet out_params;
4720 string ciphertext1 = EncryptMessage(message, params, &out_params);
4721 vector<uint8_t> iv1 = CopyIv(out_params);
4722 EXPECT_EQ(message.size(), ciphertext1.size());
4723
4724 out_params.Clear();
4725
4726 string ciphertext2 = EncryptMessage(message, params, &out_params);
4727 vector<uint8_t> iv2 = CopyIv(out_params);
4728 EXPECT_EQ(message.size(), ciphertext2.size());
4729
4730 // IVs should be random, so ciphertexts should differ.
4731 EXPECT_NE(ciphertext1, ciphertext2);
4732
4733 params.push_back(TAG_NONCE, iv1);
4734 string plaintext = DecryptMessage(ciphertext1, params);
4735 EXPECT_EQ(message, plaintext);
4736}
4737
4738/*
4739 * EncryptionOperationsTest.AesCallerNonce
4740 *
4741 * Verifies that AES caller-provided nonces work correctly.
4742 */
4743TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4745 .Authorization(TAG_NO_AUTH_REQUIRED)
4746 .AesEncryptionKey(128)
4747 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4748 .Authorization(TAG_CALLER_NONCE)
4749 .Padding(PaddingMode::NONE)));
4750
4751 string message = "12345678901234567890123456789012";
4752
4753 // Don't specify nonce, should get a random one.
4754 AuthorizationSetBuilder params =
4755 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4756 AuthorizationSet out_params;
4757 string ciphertext = EncryptMessage(message, params, &out_params);
4758 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004759 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004760
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004761 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004762 string plaintext = DecryptMessage(ciphertext, params);
4763 EXPECT_EQ(message, plaintext);
4764
4765 // Now specify a nonce, should also work.
4766 params = AuthorizationSetBuilder()
4767 .BlockMode(BlockMode::CBC)
4768 .Padding(PaddingMode::NONE)
4769 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4770 out_params.Clear();
4771 ciphertext = EncryptMessage(message, params, &out_params);
4772
4773 // Decrypt with correct nonce.
4774 plaintext = DecryptMessage(ciphertext, params);
4775 EXPECT_EQ(message, plaintext);
4776
4777 // Try with wrong nonce.
4778 params = AuthorizationSetBuilder()
4779 .BlockMode(BlockMode::CBC)
4780 .Padding(PaddingMode::NONE)
4781 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4782 plaintext = DecryptMessage(ciphertext, params);
4783 EXPECT_NE(message, plaintext);
4784}
4785
4786/*
4787 * EncryptionOperationsTest.AesCallerNonceProhibited
4788 *
4789 * Verifies that caller-provided nonces are not permitted when not specified in the key
4790 * authorizations.
4791 */
4792TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4793 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4794 .Authorization(TAG_NO_AUTH_REQUIRED)
4795 .AesEncryptionKey(128)
4796 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4797 .Padding(PaddingMode::NONE)));
4798
4799 string message = "12345678901234567890123456789012";
4800
4801 // Don't specify nonce, should get a random one.
4802 AuthorizationSetBuilder params =
4803 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4804 AuthorizationSet out_params;
4805 string ciphertext = EncryptMessage(message, params, &out_params);
4806 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004807 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004808
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004809 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004810 string plaintext = DecryptMessage(ciphertext, params);
4811 EXPECT_EQ(message, plaintext);
4812
4813 // Now specify a nonce, should fail
4814 params = AuthorizationSetBuilder()
4815 .BlockMode(BlockMode::CBC)
4816 .Padding(PaddingMode::NONE)
4817 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4818 out_params.Clear();
4819 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4820}
4821
4822/*
4823 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4824 *
4825 * Verifies that AES GCM mode works.
4826 */
4827TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4829 .Authorization(TAG_NO_AUTH_REQUIRED)
4830 .AesEncryptionKey(128)
4831 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4832 .Padding(PaddingMode::NONE)
4833 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4834
4835 string aad = "foobar";
4836 string message = "123456789012345678901234567890123456";
4837
4838 auto begin_params = AuthorizationSetBuilder()
4839 .BlockMode(BlockMode::GCM)
4840 .Padding(PaddingMode::NONE)
4841 .Authorization(TAG_MAC_LENGTH, 128);
4842
Selene Huang31ab4042020-04-29 04:22:39 -07004843 // Encrypt
4844 AuthorizationSet begin_out_params;
4845 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4846 << "Begin encrypt";
4847 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004848 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4849 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004850 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4851
4852 // Grab nonce
4853 begin_params.push_back(begin_out_params);
4854
4855 // Decrypt.
4856 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004857 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004858 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004859 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004860 EXPECT_EQ(message.length(), plaintext.length());
4861 EXPECT_EQ(message, plaintext);
4862}
4863
4864/*
4865 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4866 *
4867 * Verifies that AES GCM mode works, even when there's a long delay
4868 * between operations.
4869 */
4870TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4872 .Authorization(TAG_NO_AUTH_REQUIRED)
4873 .AesEncryptionKey(128)
4874 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4875 .Padding(PaddingMode::NONE)
4876 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4877
4878 string aad = "foobar";
4879 string message = "123456789012345678901234567890123456";
4880
4881 auto begin_params = AuthorizationSetBuilder()
4882 .BlockMode(BlockMode::GCM)
4883 .Padding(PaddingMode::NONE)
4884 .Authorization(TAG_MAC_LENGTH, 128);
4885
Selene Huang31ab4042020-04-29 04:22:39 -07004886 // Encrypt
4887 AuthorizationSet begin_out_params;
4888 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4889 << "Begin encrypt";
4890 string ciphertext;
4891 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004892 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004893 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004894 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004895
4896 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4897
4898 // Grab nonce
4899 begin_params.push_back(begin_out_params);
4900
4901 // Decrypt.
4902 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4903 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004904 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004905 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004906 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004907 sleep(5);
4908 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4909 EXPECT_EQ(message.length(), plaintext.length());
4910 EXPECT_EQ(message, plaintext);
4911}
4912
4913/*
4914 * EncryptionOperationsTest.AesGcmDifferentNonces
4915 *
4916 * Verifies that encrypting the same data with different nonces produces different outputs.
4917 */
4918TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4920 .Authorization(TAG_NO_AUTH_REQUIRED)
4921 .AesEncryptionKey(128)
4922 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4923 .Padding(PaddingMode::NONE)
4924 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4925 .Authorization(TAG_CALLER_NONCE)));
4926
4927 string aad = "foobar";
4928 string message = "123456789012345678901234567890123456";
4929 string nonce1 = "000000000000";
4930 string nonce2 = "111111111111";
4931 string nonce3 = "222222222222";
4932
4933 string ciphertext1 =
4934 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4935 string ciphertext2 =
4936 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4937 string ciphertext3 =
4938 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4939
4940 ASSERT_NE(ciphertext1, ciphertext2);
4941 ASSERT_NE(ciphertext1, ciphertext3);
4942 ASSERT_NE(ciphertext2, ciphertext3);
4943}
4944
4945/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004946 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4947 *
4948 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4949 */
4950TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4952 .Authorization(TAG_NO_AUTH_REQUIRED)
4953 .AesEncryptionKey(128)
4954 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4955 .Padding(PaddingMode::NONE)
4956 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4957
4958 string aad = "foobar";
4959 string message = "123456789012345678901234567890123456";
4960
4961 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4962 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4963 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4964
4965 ASSERT_NE(ciphertext1, ciphertext2);
4966 ASSERT_NE(ciphertext1, ciphertext3);
4967 ASSERT_NE(ciphertext2, ciphertext3);
4968}
4969
4970/*
Selene Huang31ab4042020-04-29 04:22:39 -07004971 * EncryptionOperationsTest.AesGcmTooShortTag
4972 *
4973 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4974 */
4975TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4977 .Authorization(TAG_NO_AUTH_REQUIRED)
4978 .AesEncryptionKey(128)
4979 .BlockMode(BlockMode::GCM)
4980 .Padding(PaddingMode::NONE)
4981 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4982 string message = "123456789012345678901234567890123456";
4983 auto params = AuthorizationSetBuilder()
4984 .BlockMode(BlockMode::GCM)
4985 .Padding(PaddingMode::NONE)
4986 .Authorization(TAG_MAC_LENGTH, 96);
4987
4988 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4989}
4990
4991/*
4992 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4993 *
4994 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4995 */
4996TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4997 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4998 .Authorization(TAG_NO_AUTH_REQUIRED)
4999 .AesEncryptionKey(128)
5000 .BlockMode(BlockMode::GCM)
5001 .Padding(PaddingMode::NONE)
5002 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5003 string aad = "foobar";
5004 string message = "123456789012345678901234567890123456";
5005 auto params = AuthorizationSetBuilder()
5006 .BlockMode(BlockMode::GCM)
5007 .Padding(PaddingMode::NONE)
5008 .Authorization(TAG_MAC_LENGTH, 128);
5009
Selene Huang31ab4042020-04-29 04:22:39 -07005010 // Encrypt
5011 AuthorizationSet begin_out_params;
5012 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5013 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005014 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005015
5016 AuthorizationSet finish_out_params;
5017 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005018 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5019 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005020
5021 params = AuthorizationSetBuilder()
5022 .Authorizations(begin_out_params)
5023 .BlockMode(BlockMode::GCM)
5024 .Padding(PaddingMode::NONE)
5025 .Authorization(TAG_MAC_LENGTH, 96);
5026
5027 // Decrypt.
5028 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5029}
5030
5031/*
5032 * EncryptionOperationsTest.AesGcmCorruptKey
5033 *
5034 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5035 */
5036TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5037 const uint8_t nonce_bytes[] = {
5038 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5039 };
5040 string nonce = make_string(nonce_bytes);
5041 const uint8_t ciphertext_bytes[] = {
5042 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5043 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5044 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5045 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5046 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5047 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5048 };
5049 string ciphertext = make_string(ciphertext_bytes);
5050
5051 auto params = AuthorizationSetBuilder()
5052 .BlockMode(BlockMode::GCM)
5053 .Padding(PaddingMode::NONE)
5054 .Authorization(TAG_MAC_LENGTH, 128)
5055 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5056
5057 auto import_params = AuthorizationSetBuilder()
5058 .Authorization(TAG_NO_AUTH_REQUIRED)
5059 .AesEncryptionKey(128)
5060 .BlockMode(BlockMode::GCM)
5061 .Padding(PaddingMode::NONE)
5062 .Authorization(TAG_CALLER_NONCE)
5063 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5064
5065 // Import correct key and decrypt
5066 const uint8_t key_bytes[] = {
5067 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5068 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5069 };
5070 string key = make_string(key_bytes);
5071 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5072 string plaintext = DecryptMessage(ciphertext, params);
5073 CheckedDeleteKey();
5074
5075 // Corrupt key and attempt to decrypt
5076 key[0] = 0;
5077 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5078 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5079 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5080 CheckedDeleteKey();
5081}
5082
5083/*
5084 * EncryptionOperationsTest.AesGcmAadNoData
5085 *
5086 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5087 * encrypt.
5088 */
5089TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5090 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5091 .Authorization(TAG_NO_AUTH_REQUIRED)
5092 .AesEncryptionKey(128)
5093 .BlockMode(BlockMode::GCM)
5094 .Padding(PaddingMode::NONE)
5095 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5096
5097 string aad = "1234567890123456";
5098 auto params = AuthorizationSetBuilder()
5099 .BlockMode(BlockMode::GCM)
5100 .Padding(PaddingMode::NONE)
5101 .Authorization(TAG_MAC_LENGTH, 128);
5102
Selene Huang31ab4042020-04-29 04:22:39 -07005103 // Encrypt
5104 AuthorizationSet begin_out_params;
5105 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5106 string ciphertext;
5107 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005108 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5109 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005110 EXPECT_TRUE(finish_out_params.empty());
5111
5112 // Grab nonce
5113 params.push_back(begin_out_params);
5114
5115 // Decrypt.
5116 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005117 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005118 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005119 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005120
5121 EXPECT_TRUE(finish_out_params.empty());
5122
5123 EXPECT_EQ("", plaintext);
5124}
5125
5126/*
5127 * EncryptionOperationsTest.AesGcmMultiPartAad
5128 *
5129 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5130 * chunks.
5131 */
5132TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5133 const size_t tag_bits = 128;
5134 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5135 .Authorization(TAG_NO_AUTH_REQUIRED)
5136 .AesEncryptionKey(128)
5137 .BlockMode(BlockMode::GCM)
5138 .Padding(PaddingMode::NONE)
5139 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5140
5141 string message = "123456789012345678901234567890123456";
5142 auto begin_params = AuthorizationSetBuilder()
5143 .BlockMode(BlockMode::GCM)
5144 .Padding(PaddingMode::NONE)
5145 .Authorization(TAG_MAC_LENGTH, tag_bits);
5146 AuthorizationSet begin_out_params;
5147
Selene Huang31ab4042020-04-29 04:22:39 -07005148 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5149
5150 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005151 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5152 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005153 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005154 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5155 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005156
Selene Huang31ab4042020-04-29 04:22:39 -07005157 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005158 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005159
5160 // Grab nonce.
5161 begin_params.push_back(begin_out_params);
5162
5163 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005164 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005165 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005166 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005167 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005168 EXPECT_EQ(message, plaintext);
5169}
5170
5171/*
5172 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5173 *
5174 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5175 */
5176TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5178 .Authorization(TAG_NO_AUTH_REQUIRED)
5179 .AesEncryptionKey(128)
5180 .BlockMode(BlockMode::GCM)
5181 .Padding(PaddingMode::NONE)
5182 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5183
5184 string message = "123456789012345678901234567890123456";
5185 auto begin_params = AuthorizationSetBuilder()
5186 .BlockMode(BlockMode::GCM)
5187 .Padding(PaddingMode::NONE)
5188 .Authorization(TAG_MAC_LENGTH, 128);
5189 AuthorizationSet begin_out_params;
5190
Selene Huang31ab4042020-04-29 04:22:39 -07005191 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5192
Shawn Willden92d79c02021-02-19 07:31:55 -07005193 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005194 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005195 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5196 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005197
David Drysdaled2cc8c22021-04-15 13:29:45 +01005198 // The failure should have already cancelled the operation.
5199 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5200
Shawn Willden92d79c02021-02-19 07:31:55 -07005201 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005202}
5203
5204/*
5205 * EncryptionOperationsTest.AesGcmBadAad
5206 *
5207 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5208 */
5209TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5211 .Authorization(TAG_NO_AUTH_REQUIRED)
5212 .AesEncryptionKey(128)
5213 .BlockMode(BlockMode::GCM)
5214 .Padding(PaddingMode::NONE)
5215 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5216
5217 string message = "12345678901234567890123456789012";
5218 auto begin_params = AuthorizationSetBuilder()
5219 .BlockMode(BlockMode::GCM)
5220 .Padding(PaddingMode::NONE)
5221 .Authorization(TAG_MAC_LENGTH, 128);
5222
Selene Huang31ab4042020-04-29 04:22:39 -07005223 // Encrypt
5224 AuthorizationSet begin_out_params;
5225 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005226 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005227 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005228 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005229
5230 // Grab nonce
5231 begin_params.push_back(begin_out_params);
5232
Selene Huang31ab4042020-04-29 04:22:39 -07005233 // Decrypt.
5234 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005235 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005236 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005237 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005238}
5239
5240/*
5241 * EncryptionOperationsTest.AesGcmWrongNonce
5242 *
5243 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5244 */
5245TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
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 message = "12345678901234567890123456789012";
5254 auto begin_params = AuthorizationSetBuilder()
5255 .BlockMode(BlockMode::GCM)
5256 .Padding(PaddingMode::NONE)
5257 .Authorization(TAG_MAC_LENGTH, 128);
5258
Selene Huang31ab4042020-04-29 04:22:39 -07005259 // Encrypt
5260 AuthorizationSet begin_out_params;
5261 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005262 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005263 string ciphertext;
5264 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005265 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005266
5267 // Wrong nonce
5268 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5269
5270 // Decrypt.
5271 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005272 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005273 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005274 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005275
5276 // With wrong nonce, should have gotten garbage plaintext (or none).
5277 EXPECT_NE(message, plaintext);
5278}
5279
5280/*
5281 * EncryptionOperationsTest.AesGcmCorruptTag
5282 *
5283 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5284 */
5285TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5287 .Authorization(TAG_NO_AUTH_REQUIRED)
5288 .AesEncryptionKey(128)
5289 .BlockMode(BlockMode::GCM)
5290 .Padding(PaddingMode::NONE)
5291 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5292
5293 string aad = "1234567890123456";
5294 string message = "123456789012345678901234567890123456";
5295
5296 auto params = AuthorizationSetBuilder()
5297 .BlockMode(BlockMode::GCM)
5298 .Padding(PaddingMode::NONE)
5299 .Authorization(TAG_MAC_LENGTH, 128);
5300
Selene Huang31ab4042020-04-29 04:22:39 -07005301 // Encrypt
5302 AuthorizationSet begin_out_params;
5303 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005304 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005305 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005306 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005307
5308 // Corrupt tag
5309 ++(*ciphertext.rbegin());
5310
5311 // Grab nonce
5312 params.push_back(begin_out_params);
5313
5314 // Decrypt.
5315 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005316 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005317 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005318 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005319}
5320
5321/*
5322 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5323 *
5324 * Verifies that 3DES is basically functional.
5325 */
5326TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5327 auto auths = AuthorizationSetBuilder()
5328 .TripleDesEncryptionKey(168)
5329 .BlockMode(BlockMode::ECB)
5330 .Authorization(TAG_NO_AUTH_REQUIRED)
5331 .Padding(PaddingMode::NONE);
5332
5333 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5334 // Two-block message.
5335 string message = "1234567890123456";
5336 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5337 string ciphertext1 = EncryptMessage(message, inParams);
5338 EXPECT_EQ(message.size(), ciphertext1.size());
5339
5340 string ciphertext2 = EncryptMessage(string(message), inParams);
5341 EXPECT_EQ(message.size(), ciphertext2.size());
5342
5343 // ECB is deterministic.
5344 EXPECT_EQ(ciphertext1, ciphertext2);
5345
5346 string plaintext = DecryptMessage(ciphertext1, inParams);
5347 EXPECT_EQ(message, plaintext);
5348}
5349
5350/*
5351 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5352 *
5353 * Verifies that CBC keys reject ECB usage.
5354 */
5355TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5357 .TripleDesEncryptionKey(168)
5358 .BlockMode(BlockMode::CBC)
5359 .Authorization(TAG_NO_AUTH_REQUIRED)
5360 .Padding(PaddingMode::NONE)));
5361
5362 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5363 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5364}
5365
5366/*
5367 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5368 *
5369 * Tests ECB mode with PKCS#7 padding, various message sizes.
5370 */
5371TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5372 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5373 .TripleDesEncryptionKey(168)
5374 .BlockMode(BlockMode::ECB)
5375 .Authorization(TAG_NO_AUTH_REQUIRED)
5376 .Padding(PaddingMode::PKCS7)));
5377
5378 for (size_t i = 0; i < 32; ++i) {
5379 string message(i, 'a');
5380 auto inParams =
5381 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5382 string ciphertext = EncryptMessage(message, inParams);
5383 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5384 string plaintext = DecryptMessage(ciphertext, inParams);
5385 EXPECT_EQ(message, plaintext);
5386 }
5387}
5388
5389/*
5390 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5391 *
5392 * Verifies that keys configured for no padding reject PKCS7 padding
5393 */
5394TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5396 .TripleDesEncryptionKey(168)
5397 .BlockMode(BlockMode::ECB)
5398 .Authorization(TAG_NO_AUTH_REQUIRED)
5399 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005400 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5401 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005402}
5403
5404/*
5405 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5406 *
5407 * Verifies that corrupted padding is detected.
5408 */
5409TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5411 .TripleDesEncryptionKey(168)
5412 .BlockMode(BlockMode::ECB)
5413 .Authorization(TAG_NO_AUTH_REQUIRED)
5414 .Padding(PaddingMode::PKCS7)));
5415
5416 string message = "a";
5417 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5418 EXPECT_EQ(8U, ciphertext.size());
5419 EXPECT_NE(ciphertext, message);
5420 ++ciphertext[ciphertext.size() / 2];
5421
5422 AuthorizationSetBuilder begin_params;
5423 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5424 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5425 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5426 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005427 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005428 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5429}
5430
5431struct TripleDesTestVector {
5432 const char* name;
5433 const KeyPurpose purpose;
5434 const BlockMode block_mode;
5435 const PaddingMode padding_mode;
5436 const char* key;
5437 const char* iv;
5438 const char* input;
5439 const char* output;
5440};
5441
5442// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5443// of the NIST vectors are multiples of the block size.
5444static const TripleDesTestVector kTripleDesTestVectors[] = {
5445 {
5446 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5447 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5448 "", // IV
5449 "329d86bdf1bc5af4", // input
5450 "d946c2756d78633f", // output
5451 },
5452 {
5453 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5454 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5455 "", // IV
5456 "6b1540781b01ce1997adae102dbf3c5b", // input
5457 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5458 },
5459 {
5460 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5461 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5462 "", // IV
5463 "6daad94ce08acfe7", // input
5464 "660e7d32dcc90e79", // output
5465 },
5466 {
5467 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5468 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5469 "", // IV
5470 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5471 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5472 },
5473 {
5474 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5475 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5476 "43f791134c5647ba", // IV
5477 "dcc153cef81d6f24", // input
5478 "92538bd8af18d3ba", // output
5479 },
5480 {
5481 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5482 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5483 "c2e999cb6249023c", // IV
5484 "c689aee38a301bb316da75db36f110b5", // input
5485 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5486 },
5487 {
5488 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5489 PaddingMode::PKCS7,
5490 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5491 "c2e999cb6249023c", // IV
5492 "c689aee38a301bb316da75db36f110b500", // input
5493 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5494 },
5495 {
5496 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5497 PaddingMode::PKCS7,
5498 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5499 "c2e999cb6249023c", // IV
5500 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5501 "c689aee38a301bb316da75db36f110b500", // output
5502 },
5503 {
5504 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5505 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5506 "41746c7e442d3681", // IV
5507 "c53a7b0ec40600fe", // input
5508 "d4f00eb455de1034", // output
5509 },
5510 {
5511 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5512 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5513 "3982bc02c3727d45", // IV
5514 "6006f10adef52991fcc777a1238bbb65", // input
5515 "edae09288e9e3bc05746d872b48e3b29", // output
5516 },
5517};
5518
5519/*
5520 * EncryptionOperationsTest.TripleDesTestVector
5521 *
5522 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5523 */
5524TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5525 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5526 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5527 SCOPED_TRACE(test->name);
5528 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5529 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5530 hex2str(test->output));
5531 }
5532}
5533
5534/*
5535 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5536 *
5537 * Validates CBC mode functionality.
5538 */
5539TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5541 .TripleDesEncryptionKey(168)
5542 .BlockMode(BlockMode::CBC)
5543 .Authorization(TAG_NO_AUTH_REQUIRED)
5544 .Padding(PaddingMode::NONE)));
5545
5546 ASSERT_GT(key_blob_.size(), 0U);
5547
5548 // Two-block message.
5549 string message = "1234567890123456";
5550 vector<uint8_t> iv1;
5551 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5552 EXPECT_EQ(message.size(), ciphertext1.size());
5553
5554 vector<uint8_t> iv2;
5555 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5556 EXPECT_EQ(message.size(), ciphertext2.size());
5557
5558 // IVs should be random, so ciphertexts should differ.
5559 EXPECT_NE(iv1, iv2);
5560 EXPECT_NE(ciphertext1, ciphertext2);
5561
5562 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5563 EXPECT_EQ(message, plaintext);
5564}
5565
5566/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005567 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5568 *
5569 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5570 */
5571TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5572 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5573 .TripleDesEncryptionKey(168)
5574 .BlockMode(BlockMode::CBC)
5575 .Authorization(TAG_NO_AUTH_REQUIRED)
5576 .Authorization(TAG_CALLER_NONCE)
5577 .Padding(PaddingMode::NONE)));
5578 auto params = AuthorizationSetBuilder()
5579 .BlockMode(BlockMode::CBC)
5580 .Padding(PaddingMode::NONE)
5581 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5582 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5583}
5584
5585/*
Selene Huang31ab4042020-04-29 04:22:39 -07005586 * EncryptionOperationsTest.TripleDesCallerIv
5587 *
5588 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5589 */
5590TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5592 .TripleDesEncryptionKey(168)
5593 .BlockMode(BlockMode::CBC)
5594 .Authorization(TAG_NO_AUTH_REQUIRED)
5595 .Authorization(TAG_CALLER_NONCE)
5596 .Padding(PaddingMode::NONE)));
5597 string message = "1234567890123456";
5598 vector<uint8_t> iv;
5599 // Don't specify IV, should get a random one.
5600 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5601 EXPECT_EQ(message.size(), ciphertext1.size());
5602 EXPECT_EQ(8U, iv.size());
5603
5604 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5605 EXPECT_EQ(message, plaintext);
5606
5607 // Now specify an IV, should also work.
5608 iv = AidlBuf("abcdefgh");
5609 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5610
5611 // Decrypt with correct IV.
5612 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5613 EXPECT_EQ(message, plaintext);
5614
5615 // Now try with wrong IV.
5616 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5617 EXPECT_NE(message, plaintext);
5618}
5619
5620/*
5621 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5622 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005623 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005624 */
5625TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5626 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5627 .TripleDesEncryptionKey(168)
5628 .BlockMode(BlockMode::CBC)
5629 .Authorization(TAG_NO_AUTH_REQUIRED)
5630 .Padding(PaddingMode::NONE)));
5631
5632 string message = "12345678901234567890123456789012";
5633 vector<uint8_t> iv;
5634 // Don't specify nonce, should get a random one.
5635 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5636 EXPECT_EQ(message.size(), ciphertext1.size());
5637 EXPECT_EQ(8U, iv.size());
5638
5639 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5640 EXPECT_EQ(message, plaintext);
5641
5642 // Now specify a nonce, should fail.
5643 auto input_params = AuthorizationSetBuilder()
5644 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5645 .BlockMode(BlockMode::CBC)
5646 .Padding(PaddingMode::NONE);
5647 AuthorizationSet output_params;
5648 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5649 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5650}
5651
5652/*
5653 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5654 *
5655 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5656 */
5657TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5659 .TripleDesEncryptionKey(168)
5660 .BlockMode(BlockMode::ECB)
5661 .Authorization(TAG_NO_AUTH_REQUIRED)
5662 .Padding(PaddingMode::NONE)));
5663 // Two-block message.
5664 string message = "1234567890123456";
5665 auto begin_params =
5666 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5667 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5668}
5669
5670/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005671 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005672 *
5673 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5674 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005675TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5676 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5677 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5678 .TripleDesEncryptionKey(168)
5679 .BlockMode(blockMode)
5680 .Authorization(TAG_NO_AUTH_REQUIRED)
5681 .Padding(PaddingMode::NONE)));
5682 // Message is slightly shorter than two blocks.
5683 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005684
David Drysdaled2cc8c22021-04-15 13:29:45 +01005685 auto begin_params =
5686 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5687 AuthorizationSet output_params;
5688 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5689 string ciphertext;
5690 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5691
5692 CheckedDeleteKey();
5693 }
Selene Huang31ab4042020-04-29 04:22:39 -07005694}
5695
5696/*
5697 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5698 *
5699 * Verifies that PKCS7 padding works correctly in CBC mode.
5700 */
5701TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5703 .TripleDesEncryptionKey(168)
5704 .BlockMode(BlockMode::CBC)
5705 .Authorization(TAG_NO_AUTH_REQUIRED)
5706 .Padding(PaddingMode::PKCS7)));
5707
5708 // Try various message lengths; all should work.
5709 for (size_t i = 0; i < 32; ++i) {
5710 string message(i, 'a');
5711 vector<uint8_t> iv;
5712 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5713 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5714 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5715 EXPECT_EQ(message, plaintext);
5716 }
5717}
5718
5719/*
5720 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5721 *
5722 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5723 */
5724TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5726 .TripleDesEncryptionKey(168)
5727 .BlockMode(BlockMode::CBC)
5728 .Authorization(TAG_NO_AUTH_REQUIRED)
5729 .Padding(PaddingMode::NONE)));
5730
5731 // Try various message lengths; all should fail.
5732 for (size_t i = 0; i < 32; ++i) {
5733 auto begin_params =
5734 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5735 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5736 }
5737}
5738
5739/*
5740 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5741 *
5742 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5743 */
5744TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5746 .TripleDesEncryptionKey(168)
5747 .BlockMode(BlockMode::CBC)
5748 .Authorization(TAG_NO_AUTH_REQUIRED)
5749 .Padding(PaddingMode::PKCS7)));
5750
5751 string message = "a";
5752 vector<uint8_t> iv;
5753 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5754 EXPECT_EQ(8U, ciphertext.size());
5755 EXPECT_NE(ciphertext, message);
5756 ++ciphertext[ciphertext.size() / 2];
5757
5758 auto begin_params = AuthorizationSetBuilder()
5759 .BlockMode(BlockMode::CBC)
5760 .Padding(PaddingMode::PKCS7)
5761 .Authorization(TAG_NONCE, iv);
5762 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5763 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005764 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005765 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5766}
5767
5768/*
5769 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5770 *
5771 * Verifies that 3DES CBC works with many different input sizes.
5772 */
5773TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5774 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5775 .TripleDesEncryptionKey(168)
5776 .BlockMode(BlockMode::CBC)
5777 .Authorization(TAG_NO_AUTH_REQUIRED)
5778 .Padding(PaddingMode::NONE)));
5779
5780 int increment = 7;
5781 string message(240, 'a');
5782 AuthorizationSet input_params =
5783 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5784 AuthorizationSet output_params;
5785 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5786
5787 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005788 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005789 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005790 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5791 EXPECT_EQ(message.size(), ciphertext.size());
5792
5793 // Move TAG_NONCE into input_params
5794 input_params = output_params;
5795 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5796 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5797 output_params.Clear();
5798
5799 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5800 string plaintext;
5801 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005802 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005803 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5804 EXPECT_EQ(ciphertext.size(), plaintext.size());
5805 EXPECT_EQ(message, plaintext);
5806}
5807
5808INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5809
5810typedef KeyMintAidlTestBase MaxOperationsTest;
5811
5812/*
5813 * MaxOperationsTest.TestLimitAes
5814 *
5815 * Verifies that the max uses per boot tag works correctly with AES keys.
5816 */
5817TEST_P(MaxOperationsTest, TestLimitAes) {
5818 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5819
5820 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5821 .Authorization(TAG_NO_AUTH_REQUIRED)
5822 .AesEncryptionKey(128)
5823 .EcbMode()
5824 .Padding(PaddingMode::NONE)
5825 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5826
5827 string message = "1234567890123456";
5828
5829 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5830
5831 EncryptMessage(message, params);
5832 EncryptMessage(message, params);
5833 EncryptMessage(message, params);
5834
5835 // Fourth time should fail.
5836 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5837}
5838
5839/*
Qi Wud22ec842020-11-26 13:27:53 +08005840 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005841 *
5842 * Verifies that the max uses per boot tag works correctly with RSA keys.
5843 */
5844TEST_P(MaxOperationsTest, TestLimitRsa) {
5845 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5846
5847 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5848 .Authorization(TAG_NO_AUTH_REQUIRED)
5849 .RsaSigningKey(1024, 65537)
5850 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005851 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5852 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005853
5854 string message = "1234567890123456";
5855
5856 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5857
5858 SignMessage(message, params);
5859 SignMessage(message, params);
5860 SignMessage(message, params);
5861
5862 // Fourth time should fail.
5863 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5864}
5865
5866INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5867
Qi Wud22ec842020-11-26 13:27:53 +08005868typedef KeyMintAidlTestBase UsageCountLimitTest;
5869
5870/*
Qi Wubeefae42021-01-28 23:16:37 +08005871 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005872 *
Qi Wubeefae42021-01-28 23:16:37 +08005873 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005874 */
Qi Wubeefae42021-01-28 23:16:37 +08005875TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005876 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5877
5878 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5879 .Authorization(TAG_NO_AUTH_REQUIRED)
5880 .AesEncryptionKey(128)
5881 .EcbMode()
5882 .Padding(PaddingMode::NONE)
5883 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5884
5885 // Check the usage count limit tag appears in the authorizations.
5886 AuthorizationSet auths;
5887 for (auto& entry : key_characteristics_) {
5888 auths.push_back(AuthorizationSet(entry.authorizations));
5889 }
5890 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5891 << "key usage count limit " << 1U << " missing";
5892
5893 string message = "1234567890123456";
5894 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5895
Qi Wubeefae42021-01-28 23:16:37 +08005896 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5897 AuthorizationSet keystore_auths =
5898 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5899
Qi Wud22ec842020-11-26 13:27:53 +08005900 // First usage of AES key should work.
5901 EncryptMessage(message, params);
5902
Qi Wud22ec842020-11-26 13:27:53 +08005903 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5904 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5905 // must be invalidated from secure storage (such as RPMB partition).
5906 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5907 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005908 // Usage count limit tag is enforced by keystore, keymint does nothing.
5909 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005910 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5911 }
5912}
5913
5914/*
Qi Wubeefae42021-01-28 23:16:37 +08005915 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005916 *
Qi Wubeefae42021-01-28 23:16:37 +08005917 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005918 */
Qi Wubeefae42021-01-28 23:16:37 +08005919TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5920 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5921
5922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5923 .Authorization(TAG_NO_AUTH_REQUIRED)
5924 .AesEncryptionKey(128)
5925 .EcbMode()
5926 .Padding(PaddingMode::NONE)
5927 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5928
5929 // Check the usage count limit tag appears in the authorizations.
5930 AuthorizationSet auths;
5931 for (auto& entry : key_characteristics_) {
5932 auths.push_back(AuthorizationSet(entry.authorizations));
5933 }
5934 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5935 << "key usage count limit " << 3U << " missing";
5936
5937 string message = "1234567890123456";
5938 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5939
5940 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5941 AuthorizationSet keystore_auths =
5942 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5943
5944 EncryptMessage(message, params);
5945 EncryptMessage(message, params);
5946 EncryptMessage(message, params);
5947
5948 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5949 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5950 // must be invalidated from secure storage (such as RPMB partition).
5951 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5952 } else {
5953 // Usage count limit tag is enforced by keystore, keymint does nothing.
5954 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5955 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5956 }
5957}
5958
5959/*
5960 * UsageCountLimitTest.TestSingleUseRsa
5961 *
5962 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5963 */
5964TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005965 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5966
5967 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5968 .Authorization(TAG_NO_AUTH_REQUIRED)
5969 .RsaSigningKey(1024, 65537)
5970 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005971 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5972 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005973
5974 // Check the usage count limit tag appears in the authorizations.
5975 AuthorizationSet auths;
5976 for (auto& entry : key_characteristics_) {
5977 auths.push_back(AuthorizationSet(entry.authorizations));
5978 }
5979 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5980 << "key usage count limit " << 1U << " missing";
5981
5982 string message = "1234567890123456";
5983 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5984
Qi Wubeefae42021-01-28 23:16:37 +08005985 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5986 AuthorizationSet keystore_auths =
5987 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5988
Qi Wud22ec842020-11-26 13:27:53 +08005989 // First usage of RSA key should work.
5990 SignMessage(message, params);
5991
Qi Wud22ec842020-11-26 13:27:53 +08005992 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5993 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5994 // must be invalidated from secure storage (such as RPMB partition).
5995 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5996 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005997 // Usage count limit tag is enforced by keystore, keymint does nothing.
5998 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5999 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6000 }
6001}
6002
6003/*
6004 * UsageCountLimitTest.TestLimitUseRsa
6005 *
6006 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6007 */
6008TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
6009 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6010
6011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6012 .Authorization(TAG_NO_AUTH_REQUIRED)
6013 .RsaSigningKey(1024, 65537)
6014 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006015 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6016 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006017
6018 // Check the usage count limit tag appears in the authorizations.
6019 AuthorizationSet auths;
6020 for (auto& entry : key_characteristics_) {
6021 auths.push_back(AuthorizationSet(entry.authorizations));
6022 }
6023 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6024 << "key usage count limit " << 3U << " missing";
6025
6026 string message = "1234567890123456";
6027 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6028
6029 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6030 AuthorizationSet keystore_auths =
6031 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6032
6033 SignMessage(message, params);
6034 SignMessage(message, params);
6035 SignMessage(message, params);
6036
6037 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6038 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6039 // must be invalidated from secure storage (such as RPMB partition).
6040 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6041 } else {
6042 // Usage count limit tag is enforced by keystore, keymint does nothing.
6043 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006044 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6045 }
6046}
6047
Qi Wu8e727f72021-02-11 02:49:33 +08006048/*
6049 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6050 *
6051 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6052 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6053 * in hardware.
6054 */
6055TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6056 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6057
6058 auto error = GenerateKey(AuthorizationSetBuilder()
6059 .RsaSigningKey(2048, 65537)
6060 .Digest(Digest::NONE)
6061 .Padding(PaddingMode::NONE)
6062 .Authorization(TAG_NO_AUTH_REQUIRED)
6063 .Authorization(TAG_ROLLBACK_RESISTANCE)
6064 .SetDefaultValidity());
6065 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6066
6067 if (error == ErrorCode::OK) {
6068 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6069 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6070 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6071 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6072
6073 // The KeyMint should also enforce single use key in hardware when it supports rollback
6074 // resistance.
6075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6076 .Authorization(TAG_NO_AUTH_REQUIRED)
6077 .RsaSigningKey(1024, 65537)
6078 .NoDigestOrPadding()
6079 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6080 .SetDefaultValidity()));
6081
6082 // Check the usage count limit tag appears in the hardware authorizations.
6083 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6084 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6085 << "key usage count limit " << 1U << " missing";
6086
6087 string message = "1234567890123456";
6088 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6089
6090 // First usage of RSA key should work.
6091 SignMessage(message, params);
6092
6093 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6094 // must be invalidated from secure storage (such as RPMB partition).
6095 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6096 }
6097}
6098
Qi Wud22ec842020-11-26 13:27:53 +08006099INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6100
David Drysdale7de9feb2021-03-05 14:56:19 +00006101typedef KeyMintAidlTestBase GetHardwareInfoTest;
6102
6103TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6104 // Retrieving hardware info should give the same result each time.
6105 KeyMintHardwareInfo info;
6106 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6107 KeyMintHardwareInfo info2;
6108 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6109 EXPECT_EQ(info, info2);
6110}
6111
6112INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6113
Selene Huang31ab4042020-04-29 04:22:39 -07006114typedef KeyMintAidlTestBase AddEntropyTest;
6115
6116/*
6117 * AddEntropyTest.AddEntropy
6118 *
6119 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6120 * is actually added.
6121 */
6122TEST_P(AddEntropyTest, AddEntropy) {
6123 string data = "foo";
6124 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6125}
6126
6127/*
6128 * AddEntropyTest.AddEmptyEntropy
6129 *
6130 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6131 */
6132TEST_P(AddEntropyTest, AddEmptyEntropy) {
6133 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6134}
6135
6136/*
6137 * AddEntropyTest.AddLargeEntropy
6138 *
6139 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6140 */
6141TEST_P(AddEntropyTest, AddLargeEntropy) {
6142 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6143}
6144
David Drysdalebb3d85e2021-04-13 11:15:51 +01006145/*
6146 * AddEntropyTest.AddTooLargeEntropy
6147 *
6148 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6149 */
6150TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6151 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6152 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6153}
6154
Selene Huang31ab4042020-04-29 04:22:39 -07006155INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6156
Selene Huang31ab4042020-04-29 04:22:39 -07006157typedef KeyMintAidlTestBase KeyDeletionTest;
6158
6159/**
6160 * KeyDeletionTest.DeleteKey
6161 *
6162 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6163 * valid key blob.
6164 */
6165TEST_P(KeyDeletionTest, DeleteKey) {
6166 auto error = GenerateKey(AuthorizationSetBuilder()
6167 .RsaSigningKey(2048, 65537)
6168 .Digest(Digest::NONE)
6169 .Padding(PaddingMode::NONE)
6170 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006171 .Authorization(TAG_ROLLBACK_RESISTANCE)
6172 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006173 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6174
6175 // Delete must work if rollback protection is implemented
6176 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006177 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006178 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6179
6180 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6181
6182 string message = "12345678901234567890123456789012";
6183 AuthorizationSet begin_out_params;
6184 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6185 Begin(KeyPurpose::SIGN, key_blob_,
6186 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6187 &begin_out_params));
6188 AbortIfNeeded();
6189 key_blob_ = AidlBuf();
6190 }
6191}
6192
6193/**
6194 * KeyDeletionTest.DeleteInvalidKey
6195 *
6196 * This test checks that the HAL excepts invalid key blobs..
6197 */
6198TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6199 // Generate key just to check if rollback protection is implemented
6200 auto error = GenerateKey(AuthorizationSetBuilder()
6201 .RsaSigningKey(2048, 65537)
6202 .Digest(Digest::NONE)
6203 .Padding(PaddingMode::NONE)
6204 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006205 .Authorization(TAG_ROLLBACK_RESISTANCE)
6206 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006207 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6208
6209 // Delete must work if rollback protection is implemented
6210 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006211 AuthorizationSet enforced(SecLevelAuthorizations());
6212 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006213
6214 // Delete the key we don't care about the result at this point.
6215 DeleteKey();
6216
6217 // Now create an invalid key blob and delete it.
6218 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6219
6220 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6221 }
6222}
6223
6224/**
6225 * KeyDeletionTest.DeleteAllKeys
6226 *
6227 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6228 *
6229 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6230 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6231 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6232 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6233 * credentials stored in Keystore/Keymint.
6234 */
6235TEST_P(KeyDeletionTest, DeleteAllKeys) {
6236 if (!arm_deleteAllKeys) return;
6237 auto error = GenerateKey(AuthorizationSetBuilder()
6238 .RsaSigningKey(2048, 65537)
6239 .Digest(Digest::NONE)
6240 .Padding(PaddingMode::NONE)
6241 .Authorization(TAG_NO_AUTH_REQUIRED)
6242 .Authorization(TAG_ROLLBACK_RESISTANCE));
6243 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6244
6245 // Delete must work if rollback protection is implemented
6246 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006247 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006248 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6249
6250 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6251
6252 string message = "12345678901234567890123456789012";
6253 AuthorizationSet begin_out_params;
6254
6255 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6256 Begin(KeyPurpose::SIGN, key_blob_,
6257 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6258 &begin_out_params));
6259 AbortIfNeeded();
6260 key_blob_ = AidlBuf();
6261 }
6262}
6263
6264INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6265
David Drysdaled2cc8c22021-04-15 13:29:45 +01006266typedef KeyMintAidlTestBase KeyUpgradeTest;
6267
6268/**
6269 * KeyUpgradeTest.UpgradeInvalidKey
6270 *
6271 * This test checks that the HAL excepts invalid key blobs..
6272 */
6273TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6274 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6275
6276 std::vector<uint8_t> new_blob;
6277 Status result = keymint_->upgradeKey(key_blob,
6278 AuthorizationSetBuilder()
6279 .Authorization(TAG_APPLICATION_ID, "clientid")
6280 .Authorization(TAG_APPLICATION_DATA, "appdata")
6281 .vector_data(),
6282 &new_blob);
6283 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6284}
6285
6286INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6287
Selene Huang31ab4042020-04-29 04:22:39 -07006288using UpgradeKeyTest = KeyMintAidlTestBase;
6289
6290/*
6291 * UpgradeKeyTest.UpgradeKey
6292 *
6293 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6294 */
6295TEST_P(UpgradeKeyTest, UpgradeKey) {
6296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6297 .AesEncryptionKey(128)
6298 .Padding(PaddingMode::NONE)
6299 .Authorization(TAG_NO_AUTH_REQUIRED)));
6300
6301 auto result = UpgradeKey(key_blob_);
6302
6303 // Key doesn't need upgrading. Should get okay, but no new key blob.
6304 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6305}
6306
6307INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6308
6309using ClearOperationsTest = KeyMintAidlTestBase;
6310
6311/*
6312 * ClearSlotsTest.TooManyOperations
6313 *
6314 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6315 * operations are started without being finished or aborted. Also verifies
6316 * that aborting the operations clears the operations.
6317 *
6318 */
6319TEST_P(ClearOperationsTest, TooManyOperations) {
6320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6321 .Authorization(TAG_NO_AUTH_REQUIRED)
6322 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006323 .Padding(PaddingMode::NONE)
6324 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006325
6326 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6327 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006328 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006329 AuthorizationSet out_params;
6330 ErrorCode result;
6331 size_t i;
6332
6333 for (i = 0; i < max_operations; i++) {
6334 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6335 if (ErrorCode::OK != result) {
6336 break;
6337 }
6338 }
6339 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6340 // Try again just in case there's a weird overflow bug
6341 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6342 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6343 for (size_t j = 0; j < i; j++) {
6344 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6345 << "Aboort failed for i = " << j << std::endl;
6346 }
6347 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6348 AbortIfNeeded();
6349}
6350
6351INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6352
6353typedef KeyMintAidlTestBase TransportLimitTest;
6354
6355/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006356 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006357 *
6358 * Verifies that passing input data to finish succeeds as expected.
6359 */
6360TEST_P(TransportLimitTest, LargeFinishInput) {
6361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6362 .Authorization(TAG_NO_AUTH_REQUIRED)
6363 .AesEncryptionKey(128)
6364 .BlockMode(BlockMode::ECB)
6365 .Padding(PaddingMode::NONE)));
6366
6367 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6368 auto cipher_params =
6369 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6370
6371 AuthorizationSet out_params;
6372 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6373
6374 string plain_message = std::string(1 << msg_size, 'x');
6375 string encrypted_message;
6376 auto rc = Finish(plain_message, &encrypted_message);
6377
6378 EXPECT_EQ(ErrorCode::OK, rc);
6379 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6380 << "Encrypt finish returned OK, but did not consume all of the given input";
6381 cipher_params.push_back(out_params);
6382
6383 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6384
6385 string decrypted_message;
6386 rc = Finish(encrypted_message, &decrypted_message);
6387 EXPECT_EQ(ErrorCode::OK, rc);
6388 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6389 << "Decrypt finish returned OK, did not consume all of the given input";
6390 }
6391}
6392
6393INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6394
David Zeuthene0c40892021-01-08 12:54:11 -05006395typedef KeyMintAidlTestBase KeyAgreementTest;
6396
6397int CurveToOpenSslCurveName(EcCurve curve) {
6398 switch (curve) {
6399 case EcCurve::P_224:
6400 return NID_secp224r1;
6401 case EcCurve::P_256:
6402 return NID_X9_62_prime256v1;
6403 case EcCurve::P_384:
6404 return NID_secp384r1;
6405 case EcCurve::P_521:
6406 return NID_secp521r1;
6407 }
6408}
6409
6410/*
6411 * KeyAgreementTest.Ecdh
6412 *
6413 * Verifies that ECDH works for all curves
6414 */
6415TEST_P(KeyAgreementTest, Ecdh) {
6416 // Because it's possible to use this API with keys on different curves, we
6417 // check all N^2 combinations where N is the number of supported
6418 // curves.
6419 //
6420 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6421 // lot more curves we can be smart about things and just pick |otherCurve| so
6422 // it's not |curve| and that way we end up with only 2*N runs
6423 //
6424 for (auto curve : ValidCurves()) {
6425 for (auto localCurve : ValidCurves()) {
6426 // Generate EC key locally (with access to private key material)
6427 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6428 int curveName = CurveToOpenSslCurveName(localCurve);
6429 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6430 ASSERT_NE(group, nullptr);
6431 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6432 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6433 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6434 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6435
6436 // Get encoded form of the public part of the locally generated key...
6437 unsigned char* p = nullptr;
6438 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6439 ASSERT_GT(encodedPublicKeySize, 0);
6440 vector<uint8_t> encodedPublicKey(
6441 reinterpret_cast<const uint8_t*>(p),
6442 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6443 OPENSSL_free(p);
6444
6445 // Generate EC key in KeyMint (only access to public key material)
6446 vector<uint8_t> challenge = {0x41, 0x42};
6447 EXPECT_EQ(
6448 ErrorCode::OK,
6449 GenerateKey(AuthorizationSetBuilder()
6450 .Authorization(TAG_NO_AUTH_REQUIRED)
6451 .Authorization(TAG_EC_CURVE, curve)
6452 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6453 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6454 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006455 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6456 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006457 << "Failed to generate key";
6458 ASSERT_GT(cert_chain_.size(), 0);
6459 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6460 ASSERT_NE(kmKeyCert, nullptr);
6461 // Check that keyAgreement (bit 4) is set in KeyUsage
6462 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6463 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6464 ASSERT_NE(kmPkey, nullptr);
6465 if (dump_Attestations) {
6466 for (size_t n = 0; n < cert_chain_.size(); n++) {
6467 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6468 }
6469 }
6470
6471 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6472 if (curve != localCurve) {
6473 // If the keys are using different curves KeyMint should fail with
6474 // ErrorCode:INVALID_ARGUMENT. Check that.
6475 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6476 string ZabFromKeyMintStr;
6477 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6478 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6479 &ZabFromKeyMintStr));
6480
6481 } else {
6482 // Otherwise if the keys are using the same curve, it should work.
6483 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6484 string ZabFromKeyMintStr;
6485 EXPECT_EQ(ErrorCode::OK,
6486 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6487 &ZabFromKeyMintStr));
6488 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6489
6490 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6491 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6492 ASSERT_NE(ctx, nullptr);
6493 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6494 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6495 size_t ZabFromTestLen = 0;
6496 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6497 vector<uint8_t> ZabFromTest;
6498 ZabFromTest.resize(ZabFromTestLen);
6499 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6500
6501 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6502 }
6503
6504 CheckedDeleteKey();
6505 }
6506 }
6507}
6508
6509INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6510
David Drysdaled2cc8c22021-04-15 13:29:45 +01006511using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6512
6513// This is a problematic test, as it can render the device under test permanently unusable.
6514// Re-enable and run at your own risk.
6515TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6516 auto result = DestroyAttestationIds();
6517 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6518}
6519
6520INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6521
Shawn Willdend659c7c2021-02-19 14:51:51 -07006522using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006523
6524TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
6525 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6526 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6527
6528 CheckedDeleteKey(&aesKeyData.blob);
6529 CheckedDeleteKey(&hmacKeyData.blob);
6530 CheckedDeleteKey(&rsaKeyData.blob);
6531 CheckedDeleteKey(&ecdsaKeyData.blob);
6532}
6533
David Drysdaled2cc8c22021-04-15 13:29:45 +01006534// 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 +00006535// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6536// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6537// early boot, so you'll have to reboot between runs.
6538TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6539 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6540 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6541 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6542 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6543 EXPECT_TRUE(
6544 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6545 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6546 EXPECT_TRUE(
6547 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6548
6549 // Should be able to use keys, since early boot has not ended
6550 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6551 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6552 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6553 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6554
6555 // End early boot
6556 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6557 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6558
6559 // Should not be able to use already-created keys.
6560 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6561 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6562 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6563 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6564
6565 CheckedDeleteKey(&aesKeyData.blob);
6566 CheckedDeleteKey(&hmacKeyData.blob);
6567 CheckedDeleteKey(&rsaKeyData.blob);
6568 CheckedDeleteKey(&ecdsaKeyData.blob);
6569
6570 // Should not be able to create new keys
6571 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6572 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6573
6574 CheckedDeleteKey(&aesKeyData.blob);
6575 CheckedDeleteKey(&hmacKeyData.blob);
6576 CheckedDeleteKey(&rsaKeyData.blob);
6577 CheckedDeleteKey(&ecdsaKeyData.blob);
6578}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006579
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006580INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6581
Shawn Willdend659c7c2021-02-19 14:51:51 -07006582using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006583
6584// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6585// between runs... and on most test devices there are no enrolled credentials so it can't be
6586// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6587// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6588// a manual test process, which includes unlocking between runs, which is why it's included here.
6589// Well, that and the fact that it's the only test we can do without also making calls into the
6590// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6591// implications might be, so that may or may not be a solution.
6592TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6593 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6594 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6595
6596 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6597 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6598 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6599 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6600
6601 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006602 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006603 ASSERT_EQ(ErrorCode::OK, rc);
6604 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6605 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6606 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6607 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6608
6609 CheckedDeleteKey(&aesKeyData.blob);
6610 CheckedDeleteKey(&hmacKeyData.blob);
6611 CheckedDeleteKey(&rsaKeyData.blob);
6612 CheckedDeleteKey(&ecdsaKeyData.blob);
6613}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006614
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006615INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6616
Janis Danisevskis24c04702020-12-16 18:28:39 -08006617} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006618
6619int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006620 std::cout << "Testing ";
6621 auto halInstances =
6622 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6623 std::cout << "HAL instances:\n";
6624 for (auto& entry : halInstances) {
6625 std::cout << " " << entry << '\n';
6626 }
6627
Selene Huang31ab4042020-04-29 04:22:39 -07006628 ::testing::InitGoogleTest(&argc, argv);
6629 for (int i = 1; i < argc; ++i) {
6630 if (argv[i][0] == '-') {
6631 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006632 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6633 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006634 }
6635 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006636 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6637 dump_Attestations = true;
6638 } else {
6639 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006640 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006641 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6642 if (std::string(argv[i]) == "--check_patchLevels") {
6643 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6644 }
Selene Huang31ab4042020-04-29 04:22:39 -07006645 }
6646 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006647 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006648}