blob: 2a0ee7fd3edeac88e5608c76ecccb49d021124eb [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale92464372021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Selene Huang31ab4042020-04-29 04:22:39 -070074template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000075bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
76 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070077 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080078 if (auto p = authorizationValue(ttag, param)) {
79 return *p == expected_value;
80 }
81 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070082 });
83 return (it != set.end());
84}
85
86template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(),
89 [&](const KeyParameter& param) { return param.tag == tag; });
90 return (it != set.end());
91}
92
93constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
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, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
109
110string hex2str(string a) {
111 string b;
112 size_t num = a.size() / 2;
113 b.resize(num);
114 for (size_t i = 0; i < num; i++) {
115 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
116 }
117 return b;
118}
119
David Drysdaled2cc8c22021-04-15 13:29:45 +0100120string rsa_key = hex2str(
121 // RFC 5208 s5
122 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
123 "020100" // INTEGER length 1 value 0x00 (version)
124 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
125 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
126 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
127 "0500" // NULL (parameters)
128 // } end SEQUENCE (AlgorithmIdentifier)
129 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
130 // RFC 8017 A.1.2
131 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
132 "020100" // INTEGER length 1 value 0x00 (version)
133 "028181" // INTEGER length 0x81 value (modulus) ...
134 "00c6095409047d8634812d5a218176e4"
135 "5c41d60a75b13901f234226cffe77652"
136 "1c5a77b9e389417b71c0b6a44d13afe4"
137 "e4a2805d46c9da2935adb1ff0c1f24ea"
138 "06e62b20d776430a4d435157233c6f91"
139 "6783c30e310fcbd89b85c2d567711697"
140 "85ac12bca244abda72bfb19fc44d27c8"
141 "1e1d92de284f4061edfd99280745ea6d"
142 "25"
143 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
144 "028180" // INTEGER length 0x80 (privateExponent) value...
145 "1be0f04d9cae3718691f035338308e91"
146 "564b55899ffb5084d2460e6630257e05"
147 "b3ceab02972dfabcd6ce5f6ee2589eb6"
148 "7911ed0fac16e43a444b8c861e544a05"
149 "93365772f8baf6b22fc9e3c5f1024b06"
150 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
151 "ace7240290bef16c0b3f7f3cdd64ce3a"
152 "b5912cf6e32f39ab188358afcccd8081"
153 "0241" // INTEGER length 0x41 (prime1)
154 "00e4b49ef50f765d3b24dde01aceaaf1"
155 "30f2c76670a91a61ae08af497b4a82be"
156 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
157 "8c92bfab137fba2285227b83c342ff7c"
158 "55"
159 "0241" // INTEGER length 0x41 (prime2)
160 "00ddabb5839c4c7f6bf3d4183231f005"
161 "b31aa58affdda5c79e4cce217f6bc930"
162 "dbe563d480706c24e9ebfcab28a6cdef"
163 "d324b77e1bf7251b709092c24ff501fd"
164 "91"
165 "0240" // INTEGER length 0x40 (exponent1)
166 "23d4340eda3445d8cd26c14411da6fdc"
167 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
168 "842c1d280405bc2f6c1bea214a1d742a"
169 "b996b35b63a82a5e470fa88dbf823cdd"
170 "0240" // INTEGER length 0x40 (exponent2)
171 "1b7b57449ad30d1518249a5f56bb9829"
172 "4d4b6ac12ffc86940497a5a5837a6cf9"
173 "46262b494526d328c11e1126380fde04"
174 "c24f916dec250892db09a6d77cdba351"
175 "0240" // INTEGER length 0x40 (coefficient)
176 "7762cd8f4d050da56bd591adb515d24d"
177 "7ccd32cca0d05f866d583514bd7324d5"
178 "f33645e8ed8b4a1cb3cc4a1d67987399"
179 "f2a09f5b3fb68c88d5e5d90ac33492d6"
180 // } end SEQUENCE (PrivateKey)
181 // } end SEQUENCE (PrivateKeyInfo)
182);
Selene Huang31ab4042020-04-29 04:22:39 -0700183
Selene Huange5727e62021-04-13 22:41:20 -0700184/*
185 * DER-encoded PKCS#8 format RSA key. Generated using:
186 *
187 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
188 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100189string rsa_2048_key = hex2str(
190 // RFC 5208 s5
191 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
192 "020100" // INTEGER length 1 value 0x00 (version)
193 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
194 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
195 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
196 "0500" // NULL (parameters)
197 // } end SEQUENCE (AlgorithmIdentifier)
198 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
199 // RFC 8017 A.1.2
200 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
201 "020100" // INTEGER length 1 value 0x00 (version)
202 "02820101" // INTEGER length 0x101 value (modulus) ...
203 "00BEBC342B56D443B1299F9A6A7056E8"
204 "0A897E318476A5A18029E63B2ED739A6"
205 "1791D339F58DC763D9D14911F2EDEC38"
206 "3DEE11F6319B44510E7A3ECD9B79B973"
207 "82E49500ACF8117DC89CAF0E621F7775"
208 "6554A2FD4664BFE7AB8B59AB48340DBF"
209 "A27B93B5A81F6ECDEB02D0759307128D"
210 "F3E3BAD4055C8B840216DFAA5700670E"
211 "6C5126F0962FCB70FF308F25049164CC"
212 "F76CC2DA66A7DD9A81A714C2809D6918"
213 "6133D29D84568E892B6FFBF3199BDB14"
214 "383EE224407F190358F111A949552ABA"
215 "6714227D1BD7F6B20DD0CB88F9467B71"
216 "9339F33BFF35B3870B3F62204E4286B0"
217 "948EA348B524544B5F9838F29EE643B0"
218 "79EEF8A713B220D7806924CDF7295070"
219 "C5"
220 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
221 "02820100" // INTEGER length 0x100 (privateExponent) value...
222 "69F377F35F2F584EF075353CCD1CA997"
223 "38DB3DBC7C7FF35F9366CE176DFD1B13"
224 "5AB10030344ABF5FBECF1D4659FDEF1C"
225 "0FC430834BE1BE3911951377BB3D563A"
226 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
227 "2686C7B4B3C09A7B8354133E6F93F790"
228 "D59EAEB92E84C9A4339302CCE28FDF04"
229 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
230 "6AB706645BF074A4E4090D06FB163124"
231 "365FD5EE7A20D350E9958CC30D91326E"
232 "1B292E9EF5DB408EC42DAF737D201497"
233 "04D0A678A0FB5B5446863B099228A352"
234 "D604BA8091A164D01D5AB05397C71EAD"
235 "20BE2A08FC528FE442817809C787FEE4"
236 "AB97F97B9130D022153EDC6EB6CBE7B0"
237 "F8E3473F2E901209B5DB10F93604DB01"
238 "028181" // INTEGER length 0x81 (prime1)
239 "00E83C0998214941EA4F9293F1B77E2E"
240 "99E6CF305FAF358238E126124FEAF2EB"
241 "9724B2EA7B78E6032343821A80E55D1D"
242 "88FB12D220C3F41A56142FEC85796D19"
243 "17F1E8C774F142B67D3D6E7B7E6B4383"
244 "E94DB5929089DBB346D5BDAB40CC2D96"
245 "EE0409475E175C63BF78CFD744136740"
246 "838127EA723FF3FE7FA368C1311B4A4E"
247 "05"
248 "028181" // INTEGER length 0x81 (prime2)
249 "00D240FCC0F5D7715CDE21CB2DC86EA1"
250 "46132EA3B06F61FF2AF54BF38473F59D"
251 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
252 "B1B58C39F95E4798CCBB43E83D0119AC"
253 "F532F359CA743C85199F0286610E2009"
254 "97D7312917179AC9B67558773212EC96"
255 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
256 "94D94E066A0900B7B70E82A44FB30053"
257 "C1"
258 "028181" // INTEGER length 0x81 (exponent1)
259 "00AD15DA1CBD6A492B66851BA8C316D3"
260 "8AB700E2CFDDD926A658003513C54BAA"
261 "152B30021D667D20078F500F8AD3E7F3"
262 "945D74A891ED1A28EAD0FEEAEC8C14A8"
263 "E834CF46A13D1378C99D18940823CFDD"
264 "27EC5810D59339E0C34198AC638E09C8"
265 "7CBB1B634A9864AE9F4D5EB2D53514F6"
266 "7B4CAEC048C8AB849A02E397618F3271"
267 "35"
268 "028180" // INTEGER length 0x80 (exponent2)
269 "1FA2C1A5331880A92D8F3E281C617108"
270 "BF38244F16E352E69ED417C7153F9EC3"
271 "18F211839C643DCF8B4DD67CE2AC312E"
272 "95178D5D952F06B1BF779F4916924B70"
273 "F582A23F11304E02A5E7565AE22A35E7"
274 "4FECC8B6FDC93F92A1A37703E4CF0E63"
275 "783BD02EB716A7ECBBFA606B10B74D01"
276 "579522E7EF84D91FC522292108D902C1"
277 "028180" // INTEGER length 0x80 (coefficient)
278 "796FE3825F9DCC85DF22D58690065D93"
279 "898ACD65C087BEA8DA3A63BF4549B795"
280 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
281 "0D74F40DED8E1102C52152A31B6165F8"
282 "3A6722AECFCC35A493D7634664B888A0"
283 "8D3EB034F12EA28BFEE346E205D33482"
284 "7F778B16ED40872BD29FCB36536B6E93"
285 "FFB06778696B4A9D81BB0A9423E63DE5"
286 // } end SEQUENCE (PrivateKey)
287 // } end SEQUENCE (PrivateKeyInfo)
288);
Selene Huange5727e62021-04-13 22:41:20 -0700289
David Drysdaled2cc8c22021-04-15 13:29:45 +0100290string ec_256_key = hex2str(
291 // RFC 5208 s5
292 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
293 "020100" // INTEGER length 1 value 0 (version)
294 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
295 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
296 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
297 "0608" // OBJECT IDENTIFIER length 8 (param)
298 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
299 // } end SEQUENCE (AlgorithmIdentifier)
300 "046d" // OCTET STRING length 0x6d (privateKey) holding...
301 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
302 "020101" // INTEGER length 1 value 1 (version)
303 "0420" // OCTET STRING length 0x20 (privateKey)
304 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
305 "941eed09366bc03299986481f3a4d859"
306 "a144" // TAG [1] len 0x44 (publicKey) {
307 "03420004bf85d7720d07c25461683bc6"
308 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
309 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
310 "bcc41c6eb00083cf3376d11fd44949e0"
311 "b2183bfe"
312 // } end SEQUENCE (ECPrivateKey)
313 // } end SEQUENCE (PrivateKeyInfo)
314);
Selene Huang31ab4042020-04-29 04:22:39 -0700315
David Drysdaled2cc8c22021-04-15 13:29:45 +0100316string ec_521_key = hex2str(
317 // RFC 5208 s5
318 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
319 "020100" // INTEGER length 1 value 0 (version)
320 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
321 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
322 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
323 "0605" // OBJECT IDENTIFIER length 5 (param)
324 "2B81040023" // 1.3.132.0.35 (secp521r1)
325 // } end SEQUENCE (AlgorithmIdentifier)
326 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
327 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
328 "020101" // INTEGER length 1 value 1 (version)
329 "0442" // OCTET STRING length 0x42 (privateKey)
330 "0011458C586DB5DAA92AFAB03F4FE46A"
331 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
332 "9D18D7D08B5BCFA0E53C75B064AD51C4"
333 "49BAE0258D54B94B1E885DED08ED4FB2"
334 "5CE9"
335 "A18189" // TAG [1] len 0x89 (publicKey) {
336 "03818600040149EC11C6DF0FA122C6A9"
337 "AFD9754A4FA9513A627CA329E349535A"
338 "5629875A8ADFBE27DCB932C051986377"
339 "108D054C28C6F39B6F2C9AF81802F9F3"
340 "26B842FF2E5F3C00AB7635CFB36157FC"
341 "0882D574A10D839C1A0C049DC5E0D775"
342 "E2EE50671A208431BB45E78E70BEFE93"
343 "0DB34818EE4D5C26259F5C6B8E28A652"
344 "950F9F88D7B4B2C9D9"
345 // } end SEQUENCE (ECPrivateKey)
346 // } end SEQUENCE (PrivateKeyInfo)
347);
Selene Huang31ab4042020-04-29 04:22:39 -0700348
David Drysdaled2cc8c22021-04-15 13:29:45 +0100349string ec_256_key_rfc5915 = hex2str(
350 // RFC 5208 s5
351 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
352 "020100" // INTEGER length 1 value 0 (version)
353 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
354 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
355 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
356 "0608" // OBJECT IDENTIFIER length 8 (param)
357 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
358 // } end SEQUENCE (AlgorithmIdentifier)
359 "0479" // OCTET STRING length 0x79 (privateKey) holding...
360 // RFC 5915 s3
361 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
362 "020101" // INTEGER length 1 value 1 (version)
363 "0420" // OCTET STRING length 0x42 (privateKey)
364 "782370a8c8ce5537baadd04dcff079c8"
365 "158cfa9c67b818b38e8d21c9fa750c1d"
366 "a00a" // TAG [0] length 0xa (parameters)
367 "0608" // OBJECT IDENTIFIER length 8
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end TAG [0]
370 "a144" // TAG [1] length 0x44 (publicKey) {
371 "0342" // BIT STRING length 0x42
372 "00" // no pad bits
373 "04e2cc561ee701da0ad0ef0d176bb0c9"
374 "19d42e79c393fdc1bd6c4010d85cf2cf"
375 "8e68c905464666f98dad4f01573ba810"
376 "78b3428570a439ba3229fbc026c55068"
377 "2f"
378 // } end SEQUENCE (ECPrivateKey)
379 // } end SEQUENCE (PrivateKeyInfo)
380);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
David Drysdaled2cc8c22021-04-15 13:29:45 +0100382string ec_256_key_sec1 = hex2str(
383 // RFC 5208 s5
384 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
385 "020100" // INTEGER length 1 value 0 (version)
386 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
387 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
388 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
389 "0608" // OBJECT IDENTIFIER length 8 (param)
390 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
391 // } end SEQUENCE (AlgorithmIdentifier)
392 "046d" // OCTET STRING length 0x6d (privateKey) holding...
393 // SEC1-v2 C.4
394 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
395 "020101" // INTEGER length 1 value 0x01 (version)
396 "0420" // OCTET STRING length 0x20 (privateKey)
397 "782370a8c8ce5537baadd04dcff079c8"
398 "158cfa9c67b818b38e8d21c9fa750c1d"
399 "a144" // TAG [1] length 0x44 (publicKey) {
400 "0342" // BIT STRING length 0x42
401 "00" // no pad bits
402 "04e2cc561ee701da0ad0ef0d176bb0c9"
403 "19d42e79c393fdc1bd6c4010d85cf2cf"
404 "8e68c905464666f98dad4f01573ba810"
405 "78b3428570a439ba3229fbc026c55068"
406 "2f"
407 // } end TAG [1] (publicKey)
408 // } end SEQUENCE (PrivateKeyInfo)
409);
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411struct RSA_Delete {
412 void operator()(RSA* p) { RSA_free(p); }
413};
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415std::string make_string(const uint8_t* data, size_t length) {
416 return std::string(reinterpret_cast<const char*>(data), length);
417}
418
419template <size_t N>
420std::string make_string(const uint8_t (&a)[N]) {
421 return make_string(a, N);
422}
423
424class AidlBuf : public vector<uint8_t> {
425 typedef vector<uint8_t> super;
426
427 public:
428 AidlBuf() {}
429 AidlBuf(const super& other) : super(other) {}
430 AidlBuf(super&& other) : super(std::move(other)) {}
431 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
432
433 AidlBuf& operator=(const super& other) {
434 super::operator=(other);
435 return *this;
436 }
437
438 AidlBuf& operator=(super&& other) {
439 super::operator=(std::move(other));
440 return *this;
441 }
442
443 AidlBuf& operator=(const string& other) {
444 resize(other.size());
445 for (size_t i = 0; i < other.size(); ++i) {
446 (*this)[i] = static_cast<uint8_t>(other[i]);
447 }
448 return *this;
449 }
450
451 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
452};
453
David Drysdale4dc01072021-04-01 12:17:35 +0100454string device_suffix(const string& name) {
455 size_t pos = name.find('/');
456 if (pos == string::npos) {
457 return name;
458 }
459 return name.substr(pos + 1);
460}
461
462bool matching_rp_instance(const string& km_name,
463 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
464 string km_suffix = device_suffix(km_name);
465
466 vector<string> rp_names =
467 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
468 for (const string& rp_name : rp_names) {
469 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
470 // KeyMint instance, assume they match.
471 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
472 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
473 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
474 return true;
475 }
476 }
477 return false;
478}
479
Selene Huang31ab4042020-04-29 04:22:39 -0700480} // namespace
481
482class NewKeyGenerationTest : public KeyMintAidlTestBase {
483 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700484 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000485 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700486 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700487
Selene Huang31ab4042020-04-29 04:22:39 -0700488 // Check that some unexpected tags/values are NOT present.
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
490 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 }
492
493 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
494 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
497
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000499 }
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);
David Drysdale96ad2032021-05-20 12:05:26 +0100565 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000566
567 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
568
569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
571 << "Key size " << key_size << "missing";
572
573 CheckedDeleteKey(&key_blob);
574 }
575 }
576 }
577}
578
579/*
580 * NewKeyGenerationTest.AesInvalidSize
581 *
582 * Verifies that specifying an invalid key size for AES key generation returns
583 * UNSUPPORTED_KEY_SIZE.
584 */
585TEST_P(NewKeyGenerationTest, AesInvalidSize) {
586 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
587 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
588 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
589 SCOPED_TRACE(testing::Message()
590 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
591 vector<uint8_t> key_blob;
592 vector<KeyCharacteristics> key_characteristics;
593 auto builder = AuthorizationSetBuilder()
594 .AesEncryptionKey(key_size)
595 .BlockMode(block_mode)
596 .Padding(padding_mode)
597 .SetDefaultValidity();
598 if (block_mode == BlockMode::GCM) {
599 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
600 }
601 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
602 GenerateKey(builder, &key_blob, &key_characteristics));
603 }
604 }
605 }
606
607 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
608 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611 // No key size specified
612 auto builder = AuthorizationSetBuilder()
613 .Authorization(TAG_ALGORITHM, Algorithm::AES)
614 .BlockMode(block_mode)
615 .Padding(padding_mode)
616 .SetDefaultValidity();
617 if (block_mode == BlockMode::GCM) {
618 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
619 }
620 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
621 GenerateKey(builder, &key_blob, &key_characteristics));
622 }
623 }
624}
625
626/*
627 * NewKeyGenerationTest.AesInvalidPadding
628 *
629 * Verifies that specifying an invalid padding on AES keys gives a failure
630 * somewhere along the way.
631 */
632TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
633 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
634 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
635 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
636 SCOPED_TRACE(testing::Message()
637 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000638 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 .AesEncryptionKey(key_size)
641 .BlockMode(block_mode)
642 .Padding(padding_mode)
643 .SetDefaultValidity();
644 if (block_mode == BlockMode::GCM) {
645 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
646 }
647
Tommy Chiu3950b452021-05-03 22:01:46 +0800648 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 if (result == ErrorCode::OK) {
650 // Key creation was OK but has generated a key that cannot be used.
651 auto params =
652 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800653 if (block_mode == BlockMode::GCM) {
654 params.Authorization(TAG_MAC_LENGTH, 128);
655 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 auto result = Begin(KeyPurpose::ENCRYPT, params);
657 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100658 result == ErrorCode::INVALID_KEY_BLOB)
659 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000660 } else {
661 // The KeyMint implementation detected that the generated key
662 // is unusable.
663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
664 }
665 }
666 }
667 }
668}
669
670/*
671 * NewKeyGenerationTest.AesGcmMissingMinMac
672 *
673 * Verifies that specifying an invalid key size for AES key generation returns
674 * UNSUPPORTED_KEY_SIZE.
675 */
676TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
677 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
678 BlockMode block_mode = BlockMode::GCM;
679 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
680 SCOPED_TRACE(testing::Message()
681 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
682 vector<uint8_t> key_blob;
683 vector<KeyCharacteristics> key_characteristics;
684 // No MIN_MAC_LENGTH provided.
685 auto builder = AuthorizationSetBuilder()
686 .AesEncryptionKey(key_size)
687 .BlockMode(block_mode)
688 .Padding(padding_mode)
689 .SetDefaultValidity();
690 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
691 GenerateKey(builder, &key_blob, &key_characteristics));
692 }
693 }
694}
695
696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100697 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
698 *
699 * Verifies that specifying an invalid min MAC size for AES key generation returns
700 * UNSUPPORTED_MIN_MAC_LENGTH.
701 */
702TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
703 for (size_t min_mac_len : {88, 136}) {
704 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
705 BlockMode block_mode = BlockMode::GCM;
706 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
707 SCOPED_TRACE(testing::Message()
708 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
709 vector<uint8_t> key_blob;
710 vector<KeyCharacteristics> key_characteristics;
711 auto builder = AuthorizationSetBuilder()
712 .AesEncryptionKey(key_size)
713 .BlockMode(block_mode)
714 .Padding(padding_mode)
715 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
716 .SetDefaultValidity();
717 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
718 GenerateKey(builder, &key_blob, &key_characteristics));
719 }
720 }
721 }
722}
723
724/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000725 * NewKeyGenerationTest.TripleDes
726 *
727 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
728 * have correct characteristics.
729 */
730TEST_P(NewKeyGenerationTest, TripleDes) {
731 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
732 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
733 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
734 SCOPED_TRACE(testing::Message()
735 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
736 vector<uint8_t> key_blob;
737 vector<KeyCharacteristics> key_characteristics;
738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
739 .TripleDesEncryptionKey(key_size)
740 .BlockMode(block_mode)
741 .Padding(padding_mode)
742 .Authorization(TAG_NO_AUTH_REQUIRED)
743 .SetDefaultValidity(),
744 &key_blob, &key_characteristics));
745
746 EXPECT_GT(key_blob.size(), 0U);
747 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100748 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000749
750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
751
752 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
753 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
754 << "Key size " << key_size << "missing";
755
756 CheckedDeleteKey(&key_blob);
757 }
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.TripleDesWithAttestation
764 *
765 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
766 * have correct characteristics.
767 *
768 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
769 * put in a certificate) but which isn't an error.
770 */
771TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
772 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
773 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
774 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
775 SCOPED_TRACE(testing::Message()
776 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
777
778 auto challenge = "hello";
779 auto app_id = "foo";
780
781 vector<uint8_t> key_blob;
782 vector<KeyCharacteristics> key_characteristics;
783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
784 .TripleDesEncryptionKey(key_size)
785 .BlockMode(block_mode)
786 .Padding(padding_mode)
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AttestationChallenge(challenge)
789 .AttestationApplicationId(app_id)
790 .SetDefaultValidity(),
791 &key_blob, &key_characteristics));
792
793 EXPECT_GT(key_blob.size(), 0U);
794 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100795 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000796
797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
798
799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
800 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
801 << "Key size " << key_size << "missing";
802
803 CheckedDeleteKey(&key_blob);
804 }
805 }
806 }
807}
808
809/*
810 * NewKeyGenerationTest.TripleDesInvalidSize
811 *
812 * Verifies that specifying an invalid key size for 3-DES key generation returns
813 * UNSUPPORTED_KEY_SIZE.
814 */
815TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
816 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
817 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
818 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
819 SCOPED_TRACE(testing::Message()
820 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
821 vector<uint8_t> key_blob;
822 vector<KeyCharacteristics> key_characteristics;
823 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
824 GenerateKey(AuthorizationSetBuilder()
825 .TripleDesEncryptionKey(key_size)
826 .BlockMode(block_mode)
827 .Padding(padding_mode)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .SetDefaultValidity(),
830 &key_blob, &key_characteristics));
831 }
832 }
833 }
834
835 // Omitting the key size fails.
836 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
837 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
838 SCOPED_TRACE(testing::Message()
839 << "3DES-default-" << block_mode << "-" << padding_mode);
840 vector<uint8_t> key_blob;
841 vector<KeyCharacteristics> key_characteristics;
842 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
843 GenerateKey(AuthorizationSetBuilder()
844 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
845 .BlockMode(block_mode)
846 .Padding(padding_mode)
847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity(),
849 &key_blob, &key_characteristics));
850 }
851 }
852}
853
854/*
Selene Huang31ab4042020-04-29 04:22:39 -0700855 * NewKeyGenerationTest.Rsa
856 *
857 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
858 * have correct characteristics.
859 */
860TEST_P(NewKeyGenerationTest, Rsa) {
861 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
862 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700863 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
865 .RsaSigningKey(key_size, 65537)
866 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700869 &key_blob, &key_characteristics));
870
871 ASSERT_GT(key_blob.size(), 0U);
872 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100873 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700874
Shawn Willden7f424372021-01-10 18:06:50 -0700875 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
877 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
878 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
879 << "Key size " << key_size << "missing";
880 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
881
882 CheckedDeleteKey(&key_blob);
883 }
884}
885
886/*
Qi Wud22ec842020-11-26 13:27:53 +0800887 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100889 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
890 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891 */
892TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700893 auto challenge = "hello";
894 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700895
Selene Huang6e46f142021-04-20 19:20:11 -0700896 auto subject = "cert subj 2";
897 vector<uint8_t> subject_der(make_name_from_str(subject));
898
899 uint64_t serial_int = 66;
900 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
901
Selene Huang4f64c222021-04-13 19:54:36 -0700902 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700905 ASSERT_EQ(ErrorCode::OK,
906 GenerateKey(AuthorizationSetBuilder()
907 .RsaSigningKey(key_size, 65537)
908 .Digest(Digest::NONE)
909 .Padding(PaddingMode::NONE)
910 .AttestationChallenge(challenge)
911 .AttestationApplicationId(app_id)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
914 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
915 .SetDefaultValidity(),
916 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700917
918 ASSERT_GT(key_blob.size(), 0U);
919 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100920 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700921
922 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
923
924 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
925 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
926 << "Key size " << key_size << "missing";
927 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
928
Selene Huang6e46f142021-04-20 19:20:11 -0700929 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700930 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931 ASSERT_GT(cert_chain_.size(), 0);
932
933 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
934 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
935 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
936 sw_enforced, hw_enforced, SecLevel(),
937 cert_chain_[0].encodedCertificate));
938
939 CheckedDeleteKey(&key_blob);
940 }
941}
942
943/*
David Drysdale4dc01072021-04-01 12:17:35 +0100944 * NewKeyGenerationTest.RsaWithRpkAttestation
945 *
946 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
947 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale11860f22021-04-13 17:22:13 +0100948 *
949 * This test is disabled because the KeyMint specification does not require that implementations
950 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
951 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100952 */
David Drysdale11860f22021-04-13 17:22:13 +0100953TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100954 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
955 // instance.
956 std::shared_ptr<IRemotelyProvisionedComponent> rp;
957 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
958 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
959
960 // Generate a P-256 keypair to use as an attestation key.
961 MacedPublicKey macedPubKey;
962 std::vector<uint8_t> privateKeyBlob;
963 auto status =
964 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
965 ASSERT_TRUE(status.isOk());
966 vector<uint8_t> coseKeyData;
967 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
968
969 AttestationKey attestation_key;
970 attestation_key.keyBlob = std::move(privateKeyBlob);
971 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
972
973 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
974 auto challenge = "hello";
975 auto app_id = "foo";
976
977 vector<uint8_t> key_blob;
978 vector<KeyCharacteristics> key_characteristics;
979 ASSERT_EQ(ErrorCode::OK,
980 GenerateKey(AuthorizationSetBuilder()
981 .RsaSigningKey(key_size, 65537)
982 .Digest(Digest::NONE)
983 .Padding(PaddingMode::NONE)
984 .AttestationChallenge(challenge)
985 .AttestationApplicationId(app_id)
986 .Authorization(TAG_NO_AUTH_REQUIRED)
987 .SetDefaultValidity(),
988 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
989
990 ASSERT_GT(key_blob.size(), 0U);
991 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100992 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100993
994 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
995
996 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
997 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
998 << "Key size " << key_size << "missing";
999 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1000
1001 // Attestation by itself is not valid (last entry is not self-signed).
1002 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1003
1004 // The signature over the attested key should correspond to the P256 public key.
1005 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1006 ASSERT_TRUE(key_cert.get());
1007 EVP_PKEY_Ptr signing_pubkey;
1008 p256_pub_key(coseKeyData, &signing_pubkey);
1009 ASSERT_TRUE(signing_pubkey.get());
1010
1011 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1012 << "Verification of attested certificate failed "
1013 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1014
1015 CheckedDeleteKey(&key_blob);
1016 }
1017}
1018
1019/*
Selene Huang4f64c222021-04-13 19:54:36 -07001020 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1021 *
1022 * Verifies that keymint attestation for RSA encryption keys with challenge and
1023 * app id is also successful.
1024 */
1025TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1026 auto key_size = 2048;
1027 auto challenge = "hello";
1028 auto app_id = "foo";
1029
Selene Huang6e46f142021-04-20 19:20:11 -07001030 auto subject = "subj 2";
1031 vector<uint8_t> subject_der(make_name_from_str(subject));
1032
1033 uint64_t serial_int = 111166;
1034 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1035
Selene Huang4f64c222021-04-13 19:54:36 -07001036 vector<uint8_t> key_blob;
1037 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001038 ASSERT_EQ(ErrorCode::OK,
1039 GenerateKey(AuthorizationSetBuilder()
1040 .RsaEncryptionKey(key_size, 65537)
1041 .Padding(PaddingMode::NONE)
1042 .AttestationChallenge(challenge)
1043 .AttestationApplicationId(app_id)
1044 .Authorization(TAG_NO_AUTH_REQUIRED)
1045 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1046 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1047 .SetDefaultValidity(),
1048 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001049
1050 ASSERT_GT(key_blob.size(), 0U);
1051 AuthorizationSet auths;
1052 for (auto& entry : key_characteristics) {
1053 auths.push_back(AuthorizationSet(entry.authorizations));
1054 }
1055
1056 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1057 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1058
1059 // Verify that App data and ROT are NOT included.
1060 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1061 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1062
1063 // Check that some unexpected tags/values are NOT present.
1064 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1065 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1066
1067 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1068
1069 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1070 ASSERT_TRUE(os_ver);
1071 EXPECT_EQ(*os_ver, os_version());
1072
1073 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1074
1075 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1076 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1077 << "Key size " << key_size << "missing";
1078 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1079
Selene Huang6e46f142021-04-20 19:20:11 -07001080 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001081 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1082 ASSERT_GT(cert_chain_.size(), 0);
1083
1084 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1085 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1086 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1087 sw_enforced, hw_enforced, SecLevel(),
1088 cert_chain_[0].encodedCertificate));
1089
1090 CheckedDeleteKey(&key_blob);
1091}
1092
1093/*
1094 * NewKeyGenerationTest.RsaWithSelfSign
1095 *
1096 * Verifies that attesting to RSA key generation is successful, and returns
1097 * self signed certificate if no challenge is provided. And signing etc
1098 * works as expected.
1099 */
1100TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001101 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1102 vector<uint8_t> subject_der(make_name_from_str(subject));
1103
1104 uint64_t serial_int = 0;
1105 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1106
Selene Huang4f64c222021-04-13 19:54:36 -07001107 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1108 vector<uint8_t> key_blob;
1109 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001110 ASSERT_EQ(ErrorCode::OK,
1111 GenerateKey(AuthorizationSetBuilder()
1112 .RsaSigningKey(key_size, 65537)
1113 .Digest(Digest::NONE)
1114 .Padding(PaddingMode::NONE)
1115 .Authorization(TAG_NO_AUTH_REQUIRED)
1116 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1117 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1118 .SetDefaultValidity(),
1119 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001120
1121 ASSERT_GT(key_blob.size(), 0U);
1122 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001123 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001124
1125 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1126
1127 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1128 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1129 << "Key size " << key_size << "missing";
1130 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1131
Selene Huang6e46f142021-04-20 19:20:11 -07001132 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001133 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1134 ASSERT_EQ(cert_chain_.size(), 1);
1135
1136 CheckedDeleteKey(&key_blob);
1137 }
1138}
1139
1140/*
1141 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1142 *
1143 * Verifies that attesting to RSA checks for missing app ID.
1144 */
1145TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1146 auto challenge = "hello";
1147 vector<uint8_t> key_blob;
1148 vector<KeyCharacteristics> key_characteristics;
1149
1150 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1151 GenerateKey(AuthorizationSetBuilder()
1152 .RsaSigningKey(2048, 65537)
1153 .Digest(Digest::NONE)
1154 .Padding(PaddingMode::NONE)
1155 .AttestationChallenge(challenge)
1156 .Authorization(TAG_NO_AUTH_REQUIRED)
1157 .SetDefaultValidity(),
1158 &key_blob, &key_characteristics));
1159}
1160
1161/*
1162 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1163 *
1164 * Verifies that attesting to RSA ignores app id if challenge is missing.
1165 */
1166TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1167 auto key_size = 2048;
1168 auto app_id = "foo";
1169
Selene Huang6e46f142021-04-20 19:20:11 -07001170 auto subject = "cert subj 2";
1171 vector<uint8_t> subject_der(make_name_from_str(subject));
1172
1173 uint64_t serial_int = 1;
1174 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1175
Selene Huang4f64c222021-04-13 19:54:36 -07001176 vector<uint8_t> key_blob;
1177 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001178 ASSERT_EQ(ErrorCode::OK,
1179 GenerateKey(AuthorizationSetBuilder()
1180 .RsaSigningKey(key_size, 65537)
1181 .Digest(Digest::NONE)
1182 .Padding(PaddingMode::NONE)
1183 .AttestationApplicationId(app_id)
1184 .Authorization(TAG_NO_AUTH_REQUIRED)
1185 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1186 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1187 .SetDefaultValidity(),
1188 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001189
1190 ASSERT_GT(key_blob.size(), 0U);
1191 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001192 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001193
1194 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1195
1196 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1197 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1198 << "Key size " << key_size << "missing";
1199 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1200
Selene Huang6e46f142021-04-20 19:20:11 -07001201 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001202 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1203 ASSERT_EQ(cert_chain_.size(), 1);
1204
1205 CheckedDeleteKey(&key_blob);
1206}
1207
1208/*
Qi Wud22ec842020-11-26 13:27:53 +08001209 * NewKeyGenerationTest.LimitedUsageRsa
1210 *
1211 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1212 * resulting keys have correct characteristics.
1213 */
1214TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1215 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1216 vector<uint8_t> key_blob;
1217 vector<KeyCharacteristics> key_characteristics;
1218 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1219 .RsaSigningKey(key_size, 65537)
1220 .Digest(Digest::NONE)
1221 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001222 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1223 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001224 &key_blob, &key_characteristics));
1225
1226 ASSERT_GT(key_blob.size(), 0U);
1227 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001228 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001229
1230 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1231
1232 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1233 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1234 << "Key size " << key_size << "missing";
1235 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1236
1237 // Check the usage count limit tag appears in the authorizations.
1238 AuthorizationSet auths;
1239 for (auto& entry : key_characteristics) {
1240 auths.push_back(AuthorizationSet(entry.authorizations));
1241 }
1242 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1243 << "key usage count limit " << 1U << " missing";
1244
1245 CheckedDeleteKey(&key_blob);
1246 }
1247}
1248
1249/*
Qi Wubeefae42021-01-28 23:16:37 +08001250 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1251 *
1252 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1253 * resulting keys have correct characteristics and attestation.
1254 */
1255TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001256 auto challenge = "hello";
1257 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001258
Selene Huang6e46f142021-04-20 19:20:11 -07001259 auto subject = "cert subj 2";
1260 vector<uint8_t> subject_der(make_name_from_str(subject));
1261
1262 uint64_t serial_int = 66;
1263 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1264
Selene Huang4f64c222021-04-13 19:54:36 -07001265 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001266 vector<uint8_t> key_blob;
1267 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001268 ASSERT_EQ(ErrorCode::OK,
1269 GenerateKey(AuthorizationSetBuilder()
1270 .RsaSigningKey(key_size, 65537)
1271 .Digest(Digest::NONE)
1272 .Padding(PaddingMode::NONE)
1273 .AttestationChallenge(challenge)
1274 .AttestationApplicationId(app_id)
1275 .Authorization(TAG_NO_AUTH_REQUIRED)
1276 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1277 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1278 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1279 .SetDefaultValidity(),
1280 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001281
1282 ASSERT_GT(key_blob.size(), 0U);
1283 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001284 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001285
1286 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1287
1288 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1289 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1290 << "Key size " << key_size << "missing";
1291 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1292
1293 // Check the usage count limit tag appears in the authorizations.
1294 AuthorizationSet auths;
1295 for (auto& entry : key_characteristics) {
1296 auths.push_back(AuthorizationSet(entry.authorizations));
1297 }
1298 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1299 << "key usage count limit " << 1U << " missing";
1300
1301 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001302 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001303 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001304 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001305
1306 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1307 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1308 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1309 sw_enforced, hw_enforced, SecLevel(),
1310 cert_chain_[0].encodedCertificate));
1311
1312 CheckedDeleteKey(&key_blob);
1313 }
1314}
1315
1316/*
Selene Huang31ab4042020-04-29 04:22:39 -07001317 * NewKeyGenerationTest.NoInvalidRsaSizes
1318 *
1319 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1320 */
1321TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1322 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1323 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001324 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001325 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1326 GenerateKey(AuthorizationSetBuilder()
1327 .RsaSigningKey(key_size, 65537)
1328 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001329 .Padding(PaddingMode::NONE)
1330 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001331 &key_blob, &key_characteristics));
1332 }
1333}
1334
1335/*
1336 * NewKeyGenerationTest.RsaNoDefaultSize
1337 *
1338 * Verifies that failing to specify a key size for RSA key generation returns
1339 * UNSUPPORTED_KEY_SIZE.
1340 */
1341TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1342 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1343 GenerateKey(AuthorizationSetBuilder()
1344 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1345 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001346 .SigningKey()
1347 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001348}
1349
1350/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001351 * NewKeyGenerationTest.RsaMissingParams
1352 *
1353 * Verifies that omitting optional tags works.
1354 */
1355TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1356 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1357 ASSERT_EQ(ErrorCode::OK,
1358 GenerateKey(
1359 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1360 CheckedDeleteKey();
1361 }
1362}
1363
1364/*
Selene Huang31ab4042020-04-29 04:22:39 -07001365 * NewKeyGenerationTest.Ecdsa
1366 *
1367 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1368 * have correct characteristics.
1369 */
1370TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001371 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001372 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001373 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001375 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 .Digest(Digest::NONE)
1377 .SetDefaultValidity(),
1378 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001379 ASSERT_GT(key_blob.size(), 0U);
1380 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001381 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001382
Shawn Willden7f424372021-01-10 18:06:50 -07001383 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
1385 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001386 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001387
1388 CheckedDeleteKey(&key_blob);
1389 }
1390}
1391
1392/*
Selene Huang4f64c222021-04-13 19:54:36 -07001393 * NewKeyGenerationTest.EcdsaAttestation
1394 *
1395 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1396 * an attestation will be generated.
1397 */
1398TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1399 auto challenge = "hello";
1400 auto app_id = "foo";
1401
Selene Huang6e46f142021-04-20 19:20:11 -07001402 auto subject = "cert subj 2";
1403 vector<uint8_t> subject_der(make_name_from_str(subject));
1404
1405 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1406 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1407
David Drysdale308916b2021-06-08 15:46:11 +01001408 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001409 vector<uint8_t> key_blob;
1410 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001411 ASSERT_EQ(ErrorCode::OK,
1412 GenerateKey(AuthorizationSetBuilder()
1413 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001414 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001415 .Digest(Digest::NONE)
1416 .AttestationChallenge(challenge)
1417 .AttestationApplicationId(app_id)
1418 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1419 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1420 .SetDefaultValidity(),
1421 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001422 ASSERT_GT(key_blob.size(), 0U);
1423 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001424 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001425
1426 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1427
1428 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001429 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001430
1431 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1432 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001433 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001434
1435 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1436 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1437 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1438 sw_enforced, hw_enforced, SecLevel(),
1439 cert_chain_[0].encodedCertificate));
1440
1441 CheckedDeleteKey(&key_blob);
1442 }
1443}
1444
1445/*
David Drysdale92464372021-05-14 16:46:59 +01001446 * NewKeyGenerationTest.EcdsaAttestationTags
1447 *
1448 * Verifies that creation of an attested ECDSA key includes various tags in the
1449 * attestation extension.
1450 */
1451TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1452 auto challenge = "hello";
1453 auto app_id = "foo";
1454 auto subject = "cert subj 2";
1455 vector<uint8_t> subject_der(make_name_from_str(subject));
1456 uint64_t serial_int = 0x1010;
1457 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1458 const AuthorizationSetBuilder base_builder =
1459 AuthorizationSetBuilder()
1460 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001461 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001462 .Digest(Digest::NONE)
1463 .AttestationChallenge(challenge)
1464 .AttestationApplicationId(app_id)
1465 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1466 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1467 .SetDefaultValidity();
1468
1469 // Various tags that map to fields in the attestation extension ASN.1 schema.
1470 auto extra_tags = AuthorizationSetBuilder()
1471 .Authorization(TAG_ROLLBACK_RESISTANCE)
1472 .Authorization(TAG_EARLY_BOOT_ONLY)
1473 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1474 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1475 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1476 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1477 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1478 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1479 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1480 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1481 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1482 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1483 for (const KeyParameter& tag : extra_tags) {
1484 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1485 vector<uint8_t> key_blob;
1486 vector<KeyCharacteristics> key_characteristics;
1487 AuthorizationSetBuilder builder = base_builder;
1488 builder.push_back(tag);
1489 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1490 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1491 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1492 continue;
1493 }
Seth Moore3dbdaa92021-07-12 14:18:28 -07001494 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1495 // Tag not required to be supported by all KeyMint implementations.
David Drysdale92464372021-05-14 16:46:59 +01001496 continue;
1497 }
1498 ASSERT_EQ(result, ErrorCode::OK);
1499 ASSERT_GT(key_blob.size(), 0U);
1500
1501 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1502 ASSERT_GT(cert_chain_.size(), 0);
1503 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1504
1505 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1506 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Moore3dbdaa92021-07-12 14:18:28 -07001507 // Some tags are optional, so don't require them to be in the enforcements.
1508 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale92464372021-05-14 16:46:59 +01001509 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1510 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1511 }
1512
1513 // Verifying the attestation record will check for the specific tag because
1514 // it's included in the authorizations.
1515 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1516 SecLevel(), cert_chain_[0].encodedCertificate));
1517
1518 CheckedDeleteKey(&key_blob);
1519 }
1520
1521 // Device attestation IDs should be rejected for normal attestation requests; these fields
1522 // are only used for device unique attestation.
1523 auto invalid_tags = AuthorizationSetBuilder()
1524 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1525 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1526 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1527 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1528 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1529 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1530 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1531 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1532 for (const KeyParameter& tag : invalid_tags) {
1533 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1534 vector<uint8_t> key_blob;
1535 vector<KeyCharacteristics> key_characteristics;
1536 AuthorizationSetBuilder builder =
1537 AuthorizationSetBuilder()
1538 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001539 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001540 .Digest(Digest::NONE)
1541 .AttestationChallenge(challenge)
1542 .AttestationApplicationId(app_id)
1543 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1544 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1545 .SetDefaultValidity();
1546 builder.push_back(tag);
1547 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1548 GenerateKey(builder, &key_blob, &key_characteristics));
1549 }
1550}
1551
1552/*
1553 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1554 *
1555 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1556 */
1557TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1558 auto challenge = "hello";
1559 auto attest_app_id = "foo";
1560 auto subject = "cert subj 2";
1561 vector<uint8_t> subject_der(make_name_from_str(subject));
1562 uint64_t serial_int = 0x1010;
1563 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1564
1565 // Earlier versions of the attestation extension schema included a slot:
1566 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1567 // This should never have been included, and should never be filled in.
1568 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1569 // to confirm that this field never makes it into the attestation extension.
1570 vector<uint8_t> key_blob;
1571 vector<KeyCharacteristics> key_characteristics;
1572 auto result = GenerateKey(AuthorizationSetBuilder()
1573 .Authorization(TAG_NO_AUTH_REQUIRED)
1574 .EcdsaSigningKey(EcCurve::P_256)
1575 .Digest(Digest::NONE)
1576 .AttestationChallenge(challenge)
1577 .AttestationApplicationId(attest_app_id)
1578 .Authorization(TAG_APPLICATION_ID, "client_id")
1579 .Authorization(TAG_APPLICATION_DATA, "appdata")
1580 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1581 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1582 .SetDefaultValidity(),
1583 &key_blob, &key_characteristics);
1584 ASSERT_EQ(result, ErrorCode::OK);
1585 ASSERT_GT(key_blob.size(), 0U);
1586
1587 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1588 ASSERT_GT(cert_chain_.size(), 0);
1589 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1590
1591 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1592 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1593 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1594 SecLevel(), cert_chain_[0].encodedCertificate));
1595
1596 // Check that the app id is not in the cert.
1597 string app_id = "clientid";
1598 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1599 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1600 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1601 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1602 cert_chain_[0].encodedCertificate.end());
1603
1604 CheckedDeleteKey(&key_blob);
1605}
1606
1607/*
Selene Huang4f64c222021-04-13 19:54:36 -07001608 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1609 *
1610 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1611 * the key will generate a self signed attestation.
1612 */
1613TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001614 auto subject = "cert subj 2";
1615 vector<uint8_t> subject_der(make_name_from_str(subject));
1616
1617 uint64_t serial_int = 0x123456FFF1234;
1618 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1619
David Drysdale308916b2021-06-08 15:46:11 +01001620 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001621 vector<uint8_t> key_blob;
1622 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001623 ASSERT_EQ(ErrorCode::OK,
1624 GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001625 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001626 .Digest(Digest::NONE)
1627 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1628 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1629 .SetDefaultValidity(),
1630 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001631 ASSERT_GT(key_blob.size(), 0U);
1632 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001633 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001634
1635 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1636
1637 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001638 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001639
1640 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001641 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001642 ASSERT_EQ(cert_chain_.size(), 1);
1643
1644 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1645 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1646
1647 CheckedDeleteKey(&key_blob);
1648 }
1649}
1650
1651/*
1652 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1653 *
1654 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1655 * app id must also be provided or else it will fail.
1656 */
1657TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1658 auto challenge = "hello";
1659 vector<uint8_t> key_blob;
1660 vector<KeyCharacteristics> key_characteristics;
1661
1662 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1663 GenerateKey(AuthorizationSetBuilder()
1664 .EcdsaSigningKey(EcCurve::P_256)
1665 .Digest(Digest::NONE)
1666 .AttestationChallenge(challenge)
1667 .SetDefaultValidity(),
1668 &key_blob, &key_characteristics));
1669}
1670
1671/*
1672 * NewKeyGenerationTest.EcdsaIgnoreAppId
1673 *
1674 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1675 * any appid will be ignored, and keymint will generate a self sign certificate.
1676 */
1677TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1678 auto app_id = "foo";
1679
David Drysdale308916b2021-06-08 15:46:11 +01001680 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001681 vector<uint8_t> key_blob;
1682 vector<KeyCharacteristics> key_characteristics;
1683 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001684 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001685 .Digest(Digest::NONE)
1686 .AttestationApplicationId(app_id)
1687 .SetDefaultValidity(),
1688 &key_blob, &key_characteristics));
1689
1690 ASSERT_GT(key_blob.size(), 0U);
1691 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001692 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001693
1694 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1695
1696 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001697 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001698
1699 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1700 ASSERT_EQ(cert_chain_.size(), 1);
1701
1702 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1703 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1704
1705 CheckedDeleteKey(&key_blob);
1706 }
1707}
1708
1709/*
1710 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1711 *
1712 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1713 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1714 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1715 * to specify how many following bytes will be used to encode the length.
1716 */
1717TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1718 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001719 std::vector<uint32_t> app_id_lengths{143, 258};
1720
1721 for (uint32_t length : app_id_lengths) {
1722 const string app_id(length, 'a');
1723 vector<uint8_t> key_blob;
1724 vector<KeyCharacteristics> key_characteristics;
1725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1726 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001727 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001728 .Digest(Digest::NONE)
1729 .AttestationChallenge(challenge)
1730 .AttestationApplicationId(app_id)
1731 .SetDefaultValidity(),
1732 &key_blob, &key_characteristics));
1733 ASSERT_GT(key_blob.size(), 0U);
1734 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001735 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001736
1737 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1738
1739 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001740 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001741
1742 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1743 ASSERT_GT(cert_chain_.size(), 0);
1744
1745 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1746 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1747 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1748 sw_enforced, hw_enforced, SecLevel(),
1749 cert_chain_[0].encodedCertificate));
1750
1751 CheckedDeleteKey(&key_blob);
1752 }
1753}
1754
1755/*
Qi Wud22ec842020-11-26 13:27:53 +08001756 * NewKeyGenerationTest.LimitedUsageEcdsa
1757 *
1758 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1759 * resulting keys have correct characteristics.
1760 */
1761TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001762 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001763 vector<uint8_t> key_blob;
1764 vector<KeyCharacteristics> key_characteristics;
1765 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001766 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001767 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001768 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1769 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001770 &key_blob, &key_characteristics));
1771
1772 ASSERT_GT(key_blob.size(), 0U);
1773 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001774 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001775
1776 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1777
1778 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001779 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001780
1781 // Check the usage count limit tag appears in the authorizations.
1782 AuthorizationSet auths;
1783 for (auto& entry : key_characteristics) {
1784 auths.push_back(AuthorizationSet(entry.authorizations));
1785 }
1786 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1787 << "key usage count limit " << 1U << " missing";
1788
1789 CheckedDeleteKey(&key_blob);
1790 }
1791}
1792
1793/*
Selene Huang31ab4042020-04-29 04:22:39 -07001794 * NewKeyGenerationTest.EcdsaDefaultSize
1795 *
David Drysdale308916b2021-06-08 15:46:11 +01001796 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001797 * UNSUPPORTED_KEY_SIZE.
1798 */
1799TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1800 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1801 GenerateKey(AuthorizationSetBuilder()
1802 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1803 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001804 .Digest(Digest::NONE)
1805 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001806}
1807
1808/*
1809 * NewKeyGenerationTest.EcdsaInvalidSize
1810 *
1811 * Verifies that specifying an invalid key size for EC key generation returns
1812 * UNSUPPORTED_KEY_SIZE.
1813 */
1814TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdale308916b2021-06-08 15:46:11 +01001815 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001816 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001817 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001818 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001819 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001820 .Digest(Digest::NONE)
1821 .SetDefaultValidity(),
1822 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001823 }
1824
David Drysdale308916b2021-06-08 15:46:11 +01001825 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1826 GenerateKey(AuthorizationSetBuilder()
1827 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1828 .Authorization(TAG_KEY_SIZE, 190)
1829 .SigningKey()
1830 .Digest(Digest::NONE)
1831 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001832}
1833
1834/*
1835 * NewKeyGenerationTest.EcdsaMismatchKeySize
1836 *
1837 * Verifies that specifying mismatched key size and curve for EC key generation returns
1838 * INVALID_ARGUMENT.
1839 */
1840TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1841 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1842
David Drysdale308916b2021-06-08 15:46:11 +01001843 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleca76a752021-08-18 16:45:50 +01001844 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdale308916b2021-06-08 15:46:11 +01001845 .Authorization(TAG_KEY_SIZE, 224)
1846 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleca76a752021-08-18 16:45:50 +01001847 .SigningKey()
David Drysdale308916b2021-06-08 15:46:11 +01001848 .Digest(Digest::NONE)
1849 .SetDefaultValidity());
David Drysdaleca76a752021-08-18 16:45:50 +01001850 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001851}
1852
1853/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001854 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001855 *
1856 * Verifies that keymint does not support any curve designated as unsupported.
1857 */
1858TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1859 Digest digest;
1860 if (SecLevel() == SecurityLevel::STRONGBOX) {
1861 digest = Digest::SHA_2_256;
1862 } else {
1863 digest = Digest::SHA_2_512;
1864 }
1865 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001866 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1867 .EcdsaSigningKey(curve)
1868 .Digest(digest)
1869 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001870 << "Failed to generate key on curve: " << curve;
1871 CheckedDeleteKey();
1872 }
1873}
1874
1875/*
1876 * NewKeyGenerationTest.Hmac
1877 *
1878 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1879 * characteristics.
1880 */
1881TEST_P(NewKeyGenerationTest, Hmac) {
1882 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1883 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001884 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001885 constexpr size_t key_size = 128;
1886 ASSERT_EQ(ErrorCode::OK,
1887 GenerateKey(
1888 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1889 TAG_MIN_MAC_LENGTH, 128),
1890 &key_blob, &key_characteristics));
1891
1892 ASSERT_GT(key_blob.size(), 0U);
1893 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001894 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001895
Shawn Willden7f424372021-01-10 18:06:50 -07001896 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1897 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1898 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1899 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001900
1901 CheckedDeleteKey(&key_blob);
1902 }
1903}
1904
1905/*
Selene Huang4f64c222021-04-13 19:54:36 -07001906 * NewKeyGenerationTest.HmacNoAttestation
1907 *
1908 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1909 * and app id are provided.
1910 */
1911TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1912 auto challenge = "hello";
1913 auto app_id = "foo";
1914
1915 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1916 vector<uint8_t> key_blob;
1917 vector<KeyCharacteristics> key_characteristics;
1918 constexpr size_t key_size = 128;
1919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1920 .HmacKey(key_size)
1921 .Digest(digest)
1922 .AttestationChallenge(challenge)
1923 .AttestationApplicationId(app_id)
1924 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1925 &key_blob, &key_characteristics));
1926
1927 ASSERT_GT(key_blob.size(), 0U);
1928 ASSERT_EQ(cert_chain_.size(), 0);
1929 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001930 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001931
1932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1935 << "Key size " << key_size << "missing";
1936
1937 CheckedDeleteKey(&key_blob);
1938 }
1939}
1940
1941/*
Qi Wud22ec842020-11-26 13:27:53 +08001942 * NewKeyGenerationTest.LimitedUsageHmac
1943 *
1944 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1945 * resulting keys have correct characteristics.
1946 */
1947TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1948 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1949 vector<uint8_t> key_blob;
1950 vector<KeyCharacteristics> key_characteristics;
1951 constexpr size_t key_size = 128;
1952 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1953 .HmacKey(key_size)
1954 .Digest(digest)
1955 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1956 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1957 &key_blob, &key_characteristics));
1958
1959 ASSERT_GT(key_blob.size(), 0U);
1960 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001961 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001962
1963 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1964 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1965 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1966 << "Key size " << key_size << "missing";
1967
1968 // Check the usage count limit tag appears in the authorizations.
1969 AuthorizationSet auths;
1970 for (auto& entry : key_characteristics) {
1971 auths.push_back(AuthorizationSet(entry.authorizations));
1972 }
1973 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1974 << "key usage count limit " << 1U << " missing";
1975
1976 CheckedDeleteKey(&key_blob);
1977 }
1978}
1979
1980/*
Selene Huang31ab4042020-04-29 04:22:39 -07001981 * NewKeyGenerationTest.HmacCheckKeySizes
1982 *
1983 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1984 */
1985TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1986 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1987 if (key_size < 64 || key_size % 8 != 0) {
1988 // To keep this test from being very slow, we only test a random fraction of
1989 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1990 // them, we expect to run ~40 of them in each run.
1991 if (key_size % 8 == 0 || random() % 10 == 0) {
1992 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1993 GenerateKey(AuthorizationSetBuilder()
1994 .HmacKey(key_size)
1995 .Digest(Digest::SHA_2_256)
1996 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1997 << "HMAC key size " << key_size << " invalid";
1998 }
1999 } else {
2000 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2001 .HmacKey(key_size)
2002 .Digest(Digest::SHA_2_256)
2003 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2004 << "Failed to generate HMAC key of size " << key_size;
2005 CheckedDeleteKey();
2006 }
2007 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002008 if (SecLevel() == SecurityLevel::STRONGBOX) {
2009 // STRONGBOX devices must not support keys larger than 512 bits.
2010 size_t key_size = 520;
2011 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2012 GenerateKey(AuthorizationSetBuilder()
2013 .HmacKey(key_size)
2014 .Digest(Digest::SHA_2_256)
2015 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2016 << "HMAC key size " << key_size << " unexpectedly valid";
2017 }
Selene Huang31ab4042020-04-29 04:22:39 -07002018}
2019
2020/*
2021 * NewKeyGenerationTest.HmacCheckMinMacLengths
2022 *
2023 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2024 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2025 * specific MAC length that failed, so reproducing a failed run will be easy.
2026 */
2027TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2028 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2029 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2030 // To keep this test from being very long, we only test a random fraction of
2031 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2032 // we expect to run ~17 of them in each run.
2033 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2034 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2035 GenerateKey(AuthorizationSetBuilder()
2036 .HmacKey(128)
2037 .Digest(Digest::SHA_2_256)
2038 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2039 << "HMAC min mac length " << min_mac_length << " invalid.";
2040 }
2041 } else {
2042 EXPECT_EQ(ErrorCode::OK,
2043 GenerateKey(AuthorizationSetBuilder()
2044 .HmacKey(128)
2045 .Digest(Digest::SHA_2_256)
2046 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2047 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2048 CheckedDeleteKey();
2049 }
2050 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002051
2052 // Minimum MAC length must be no more than 512 bits.
2053 size_t min_mac_length = 520;
2054 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2055 GenerateKey(AuthorizationSetBuilder()
2056 .HmacKey(128)
2057 .Digest(Digest::SHA_2_256)
2058 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2059 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002060}
2061
2062/*
2063 * NewKeyGenerationTest.HmacMultipleDigests
2064 *
2065 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2066 */
2067TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2068 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2069
2070 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2071 GenerateKey(AuthorizationSetBuilder()
2072 .HmacKey(128)
2073 .Digest(Digest::SHA1)
2074 .Digest(Digest::SHA_2_256)
2075 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2076}
2077
2078/*
2079 * NewKeyGenerationTest.HmacDigestNone
2080 *
2081 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2082 */
2083TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2084 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2085 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2086 128)));
2087
2088 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2089 GenerateKey(AuthorizationSetBuilder()
2090 .HmacKey(128)
2091 .Digest(Digest::NONE)
2092 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2093}
2094
Selene Huang4f64c222021-04-13 19:54:36 -07002095/*
2096 * NewKeyGenerationTest.AesNoAttestation
2097 *
2098 * Verifies that attestation parameters to AES keys are ignored and generateKey
2099 * will succeed.
2100 */
2101TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2102 auto challenge = "hello";
2103 auto app_id = "foo";
2104
2105 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2106 .Authorization(TAG_NO_AUTH_REQUIRED)
2107 .AesEncryptionKey(128)
2108 .EcbMode()
2109 .Padding(PaddingMode::PKCS7)
2110 .AttestationChallenge(challenge)
2111 .AttestationApplicationId(app_id)));
2112
2113 ASSERT_EQ(cert_chain_.size(), 0);
2114}
2115
2116/*
2117 * NewKeyGenerationTest.TripleDesNoAttestation
2118 *
2119 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2120 * will be successful. No attestation should be generated.
2121 */
2122TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2123 auto challenge = "hello";
2124 auto app_id = "foo";
2125
2126 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2127 .TripleDesEncryptionKey(168)
2128 .BlockMode(BlockMode::ECB)
2129 .Authorization(TAG_NO_AUTH_REQUIRED)
2130 .Padding(PaddingMode::NONE)
2131 .AttestationChallenge(challenge)
2132 .AttestationApplicationId(app_id)));
2133 ASSERT_EQ(cert_chain_.size(), 0);
2134}
2135
Selene Huang31ab4042020-04-29 04:22:39 -07002136INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2137
2138typedef KeyMintAidlTestBase SigningOperationsTest;
2139
2140/*
2141 * SigningOperationsTest.RsaSuccess
2142 *
2143 * Verifies that raw RSA signature operations succeed.
2144 */
2145TEST_P(SigningOperationsTest, RsaSuccess) {
2146 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2147 .RsaSigningKey(2048, 65537)
2148 .Digest(Digest::NONE)
2149 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002150 .Authorization(TAG_NO_AUTH_REQUIRED)
2151 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002152 string message = "12345678901234567890123456789012";
2153 string signature = SignMessage(
2154 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdalefe42aa32021-05-06 08:10:58 +01002155 LocalVerifyMessage(message, signature,
2156 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2157}
2158
2159/*
2160 * SigningOperationsTest.RsaAllPaddingsAndDigests
2161 *
2162 * Verifies RSA signature/verification for all padding modes and digests.
2163 */
2164TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2165 auto authorizations = AuthorizationSetBuilder()
2166 .Authorization(TAG_NO_AUTH_REQUIRED)
2167 .RsaSigningKey(2048, 65537)
2168 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2169 .Padding(PaddingMode::NONE)
2170 .Padding(PaddingMode::RSA_PSS)
2171 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2172 .SetDefaultValidity();
2173
2174 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2175
2176 string message(128, 'a');
2177 string corrupt_message(message);
2178 ++corrupt_message[corrupt_message.size() / 2];
2179
2180 for (auto padding :
2181 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2182 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2183 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2184 // Digesting only makes sense with padding.
2185 continue;
2186 }
2187
2188 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2189 // PSS requires digesting.
2190 continue;
2191 }
2192
2193 string signature =
2194 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2195 LocalVerifyMessage(message, signature,
2196 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2197 }
2198 }
Selene Huang31ab4042020-04-29 04:22:39 -07002199}
2200
2201/*
2202 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2203 *
Shawn Willden7f424372021-01-10 18:06:50 -07002204 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002205 */
2206TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2208 .Authorization(TAG_NO_AUTH_REQUIRED)
2209 .RsaSigningKey(2048, 65537)
2210 .Digest(Digest::NONE)
2211 .Padding(PaddingMode::NONE)
2212 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002213 .Authorization(TAG_APPLICATION_DATA, "appdata")
2214 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002215
2216 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2217
Selene Huang31ab4042020-04-29 04:22:39 -07002218 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2219 Begin(KeyPurpose::SIGN,
2220 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2221 AbortIfNeeded();
2222 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2223 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2224 .Digest(Digest::NONE)
2225 .Padding(PaddingMode::NONE)
2226 .Authorization(TAG_APPLICATION_ID, "clientid")));
2227 AbortIfNeeded();
2228 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2229 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2230 .Digest(Digest::NONE)
2231 .Padding(PaddingMode::NONE)
2232 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2233 AbortIfNeeded();
2234 EXPECT_EQ(ErrorCode::OK,
2235 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2236 .Digest(Digest::NONE)
2237 .Padding(PaddingMode::NONE)
2238 .Authorization(TAG_APPLICATION_DATA, "appdata")
2239 .Authorization(TAG_APPLICATION_ID, "clientid")));
2240 AbortIfNeeded();
2241}
2242
2243/*
2244 * SigningOperationsTest.RsaPssSha256Success
2245 *
2246 * Verifies that RSA-PSS signature operations succeed.
2247 */
2248TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2249 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2250 .RsaSigningKey(2048, 65537)
2251 .Digest(Digest::SHA_2_256)
2252 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002253 .Authorization(TAG_NO_AUTH_REQUIRED)
2254 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002255 // Use large message, which won't work without digesting.
2256 string message(1024, 'a');
2257 string signature = SignMessage(
2258 message,
2259 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2260}
2261
2262/*
2263 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2264 *
2265 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2266 * supports only unpadded operations.
2267 */
2268TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2270 .RsaSigningKey(2048, 65537)
2271 .Digest(Digest::NONE)
2272 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002273 .Padding(PaddingMode::NONE)
2274 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002275 string message = "12345678901234567890123456789012";
2276 string signature;
2277
2278 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2279 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2280 .Digest(Digest::NONE)
2281 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2282}
2283
2284/*
2285 * SigningOperationsTest.NoUserConfirmation
2286 *
2287 * Verifies that keymint rejects signing operations for keys with
2288 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2289 * presented.
2290 */
2291TEST_P(SigningOperationsTest, NoUserConfirmation) {
2292 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2294 .RsaSigningKey(1024, 65537)
2295 .Digest(Digest::NONE)
2296 .Padding(PaddingMode::NONE)
2297 .Authorization(TAG_NO_AUTH_REQUIRED)
2298 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2299 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002300
2301 const string message = "12345678901234567890123456789012";
2302 EXPECT_EQ(ErrorCode::OK,
2303 Begin(KeyPurpose::SIGN,
2304 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2305 string signature;
2306 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2307}
2308
2309/*
2310 * SigningOperationsTest.RsaPkcs1Sha256Success
2311 *
2312 * Verifies that digested RSA-PKCS1 signature operations succeed.
2313 */
2314TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2316 .RsaSigningKey(2048, 65537)
2317 .Digest(Digest::SHA_2_256)
2318 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002319 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2320 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002321 string message(1024, 'a');
2322 string signature = SignMessage(message, AuthorizationSetBuilder()
2323 .Digest(Digest::SHA_2_256)
2324 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2325}
2326
2327/*
2328 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2329 *
2330 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2331 */
2332TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2334 .RsaSigningKey(2048, 65537)
2335 .Digest(Digest::NONE)
2336 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002337 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2338 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002339 string message(53, 'a');
2340 string signature = SignMessage(message, AuthorizationSetBuilder()
2341 .Digest(Digest::NONE)
2342 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2343}
2344
2345/*
2346 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2347 *
2348 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2349 * given a too-long message.
2350 */
2351TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2353 .RsaSigningKey(2048, 65537)
2354 .Digest(Digest::NONE)
2355 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002356 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2357 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002358 string message(257, 'a');
2359
2360 EXPECT_EQ(ErrorCode::OK,
2361 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2362 .Digest(Digest::NONE)
2363 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2364 string signature;
2365 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2366}
2367
2368/*
2369 * SigningOperationsTest.RsaPssSha512TooSmallKey
2370 *
2371 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2372 * used with a key that is too small for the message.
2373 *
2374 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2375 * keymint specification requires that salt_size == digest_size, so the message will be
2376 * digest_size * 2 +
2377 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2378 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2379 * for a 1024-bit key.
2380 */
2381TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2382 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2383 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2384 .RsaSigningKey(1024, 65537)
2385 .Digest(Digest::SHA_2_512)
2386 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002387 .Padding(PaddingMode::RSA_PSS)
2388 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002389 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2390 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2391 .Digest(Digest::SHA_2_512)
2392 .Padding(PaddingMode::RSA_PSS)));
2393}
2394
2395/*
2396 * SigningOperationsTest.RsaNoPaddingTooLong
2397 *
2398 * Verifies that raw RSA signature operations fail with the correct error code when
2399 * given a too-long message.
2400 */
2401TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2403 .RsaSigningKey(2048, 65537)
2404 .Digest(Digest::NONE)
2405 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002406 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2407 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002408 // One byte too long
2409 string message(2048 / 8 + 1, 'a');
2410 ASSERT_EQ(ErrorCode::OK,
2411 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2412 .Digest(Digest::NONE)
2413 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2414 string result;
2415 ErrorCode finish_error_code = Finish(message, &result);
2416 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2417 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2418
2419 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2420 message = string(128 * 1024, 'a');
2421 ASSERT_EQ(ErrorCode::OK,
2422 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2423 .Digest(Digest::NONE)
2424 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2425 finish_error_code = Finish(message, &result);
2426 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2427 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2428}
2429
2430/*
2431 * SigningOperationsTest.RsaAbort
2432 *
2433 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2434 * test, but the behavior should be algorithm and purpose-independent.
2435 */
2436TEST_P(SigningOperationsTest, RsaAbort) {
2437 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2438 .RsaSigningKey(2048, 65537)
2439 .Digest(Digest::NONE)
2440 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002441 .Padding(PaddingMode::NONE)
2442 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002443
2444 ASSERT_EQ(ErrorCode::OK,
2445 Begin(KeyPurpose::SIGN,
2446 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2447 EXPECT_EQ(ErrorCode::OK, Abort());
2448
2449 // Another abort should fail
2450 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2451
2452 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002453 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002454}
2455
2456/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002457 * SigningOperationsTest.RsaNonUniqueParams
2458 *
2459 * Verifies that an operation with multiple padding modes is rejected.
2460 */
2461TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2462 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2463 .RsaSigningKey(2048, 65537)
2464 .Digest(Digest::NONE)
2465 .Digest(Digest::SHA1)
2466 .Authorization(TAG_NO_AUTH_REQUIRED)
2467 .Padding(PaddingMode::NONE)
2468 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2469 .SetDefaultValidity()));
2470
2471 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2472 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2473 .Digest(Digest::NONE)
2474 .Padding(PaddingMode::NONE)
2475 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2476
Tommy Chiu3b56cbc2021-05-11 18:36:50 +08002477 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2478 .Digest(Digest::NONE)
2479 .Digest(Digest::SHA1)
2480 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2481 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002482
2483 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2484 Begin(KeyPurpose::SIGN,
2485 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2486}
2487
2488/*
Selene Huang31ab4042020-04-29 04:22:39 -07002489 * SigningOperationsTest.RsaUnsupportedPadding
2490 *
2491 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2492 * with a padding mode inappropriate for RSA.
2493 */
2494TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2496 .RsaSigningKey(2048, 65537)
2497 .Authorization(TAG_NO_AUTH_REQUIRED)
2498 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002499 .Padding(PaddingMode::PKCS7)
2500 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002501 ASSERT_EQ(
2502 ErrorCode::UNSUPPORTED_PADDING_MODE,
2503 Begin(KeyPurpose::SIGN,
2504 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002505 CheckedDeleteKey();
2506
2507 ASSERT_EQ(ErrorCode::OK,
2508 GenerateKey(
2509 AuthorizationSetBuilder()
2510 .RsaSigningKey(2048, 65537)
2511 .Authorization(TAG_NO_AUTH_REQUIRED)
2512 .Digest(Digest::SHA_2_256 /* supported digest */)
2513 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2514 .SetDefaultValidity()));
2515 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2516 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2517 .Digest(Digest::SHA_2_256)
2518 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002519}
2520
2521/*
2522 * SigningOperationsTest.RsaPssNoDigest
2523 *
2524 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2525 */
2526TEST_P(SigningOperationsTest, RsaNoDigest) {
2527 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2528 .RsaSigningKey(2048, 65537)
2529 .Authorization(TAG_NO_AUTH_REQUIRED)
2530 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002531 .Padding(PaddingMode::RSA_PSS)
2532 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002533 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2534 Begin(KeyPurpose::SIGN,
2535 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2536
2537 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2538 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2539}
2540
2541/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002542 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002543 *
2544 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2545 * supported in some cases (as validated in other tests), but a mode must be specified.
2546 */
2547TEST_P(SigningOperationsTest, RsaNoPadding) {
2548 // Padding must be specified
2549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2550 .RsaKey(2048, 65537)
2551 .Authorization(TAG_NO_AUTH_REQUIRED)
2552 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002553 .Digest(Digest::NONE)
2554 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002555 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2556 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2557}
2558
2559/*
2560 * SigningOperationsTest.RsaShortMessage
2561 *
2562 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2563 */
2564TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2566 .Authorization(TAG_NO_AUTH_REQUIRED)
2567 .RsaSigningKey(2048, 65537)
2568 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002569 .Padding(PaddingMode::NONE)
2570 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002571
2572 // Barely shorter
2573 string message(2048 / 8 - 1, 'a');
2574 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2575
2576 // Much shorter
2577 message = "a";
2578 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2579}
2580
2581/*
2582 * SigningOperationsTest.RsaSignWithEncryptionKey
2583 *
2584 * Verifies that RSA encryption keys cannot be used to sign.
2585 */
2586TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2587 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2588 .Authorization(TAG_NO_AUTH_REQUIRED)
2589 .RsaEncryptionKey(2048, 65537)
2590 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002591 .Padding(PaddingMode::NONE)
2592 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002593 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2594 Begin(KeyPurpose::SIGN,
2595 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2596}
2597
2598/*
2599 * SigningOperationsTest.RsaSignTooLargeMessage
2600 *
2601 * Verifies that attempting a raw signature of a message which is the same length as the key,
2602 * but numerically larger than the public modulus, fails with the correct error.
2603 */
2604TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2606 .Authorization(TAG_NO_AUTH_REQUIRED)
2607 .RsaSigningKey(2048, 65537)
2608 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002609 .Padding(PaddingMode::NONE)
2610 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002611
2612 // Largest possible message will always be larger than the public modulus.
2613 string message(2048 / 8, static_cast<char>(0xff));
2614 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2615 .Authorization(TAG_NO_AUTH_REQUIRED)
2616 .Digest(Digest::NONE)
2617 .Padding(PaddingMode::NONE)));
2618 string signature;
2619 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2620}
2621
2622/*
David Drysdalefe42aa32021-05-06 08:10:58 +01002623 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2624 *
2625 * Verifies ECDSA signature/verification for all digests and curves.
2626 */
2627TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2628 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2629
2630 string message = "1234567890";
2631 string corrupt_message = "2234567890";
2632 for (auto curve : ValidCurves()) {
2633 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2634 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2635 .Authorization(TAG_NO_AUTH_REQUIRED)
2636 .EcdsaSigningKey(curve)
2637 .Digest(digests)
2638 .SetDefaultValidity());
2639 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2640 if (error != ErrorCode::OK) {
2641 continue;
2642 }
2643
2644 for (auto digest : digests) {
2645 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2646 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2647 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2648 }
2649
2650 auto rc = DeleteKey();
2651 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2652 }
2653}
2654
2655/*
Selene Huang31ab4042020-04-29 04:22:39 -07002656 * SigningOperationsTest.EcdsaAllCurves
2657 *
2658 * Verifies that ECDSA operations succeed with all possible curves.
2659 */
2660TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2661 for (auto curve : ValidCurves()) {
2662 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2663 .Authorization(TAG_NO_AUTH_REQUIRED)
2664 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002665 .Digest(Digest::SHA_2_256)
2666 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002667 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2668 if (error != ErrorCode::OK) continue;
2669
2670 string message(1024, 'a');
2671 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2672 CheckedDeleteKey();
2673 }
2674}
2675
2676/*
2677 * SigningOperationsTest.EcdsaNoDigestHugeData
2678 *
2679 * Verifies that ECDSA operations support very large messages, even without digesting. This
2680 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2681 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2682 * the framework.
2683 */
2684TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2686 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002687 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002688 .Digest(Digest::NONE)
2689 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002690 string message(1 * 1024, 'a');
2691 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2692}
2693
2694/*
2695 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2696 *
2697 * Verifies that using an EC key requires the correct app ID/data.
2698 */
2699TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2701 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002702 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002703 .Digest(Digest::NONE)
2704 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002705 .Authorization(TAG_APPLICATION_DATA, "appdata")
2706 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002707
2708 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2709
Selene Huang31ab4042020-04-29 04:22:39 -07002710 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2711 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2712 AbortIfNeeded();
2713 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2714 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2715 .Digest(Digest::NONE)
2716 .Authorization(TAG_APPLICATION_ID, "clientid")));
2717 AbortIfNeeded();
2718 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2719 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2720 .Digest(Digest::NONE)
2721 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2722 AbortIfNeeded();
2723 EXPECT_EQ(ErrorCode::OK,
2724 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2725 .Digest(Digest::NONE)
2726 .Authorization(TAG_APPLICATION_DATA, "appdata")
2727 .Authorization(TAG_APPLICATION_ID, "clientid")));
2728 AbortIfNeeded();
2729}
2730
2731/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002732 * SigningOperationsTest.EcdsaIncompatibleDigest
2733 *
2734 * Verifies that using an EC key requires compatible digest.
2735 */
2736TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2737 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2738 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002739 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002740 .Digest(Digest::NONE)
2741 .Digest(Digest::SHA1)
2742 .SetDefaultValidity()));
2743 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2744 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2745 AbortIfNeeded();
2746}
2747
2748/*
Selene Huang31ab4042020-04-29 04:22:39 -07002749 * SigningOperationsTest.AesEcbSign
2750 *
2751 * Verifies that attempts to use AES keys to sign fail in the correct way.
2752 */
2753TEST_P(SigningOperationsTest, AesEcbSign) {
2754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2755 .Authorization(TAG_NO_AUTH_REQUIRED)
2756 .SigningKey()
2757 .AesEncryptionKey(128)
2758 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2759
2760 AuthorizationSet out_params;
2761 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2762 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2763 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2764 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2765}
2766
2767/*
2768 * SigningOperationsTest.HmacAllDigests
2769 *
2770 * Verifies that HMAC works with all digests.
2771 */
2772TEST_P(SigningOperationsTest, HmacAllDigests) {
2773 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2774 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2775 .Authorization(TAG_NO_AUTH_REQUIRED)
2776 .HmacKey(128)
2777 .Digest(digest)
2778 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2779 << "Failed to create HMAC key with digest " << digest;
2780 string message = "12345678901234567890123456789012";
2781 string signature = MacMessage(message, digest, 160);
2782 EXPECT_EQ(160U / 8U, signature.size())
2783 << "Failed to sign with HMAC key with digest " << digest;
2784 CheckedDeleteKey();
2785 }
2786}
2787
2788/*
2789 * SigningOperationsTest.HmacSha256TooLargeMacLength
2790 *
2791 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2792 * digest size.
2793 */
2794TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2795 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2796 .Authorization(TAG_NO_AUTH_REQUIRED)
2797 .HmacKey(128)
2798 .Digest(Digest::SHA_2_256)
2799 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2800 AuthorizationSet output_params;
2801 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2802 AuthorizationSetBuilder()
2803 .Digest(Digest::SHA_2_256)
2804 .Authorization(TAG_MAC_LENGTH, 264),
2805 &output_params));
2806}
2807
2808/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002809 * SigningOperationsTest.HmacSha256InvalidMacLength
2810 *
2811 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2812 * not a multiple of 8.
2813 */
2814TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2815 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2816 .Authorization(TAG_NO_AUTH_REQUIRED)
2817 .HmacKey(128)
2818 .Digest(Digest::SHA_2_256)
2819 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2820 AuthorizationSet output_params;
2821 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2822 AuthorizationSetBuilder()
2823 .Digest(Digest::SHA_2_256)
2824 .Authorization(TAG_MAC_LENGTH, 161),
2825 &output_params));
2826}
2827
2828/*
Selene Huang31ab4042020-04-29 04:22:39 -07002829 * SigningOperationsTest.HmacSha256TooSmallMacLength
2830 *
2831 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2832 * specified minimum MAC length.
2833 */
2834TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2835 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2836 .Authorization(TAG_NO_AUTH_REQUIRED)
2837 .HmacKey(128)
2838 .Digest(Digest::SHA_2_256)
2839 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2840 AuthorizationSet output_params;
2841 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2842 AuthorizationSetBuilder()
2843 .Digest(Digest::SHA_2_256)
2844 .Authorization(TAG_MAC_LENGTH, 120),
2845 &output_params));
2846}
2847
2848/*
2849 * SigningOperationsTest.HmacRfc4231TestCase3
2850 *
2851 * Validates against the test vectors from RFC 4231 test case 3.
2852 */
2853TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2854 string key(20, 0xaa);
2855 string message(50, 0xdd);
2856 uint8_t sha_224_expected[] = {
2857 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2858 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2859 };
2860 uint8_t sha_256_expected[] = {
2861 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2862 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2863 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2864 };
2865 uint8_t sha_384_expected[] = {
2866 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2867 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2868 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2869 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2870 };
2871 uint8_t sha_512_expected[] = {
2872 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2873 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2874 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2875 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2876 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2877 };
2878
2879 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2880 if (SecLevel() != SecurityLevel::STRONGBOX) {
2881 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2882 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2883 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2884 }
2885}
2886
2887/*
2888 * SigningOperationsTest.HmacRfc4231TestCase5
2889 *
2890 * Validates against the test vectors from RFC 4231 test case 5.
2891 */
2892TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2893 string key(20, 0x0c);
2894 string message = "Test With Truncation";
2895
2896 uint8_t sha_224_expected[] = {
2897 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2898 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2899 };
2900 uint8_t sha_256_expected[] = {
2901 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2902 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2903 };
2904 uint8_t sha_384_expected[] = {
2905 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2906 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2907 };
2908 uint8_t sha_512_expected[] = {
2909 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2910 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2911 };
2912
2913 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2914 if (SecLevel() != SecurityLevel::STRONGBOX) {
2915 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2916 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2917 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2918 }
2919}
2920
2921INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2922
2923typedef KeyMintAidlTestBase VerificationOperationsTest;
2924
2925/*
Selene Huang31ab4042020-04-29 04:22:39 -07002926 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2927 *
2928 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2929 */
2930TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2931 string key_material = "HelloThisIsAKey";
2932
2933 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002934 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002935 EXPECT_EQ(ErrorCode::OK,
2936 ImportKey(AuthorizationSetBuilder()
2937 .Authorization(TAG_NO_AUTH_REQUIRED)
2938 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2939 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2940 .Digest(Digest::SHA_2_256)
2941 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2942 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2943 EXPECT_EQ(ErrorCode::OK,
2944 ImportKey(AuthorizationSetBuilder()
2945 .Authorization(TAG_NO_AUTH_REQUIRED)
2946 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2947 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2948 .Digest(Digest::SHA_2_256)
2949 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2950 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2951
2952 string message = "This is a message.";
2953 string signature = SignMessage(
2954 signing_key, message,
2955 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2956
2957 // Signing key should not work.
2958 AuthorizationSet out_params;
2959 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2960 Begin(KeyPurpose::VERIFY, signing_key,
2961 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2962
2963 // Verification key should work.
2964 VerifyMessage(verification_key, message, signature,
2965 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2966
2967 CheckedDeleteKey(&signing_key);
2968 CheckedDeleteKey(&verification_key);
2969}
2970
2971INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2972
2973typedef KeyMintAidlTestBase ExportKeyTest;
2974
2975/*
2976 * ExportKeyTest.RsaUnsupportedKeyFormat
2977 *
2978 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2979 */
2980// TODO(seleneh) add ExportKey to GenerateKey
2981// check result
2982
2983class ImportKeyTest : public KeyMintAidlTestBase {
2984 public:
2985 template <TagType tag_type, Tag tag, typename ValueT>
2986 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2987 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002988 for (auto& entry : key_characteristics_) {
2989 if (entry.securityLevel == SecLevel()) {
2990 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2991 << "Tag " << tag << " with value " << expected
2992 << " not found at security level" << entry.securityLevel;
2993 } else {
2994 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2995 << "Tag " << tag << " found at security level " << entry.securityLevel;
2996 }
Selene Huang31ab4042020-04-29 04:22:39 -07002997 }
2998 }
2999
3000 void CheckOrigin() {
3001 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003002 // Origin isn't a crypto param, but it always lives with them.
3003 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003004 }
3005};
3006
3007/*
3008 * ImportKeyTest.RsaSuccess
3009 *
3010 * Verifies that importing and using an RSA key pair works correctly.
3011 */
3012TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003013 uint32_t key_size;
3014 string key;
3015
3016 if (SecLevel() == SecurityLevel::STRONGBOX) {
3017 key_size = 2048;
3018 key = rsa_2048_key;
3019 } else {
3020 key_size = 1024;
3021 key = rsa_key;
3022 }
3023
Selene Huang31ab4042020-04-29 04:22:39 -07003024 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3025 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003026 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003027 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003028 .Padding(PaddingMode::RSA_PSS)
3029 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003030 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003031
3032 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003033 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003034 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3035 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3036 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3037 CheckOrigin();
3038
3039 string message(1024 / 8, 'a');
3040 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3041 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003042 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003043}
3044
3045/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003046 * ImportKeyTest.RsaSuccessWithoutParams
3047 *
3048 * Verifies that importing and using an RSA key pair without specifying parameters
3049 * works correctly.
3050 */
3051TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3052 uint32_t key_size;
3053 string key;
3054
3055 if (SecLevel() == SecurityLevel::STRONGBOX) {
3056 key_size = 2048;
3057 key = rsa_2048_key;
3058 } else {
3059 key_size = 1024;
3060 key = rsa_key;
3061 }
3062
3063 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3064 .Authorization(TAG_NO_AUTH_REQUIRED)
3065 .SigningKey()
3066 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3067 .Digest(Digest::SHA_2_256)
3068 .Padding(PaddingMode::RSA_PSS)
3069 .SetDefaultValidity(),
3070 KeyFormat::PKCS8, key));
3071
3072 // Key size and public exponent are determined from the imported key material.
3073 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3074 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3075
3076 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3077 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3078 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3079 CheckOrigin();
3080
3081 string message(1024 / 8, 'a');
3082 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3083 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003084 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003085}
3086
3087/*
Selene Huang31ab4042020-04-29 04:22:39 -07003088 * ImportKeyTest.RsaKeySizeMismatch
3089 *
3090 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3091 * correct way.
3092 */
3093TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3094 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3095 ImportKey(AuthorizationSetBuilder()
3096 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3097 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003098 .Padding(PaddingMode::NONE)
3099 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003100 KeyFormat::PKCS8, rsa_key));
3101}
3102
3103/*
3104 * ImportKeyTest.RsaPublicExponentMismatch
3105 *
3106 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3107 * fails in the correct way.
3108 */
3109TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3110 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3111 ImportKey(AuthorizationSetBuilder()
3112 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3113 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003114 .Padding(PaddingMode::NONE)
3115 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003116 KeyFormat::PKCS8, rsa_key));
3117}
3118
3119/*
3120 * ImportKeyTest.EcdsaSuccess
3121 *
3122 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3123 */
3124TEST_P(ImportKeyTest, EcdsaSuccess) {
3125 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3126 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003127 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003128 .Digest(Digest::SHA_2_256)
3129 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003130 KeyFormat::PKCS8, ec_256_key));
3131
3132 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003133 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3134 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3135
3136 CheckOrigin();
3137
3138 string message(32, 'a');
3139 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3140 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003141 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003142}
3143
3144/*
3145 * ImportKeyTest.EcdsaP256RFC5915Success
3146 *
3147 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3148 * correctly.
3149 */
3150TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3151 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3152 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003153 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003154 .Digest(Digest::SHA_2_256)
3155 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003156 KeyFormat::PKCS8, ec_256_key_rfc5915));
3157
3158 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003159 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3160 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3161
3162 CheckOrigin();
3163
3164 string message(32, 'a');
3165 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3166 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003167 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003168}
3169
3170/*
3171 * ImportKeyTest.EcdsaP256SEC1Success
3172 *
3173 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3174 */
3175TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3176 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3177 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003178 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003179 .Digest(Digest::SHA_2_256)
3180 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003181 KeyFormat::PKCS8, ec_256_key_sec1));
3182
3183 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003184 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3185 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3186
3187 CheckOrigin();
3188
3189 string message(32, 'a');
3190 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3191 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003192 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003193}
3194
3195/*
3196 * ImportKeyTest.Ecdsa521Success
3197 *
3198 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3199 */
3200TEST_P(ImportKeyTest, Ecdsa521Success) {
3201 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3202 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3203 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003204 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003205 .Digest(Digest::SHA_2_256)
3206 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003207 KeyFormat::PKCS8, ec_521_key));
3208
3209 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003210 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3211 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3212 CheckOrigin();
3213
3214 string message(32, 'a');
3215 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3216 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003217 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003218}
3219
3220/*
Selene Huang31ab4042020-04-29 04:22:39 -07003221 * ImportKeyTest.EcdsaCurveMismatch
3222 *
3223 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3224 * the correct way.
3225 */
3226TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3227 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3228 ImportKey(AuthorizationSetBuilder()
3229 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003230 .Digest(Digest::NONE)
3231 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003232 KeyFormat::PKCS8, ec_256_key));
3233}
3234
3235/*
3236 * ImportKeyTest.AesSuccess
3237 *
3238 * Verifies that importing and using an AES key works.
3239 */
3240TEST_P(ImportKeyTest, AesSuccess) {
3241 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3242 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3243 .Authorization(TAG_NO_AUTH_REQUIRED)
3244 .AesEncryptionKey(key.size() * 8)
3245 .EcbMode()
3246 .Padding(PaddingMode::PKCS7),
3247 KeyFormat::RAW, key));
3248
3249 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3250 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3251 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3252 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3253 CheckOrigin();
3254
3255 string message = "Hello World!";
3256 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3257 string ciphertext = EncryptMessage(message, params);
3258 string plaintext = DecryptMessage(ciphertext, params);
3259 EXPECT_EQ(message, plaintext);
3260}
3261
3262/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003263 * ImportKeyTest.AesFailure
3264 *
3265 * Verifies that importing an invalid AES key fails.
3266 */
3267TEST_P(ImportKeyTest, AesFailure) {
3268 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3269 uint32_t bitlen = key.size() * 8;
3270 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003271 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003272 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003273 .Authorization(TAG_NO_AUTH_REQUIRED)
3274 .AesEncryptionKey(key_size)
3275 .EcbMode()
3276 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003277 KeyFormat::RAW, key);
3278 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003279 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3280 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003281 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003282
3283 // Explicit key size matches that of the provided key, but it's not a valid size.
3284 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3285 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3286 ImportKey(AuthorizationSetBuilder()
3287 .Authorization(TAG_NO_AUTH_REQUIRED)
3288 .AesEncryptionKey(long_key.size() * 8)
3289 .EcbMode()
3290 .Padding(PaddingMode::PKCS7),
3291 KeyFormat::RAW, long_key));
3292 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3293 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3294 ImportKey(AuthorizationSetBuilder()
3295 .Authorization(TAG_NO_AUTH_REQUIRED)
3296 .AesEncryptionKey(short_key.size() * 8)
3297 .EcbMode()
3298 .Padding(PaddingMode::PKCS7),
3299 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003300}
3301
3302/*
3303 * ImportKeyTest.TripleDesSuccess
3304 *
3305 * Verifies that importing and using a 3DES key works.
3306 */
3307TEST_P(ImportKeyTest, TripleDesSuccess) {
3308 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3309 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3310 .Authorization(TAG_NO_AUTH_REQUIRED)
3311 .TripleDesEncryptionKey(168)
3312 .EcbMode()
3313 .Padding(PaddingMode::PKCS7),
3314 KeyFormat::RAW, key));
3315
3316 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3317 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3318 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3319 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3320 CheckOrigin();
3321
3322 string message = "Hello World!";
3323 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3324 string ciphertext = EncryptMessage(message, params);
3325 string plaintext = DecryptMessage(ciphertext, params);
3326 EXPECT_EQ(message, plaintext);
3327}
3328
3329/*
3330 * ImportKeyTest.TripleDesFailure
3331 *
3332 * Verifies that importing an invalid 3DES key fails.
3333 */
3334TEST_P(ImportKeyTest, TripleDesFailure) {
3335 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003336 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003337 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003338 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003339 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003340 .Authorization(TAG_NO_AUTH_REQUIRED)
3341 .TripleDesEncryptionKey(key_size)
3342 .EcbMode()
3343 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003344 KeyFormat::RAW, key);
3345 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003346 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3347 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003348 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003349 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003350 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003351 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3352 ImportKey(AuthorizationSetBuilder()
3353 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003354 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003355 .EcbMode()
3356 .Padding(PaddingMode::PKCS7),
3357 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003358 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003359 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3360 ImportKey(AuthorizationSetBuilder()
3361 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003362 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003363 .EcbMode()
3364 .Padding(PaddingMode::PKCS7),
3365 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003366}
3367
3368/*
3369 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003370 *
3371 * Verifies that importing and using an HMAC key works.
3372 */
3373TEST_P(ImportKeyTest, HmacKeySuccess) {
3374 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3375 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3376 .Authorization(TAG_NO_AUTH_REQUIRED)
3377 .HmacKey(key.size() * 8)
3378 .Digest(Digest::SHA_2_256)
3379 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3380 KeyFormat::RAW, key));
3381
3382 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3383 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3384 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3385 CheckOrigin();
3386
3387 string message = "Hello World!";
3388 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3389 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3390}
3391
3392INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3393
3394auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003395 // IKeyMintDevice.aidl
3396 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3397 "020100" // INTEGER length 1 value 0x00 (version)
3398 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3399 "934bf94e2aa28a3f83c9f79297250262"
3400 "fbe3276b5a1c91159bbfa3ef8957aac8"
3401 "4b59b30b455a79c2973480823d8b3863"
3402 "c3deef4a8e243590268d80e18751a0e1"
3403 "30f67ce6a1ace9f79b95e097474febc9"
3404 "81195b1d13a69086c0863f66a7b7fdb4"
3405 "8792227b1ac5e2489febdf087ab54864"
3406 "83033a6f001ca5d1ec1e27f5c30f4cec"
3407 "2642074a39ae68aee552e196627a8e3d"
3408 "867e67a8c01b11e75f13cca0a97ab668"
3409 "b50cda07a8ecb7cd8e3dd7009c963653"
3410 "4f6f239cffe1fc8daa466f78b676c711"
3411 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3412 "99b801597d5220e307eaa5bee507fb94"
3413 "d1fa69f9e519b2de315bac92c36f2ea1"
3414 "fa1df4478c0ddedeae8c70e0233cd098"
3415 "040c" // OCTET STRING length 0x0c (initializationVector)
3416 "d796b02c370f1fa4cc0124f1"
3417 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3418 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3419 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3420 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3421 "3106" // SET length 0x06
3422 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3423 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3424 // } end SET
3425 // } end [1]
3426 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3427 "020120" // INTEGER length 1 value 0x20 (AES)
3428 // } end [2]
3429 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3430 "02020100" // INTEGER length 2 value 0x100
3431 // } end [3]
3432 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3433 "3103" // SET length 0x03 {
3434 "020101" // INTEGER length 1 value 0x01 (ECB)
3435 // } end SET
3436 // } end [4]
3437 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3438 "3103" // SET length 0x03 {
3439 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3440 // } end SET
3441 // } end [5]
3442 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3443 // (noAuthRequired)
3444 "0500" // NULL
3445 // } end [503]
3446 // } end SEQUENCE (AuthorizationList)
3447 // } end SEQUENCE (KeyDescription)
3448 "0420" // OCTET STRING length 0x20 (encryptedKey)
3449 "ccd540855f833a5e1480bfd2d36faf3a"
3450 "eee15df5beabe2691bc82dde2a7aa910"
3451 "0410" // OCTET STRING length 0x10 (tag)
3452 "64c9f689c60ff6223ab6e6999e0eb6e5"
3453 // } SEQUENCE (SecureKeyWrapper)
3454);
Selene Huang31ab4042020-04-29 04:22:39 -07003455
3456auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003457 // IKeyMintDevice.aidl
3458 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3459 "020100" // INTEGER length 1 value 0x00 (version)
3460 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3461 "aad93ed5924f283b4bb5526fbe7a1412"
3462 "f9d9749ec30db9062b29e574a8546f33"
3463 "c88732452f5b8e6a391ee76c39ed1712"
3464 "c61d8df6213dec1cffbc17a8c6d04c7b"
3465 "30893d8daa9b2015213e219468215532"
3466 "07f8f9931c4caba23ed3bee28b36947e"
3467 "47f10e0a5c3dc51c988a628daad3e5e1"
3468 "f4005e79c2d5a96c284b4b8d7e4948f3"
3469 "31e5b85dd5a236f85579f3ea1d1b8484"
3470 "87470bdb0ab4f81a12bee42c99fe0df4"
3471 "bee3759453e69ad1d68a809ce06b949f"
3472 "7694a990429b2fe81e066ff43e56a216"
3473 "02db70757922a4bcc23ab89f1e35da77"
3474 "586775f423e519c2ea394caf48a28d0c"
3475 "8020f1dcf6b3a68ec246f615ae96dae9"
3476 "a079b1f6eb959033c1af5c125fd94168"
3477 "040c" // OCTET STRING length 0x0c (initializationVector)
3478 "6d9721d08589581ab49204a3"
3479 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3480 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3481 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3482 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3483 "3106" // SET length 0x06
3484 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3485 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3486 // } end SET
3487 // } end [1]
3488 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3489 "020120" // INTEGER length 1 value 0x20 (AES)
3490 // } end [2]
3491 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3492 "02020100" // INTEGER length 2 value 0x100
3493 // } end [3]
3494 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3495 "3103" // SET length 0x03 {
3496 "020101" // INTEGER length 1 value 0x01 (ECB)
3497 // } end SET
3498 // } end [4]
3499 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3500 "3103" // SET length 0x03 {
3501 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3502 // } end SET
3503 // } end [5]
3504 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3505 // (noAuthRequired)
3506 "0500" // NULL
3507 // } end [503]
3508 // } end SEQUENCE (AuthorizationList)
3509 // } end SEQUENCE (KeyDescription)
3510 "0420" // OCTET STRING length 0x20 (encryptedKey)
3511 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3512 "c20d1f99a9a024a76f35c8e2cab9b68d"
3513 "0410" // OCTET STRING length 0x10 (tag)
3514 "2560c70109ae67c030f00b98b512a670"
3515 // } SEQUENCE (SecureKeyWrapper)
3516);
Selene Huang31ab4042020-04-29 04:22:39 -07003517
3518auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003519 // RFC 5208 s5
3520 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3521 "020100" // INTEGER length 1 value 0x00 (version)
3522 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3523 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3524 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3525 "0500" // NULL (parameters)
3526 // } SEQUENCE (AlgorithmIdentifier)
3527 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3528 // RFC 8017 A.1.2
3529 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3530 "020100" // INTEGER length 1 value 0x00 (version)
3531 "02820101" // INTEGER length 0x0101 (modulus) value...
3532 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3533 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3534 "7b06e673a837313d56b1c725150a3fef" // 0x30
3535 "86acbddc41bb759c2854eae32d35841e" // 0x40
3536 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3537 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3538 "312d7bd5921ffaea1347c157406fef71" // 0x70
3539 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3540 "f4645c11f5c1374c3886427411c44979" // 0x90
3541 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3542 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3543 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3544 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3545 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3546 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3547 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3548 "55" // 0x101
3549 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3550 "02820100" // INTEGER length 0x100 (privateExponent) value...
3551 "431447b6251908112b1ee76f99f3711a" // 0x10
3552 "52b6630960046c2de70de188d833f8b8" // 0x20
3553 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3554 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3555 "e710b630a03adc683b5d2c43080e52be" // 0x50
3556 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3557 "822bccff087d63c940ba8a45f670feb2" // 0x70
3558 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3559 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3560 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3561 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3562 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3563 "52659d5a5ba05b663737a8696281865b" // 0xd0
3564 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3565 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3566 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3567 "028181" // INTEGER length 0x81 (prime1) value...
3568 "00de392e18d682c829266cc3454e1d61" // 0x10
3569 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3570 "ff841be5bac82a164c5970007047b8c5" // 0x30
3571 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3572 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3573 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3574 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3575 "9e91346130748a6e3c124f9149d71c74" // 0x80
3576 "35"
3577 "028181" // INTEGER length 0x81 (prime2) value...
3578 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3579 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3580 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3581 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3582 "9ed39a2d934c880440aed8832f984316" // 0x50
3583 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3584 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3585 "b880677c068e1be936e81288815252a8" // 0x80
3586 "a1"
3587 "028180" // INTEGER length 0x80 (exponent1) value...
3588 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3589 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3590 "5a063212a4f105a3764743e53281988a" // 0x30
3591 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3592 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3593 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3594 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3595 "4719d6e2b9439823719cd08bcd031781" // 0x80
3596 "028181" // INTEGER length 0x81 (exponent2) value...
3597 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3598 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3599 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3600 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3601 "1254186af30b22c10582a8a43e34fe94" // 0x50
3602 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3603 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3604 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3605 "61"
3606 "028181" // INTEGER length 0x81 (coefficient) value...
3607 "00c931617c77829dfb1270502be9195c" // 0x10
3608 "8f2830885f57dba869536811e6864236" // 0x20
3609 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3610 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3611 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3612 "959356210723287b0affcc9f727044d4" // 0x60
3613 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3614 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3615 "22"
3616 // } SEQUENCE
3617 // } SEQUENCE ()
3618);
Selene Huang31ab4042020-04-29 04:22:39 -07003619
3620string zero_masking_key =
3621 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3622string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3623
3624class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3625
3626TEST_P(ImportWrappedKeyTest, Success) {
3627 auto wrapping_key_desc = AuthorizationSetBuilder()
3628 .RsaEncryptionKey(2048, 65537)
3629 .Digest(Digest::SHA_2_256)
3630 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003631 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3632 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003633
3634 ASSERT_EQ(ErrorCode::OK,
3635 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3636 AuthorizationSetBuilder()
3637 .Digest(Digest::SHA_2_256)
3638 .Padding(PaddingMode::RSA_OAEP)));
3639
3640 string message = "Hello World!";
3641 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3642 string ciphertext = EncryptMessage(message, params);
3643 string plaintext = DecryptMessage(ciphertext, params);
3644 EXPECT_EQ(message, plaintext);
3645}
3646
David Drysdaled2cc8c22021-04-15 13:29:45 +01003647/*
3648 * ImportWrappedKeyTest.SuccessSidsIgnored
3649 *
3650 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3651 * include Tag:USER_SECURE_ID.
3652 */
3653TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3654 auto wrapping_key_desc = AuthorizationSetBuilder()
3655 .RsaEncryptionKey(2048, 65537)
3656 .Digest(Digest::SHA_2_256)
3657 .Padding(PaddingMode::RSA_OAEP)
3658 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3659 .SetDefaultValidity();
3660
3661 int64_t password_sid = 42;
3662 int64_t biometric_sid = 24;
3663 ASSERT_EQ(ErrorCode::OK,
3664 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3665 AuthorizationSetBuilder()
3666 .Digest(Digest::SHA_2_256)
3667 .Padding(PaddingMode::RSA_OAEP),
3668 password_sid, biometric_sid));
3669
3670 string message = "Hello World!";
3671 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3672 string ciphertext = EncryptMessage(message, params);
3673 string plaintext = DecryptMessage(ciphertext, params);
3674 EXPECT_EQ(message, plaintext);
3675}
3676
Selene Huang31ab4042020-04-29 04:22:39 -07003677TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3678 auto wrapping_key_desc = AuthorizationSetBuilder()
3679 .RsaEncryptionKey(2048, 65537)
3680 .Digest(Digest::SHA_2_256)
3681 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003682 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3683 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003684
3685 ASSERT_EQ(ErrorCode::OK,
3686 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3687 AuthorizationSetBuilder()
3688 .Digest(Digest::SHA_2_256)
3689 .Padding(PaddingMode::RSA_OAEP)));
3690}
3691
3692TEST_P(ImportWrappedKeyTest, WrongMask) {
3693 auto wrapping_key_desc = AuthorizationSetBuilder()
3694 .RsaEncryptionKey(2048, 65537)
3695 .Digest(Digest::SHA_2_256)
3696 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003697 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3698 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003699
3700 ASSERT_EQ(
3701 ErrorCode::VERIFICATION_FAILED,
3702 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3703 AuthorizationSetBuilder()
3704 .Digest(Digest::SHA_2_256)
3705 .Padding(PaddingMode::RSA_OAEP)));
3706}
3707
3708TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3709 auto wrapping_key_desc = AuthorizationSetBuilder()
3710 .RsaEncryptionKey(2048, 65537)
3711 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003712 .Padding(PaddingMode::RSA_OAEP)
3713 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003714
3715 ASSERT_EQ(
3716 ErrorCode::INCOMPATIBLE_PURPOSE,
3717 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3718 AuthorizationSetBuilder()
3719 .Digest(Digest::SHA_2_256)
3720 .Padding(PaddingMode::RSA_OAEP)));
3721}
3722
David Drysdaled2cc8c22021-04-15 13:29:45 +01003723TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3724 auto wrapping_key_desc = AuthorizationSetBuilder()
3725 .RsaEncryptionKey(2048, 65537)
3726 .Digest(Digest::SHA_2_256)
3727 .Padding(PaddingMode::RSA_PSS)
3728 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3729 .SetDefaultValidity();
3730
3731 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3732 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3733 AuthorizationSetBuilder()
3734 .Digest(Digest::SHA_2_256)
3735 .Padding(PaddingMode::RSA_OAEP)));
3736}
3737
3738TEST_P(ImportWrappedKeyTest, WrongDigest) {
3739 auto wrapping_key_desc = AuthorizationSetBuilder()
3740 .RsaEncryptionKey(2048, 65537)
3741 .Digest(Digest::SHA_2_512)
3742 .Padding(PaddingMode::RSA_OAEP)
3743 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3744 .SetDefaultValidity();
3745
3746 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3747 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3748 AuthorizationSetBuilder()
3749 .Digest(Digest::SHA_2_256)
3750 .Padding(PaddingMode::RSA_OAEP)));
3751}
3752
Selene Huang31ab4042020-04-29 04:22:39 -07003753INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3754
3755typedef KeyMintAidlTestBase EncryptionOperationsTest;
3756
3757/*
3758 * EncryptionOperationsTest.RsaNoPaddingSuccess
3759 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003760 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003761 */
3762TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003763 for (uint64_t exponent : {3, 65537}) {
3764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3765 .Authorization(TAG_NO_AUTH_REQUIRED)
3766 .RsaEncryptionKey(2048, exponent)
3767 .Padding(PaddingMode::NONE)
3768 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003769
David Drysdaled2cc8c22021-04-15 13:29:45 +01003770 string message = string(2048 / 8, 'a');
3771 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003772 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003773 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003774
David Drysdale2b6c3512021-05-12 13:52:03 +01003775 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003776 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003777
David Drysdaled2cc8c22021-04-15 13:29:45 +01003778 // Unpadded RSA is deterministic
3779 EXPECT_EQ(ciphertext1, ciphertext2);
3780
3781 CheckedDeleteKey();
3782 }
Selene Huang31ab4042020-04-29 04:22:39 -07003783}
3784
3785/*
3786 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3787 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003788 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003789 */
3790TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3792 .Authorization(TAG_NO_AUTH_REQUIRED)
3793 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003794 .Padding(PaddingMode::NONE)
3795 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003796
3797 string message = "1";
3798 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3799
David Drysdale2b6c3512021-05-12 13:52:03 +01003800 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003801 EXPECT_EQ(2048U / 8, ciphertext.size());
3802
3803 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3804 string plaintext = DecryptMessage(ciphertext, params);
3805
3806 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003807}
3808
3809/*
Selene Huang31ab4042020-04-29 04:22:39 -07003810 * EncryptionOperationsTest.RsaOaepSuccess
3811 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003812 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003813 */
3814TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3815 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3816
3817 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale2b6c3512021-05-12 13:52:03 +01003818 ASSERT_EQ(ErrorCode::OK,
3819 GenerateKey(AuthorizationSetBuilder()
3820 .Authorization(TAG_NO_AUTH_REQUIRED)
3821 .RsaEncryptionKey(key_size, 65537)
3822 .Padding(PaddingMode::RSA_OAEP)
3823 .Digest(digests)
3824 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3825 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003826
3827 string message = "Hello";
3828
3829 for (auto digest : digests) {
David Drysdale2b6c3512021-05-12 13:52:03 +01003830 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3831
3832 auto params = AuthorizationSetBuilder()
3833 .Digest(digest)
3834 .Padding(PaddingMode::RSA_OAEP)
3835 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3836 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003837 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3838 EXPECT_EQ(key_size / 8, ciphertext1.size());
3839
David Drysdale2b6c3512021-05-12 13:52:03 +01003840 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003841 EXPECT_EQ(key_size / 8, ciphertext2.size());
3842
3843 // OAEP randomizes padding so every result should be different (with astronomically high
3844 // probability).
3845 EXPECT_NE(ciphertext1, ciphertext2);
3846
3847 string plaintext1 = DecryptMessage(ciphertext1, params);
3848 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3849 string plaintext2 = DecryptMessage(ciphertext2, params);
3850 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3851
3852 // Decrypting corrupted ciphertext should fail.
3853 size_t offset_to_corrupt = random() % ciphertext1.size();
3854 char corrupt_byte;
3855 do {
3856 corrupt_byte = static_cast<char>(random() % 256);
3857 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3858 ciphertext1[offset_to_corrupt] = corrupt_byte;
3859
3860 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3861 string result;
3862 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3863 EXPECT_EQ(0U, result.size());
3864 }
3865}
3866
3867/*
3868 * EncryptionOperationsTest.RsaOaepInvalidDigest
3869 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003870 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003871 * without a digest.
3872 */
3873TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3875 .Authorization(TAG_NO_AUTH_REQUIRED)
3876 .RsaEncryptionKey(2048, 65537)
3877 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003878 .Digest(Digest::NONE)
3879 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003880
3881 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003882 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003883}
3884
3885/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003886 * EncryptionOperationsTest.RsaOaepInvalidPadding
3887 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003888 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003889 * with a padding value that is only suitable for signing/verifying.
3890 */
3891TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3893 .Authorization(TAG_NO_AUTH_REQUIRED)
3894 .RsaEncryptionKey(2048, 65537)
3895 .Padding(PaddingMode::RSA_PSS)
3896 .Digest(Digest::NONE)
3897 .SetDefaultValidity()));
3898
3899 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003900 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003901}
3902
3903/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003904 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003905 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003906 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003907 * with a different digest than was used to encrypt.
3908 */
3909TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3910 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3911
3912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3913 .Authorization(TAG_NO_AUTH_REQUIRED)
3914 .RsaEncryptionKey(1024, 65537)
3915 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003916 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3917 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003918 string message = "Hello World!";
David Drysdale2b6c3512021-05-12 13:52:03 +01003919 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003920 message,
3921 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3922
3923 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3924 .Digest(Digest::SHA_2_256)
3925 .Padding(PaddingMode::RSA_OAEP)));
3926 string result;
3927 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3928 EXPECT_EQ(0U, result.size());
3929}
3930
3931/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003932 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3933 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003934 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003935 * digests.
3936 */
3937TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3938 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3939
3940 size_t key_size = 2048; // Need largish key for SHA-512 test.
3941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3942 .OaepMGFDigest(digests)
3943 .Authorization(TAG_NO_AUTH_REQUIRED)
3944 .RsaEncryptionKey(key_size, 65537)
3945 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003946 .Digest(Digest::SHA_2_256)
3947 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003948
3949 string message = "Hello";
3950
3951 for (auto digest : digests) {
3952 auto params = AuthorizationSetBuilder()
3953 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3954 .Digest(Digest::SHA_2_256)
3955 .Padding(PaddingMode::RSA_OAEP);
David Drysdale2b6c3512021-05-12 13:52:03 +01003956 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003957 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3958 EXPECT_EQ(key_size / 8, ciphertext1.size());
3959
David Drysdale2b6c3512021-05-12 13:52:03 +01003960 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003961 EXPECT_EQ(key_size / 8, ciphertext2.size());
3962
3963 // OAEP randomizes padding so every result should be different (with astronomically high
3964 // probability).
3965 EXPECT_NE(ciphertext1, ciphertext2);
3966
3967 string plaintext1 = DecryptMessage(ciphertext1, params);
3968 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3969 string plaintext2 = DecryptMessage(ciphertext2, params);
3970 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3971
3972 // Decrypting corrupted ciphertext should fail.
3973 size_t offset_to_corrupt = random() % ciphertext1.size();
3974 char corrupt_byte;
3975 do {
3976 corrupt_byte = static_cast<char>(random() % 256);
3977 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3978 ciphertext1[offset_to_corrupt] = corrupt_byte;
3979
3980 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3981 string result;
3982 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3983 EXPECT_EQ(0U, result.size());
3984 }
3985}
3986
3987/*
3988 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3989 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003990 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003991 * with incompatible MGF digest.
3992 */
3993TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3994 ASSERT_EQ(ErrorCode::OK,
3995 GenerateKey(AuthorizationSetBuilder()
3996 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3997 .Authorization(TAG_NO_AUTH_REQUIRED)
3998 .RsaEncryptionKey(2048, 65537)
3999 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004000 .Digest(Digest::SHA_2_256)
4001 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004002 string message = "Hello World!";
4003
4004 auto params = AuthorizationSetBuilder()
4005 .Padding(PaddingMode::RSA_OAEP)
4006 .Digest(Digest::SHA_2_256)
4007 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale2b6c3512021-05-12 13:52:03 +01004008 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004009}
4010
4011/*
4012 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4013 *
4014 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4015 * with unsupported MGF digest.
4016 */
4017TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4018 ASSERT_EQ(ErrorCode::OK,
4019 GenerateKey(AuthorizationSetBuilder()
4020 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4021 .Authorization(TAG_NO_AUTH_REQUIRED)
4022 .RsaEncryptionKey(2048, 65537)
4023 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004024 .Digest(Digest::SHA_2_256)
4025 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004026 string message = "Hello World!";
4027
4028 auto params = AuthorizationSetBuilder()
4029 .Padding(PaddingMode::RSA_OAEP)
4030 .Digest(Digest::SHA_2_256)
4031 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01004032 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004033}
4034
4035/*
Selene Huang31ab4042020-04-29 04:22:39 -07004036 * EncryptionOperationsTest.RsaPkcs1Success
4037 *
4038 * Verifies that RSA PKCS encryption/decrypts works.
4039 */
4040TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4042 .Authorization(TAG_NO_AUTH_REQUIRED)
4043 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004044 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4045 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004046
4047 string message = "Hello World!";
4048 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale2b6c3512021-05-12 13:52:03 +01004049 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004050 EXPECT_EQ(2048U / 8, ciphertext1.size());
4051
David Drysdale2b6c3512021-05-12 13:52:03 +01004052 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004053 EXPECT_EQ(2048U / 8, ciphertext2.size());
4054
4055 // PKCS1 v1.5 randomizes padding so every result should be different.
4056 EXPECT_NE(ciphertext1, ciphertext2);
4057
4058 string plaintext = DecryptMessage(ciphertext1, params);
4059 EXPECT_EQ(message, plaintext);
4060
4061 // Decrypting corrupted ciphertext should fail.
4062 size_t offset_to_corrupt = random() % ciphertext1.size();
4063 char corrupt_byte;
4064 do {
4065 corrupt_byte = static_cast<char>(random() % 256);
4066 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4067 ciphertext1[offset_to_corrupt] = corrupt_byte;
4068
4069 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4070 string result;
4071 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4072 EXPECT_EQ(0U, result.size());
4073}
4074
4075/*
Selene Huang31ab4042020-04-29 04:22:39 -07004076 * EncryptionOperationsTest.EcdsaEncrypt
4077 *
4078 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4079 */
4080TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4081 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4082 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01004083 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004084 .Digest(Digest::NONE)
4085 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004086 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4087 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4088 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4089}
4090
4091/*
4092 * EncryptionOperationsTest.HmacEncrypt
4093 *
4094 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4095 */
4096TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4098 .Authorization(TAG_NO_AUTH_REQUIRED)
4099 .HmacKey(128)
4100 .Digest(Digest::SHA_2_256)
4101 .Padding(PaddingMode::NONE)
4102 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4103 auto params = AuthorizationSetBuilder()
4104 .Digest(Digest::SHA_2_256)
4105 .Padding(PaddingMode::NONE)
4106 .Authorization(TAG_MAC_LENGTH, 128);
4107 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4108 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4109}
4110
4111/*
4112 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4113 *
4114 * Verifies that AES ECB mode works.
4115 */
4116TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4117 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4118 .Authorization(TAG_NO_AUTH_REQUIRED)
4119 .AesEncryptionKey(128)
4120 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4121 .Padding(PaddingMode::NONE)));
4122
4123 ASSERT_GT(key_blob_.size(), 0U);
4124 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4125
4126 // Two-block message.
4127 string message = "12345678901234567890123456789012";
4128 string ciphertext1 = EncryptMessage(message, params);
4129 EXPECT_EQ(message.size(), ciphertext1.size());
4130
4131 string ciphertext2 = EncryptMessage(string(message), params);
4132 EXPECT_EQ(message.size(), ciphertext2.size());
4133
4134 // ECB is deterministic.
4135 EXPECT_EQ(ciphertext1, ciphertext2);
4136
4137 string plaintext = DecryptMessage(ciphertext1, params);
4138 EXPECT_EQ(message, plaintext);
4139}
4140
4141/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004142 * EncryptionOperationsTest.AesEcbUnknownTag
4143 *
4144 * Verifies that AES ECB operations ignore unknown tags.
4145 */
4146TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4147 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4148 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4149 KeyParameter unknown_param;
4150 unknown_param.tag = unknown_tag;
4151
4152 vector<KeyCharacteristics> key_characteristics;
4153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4154 .Authorization(TAG_NO_AUTH_REQUIRED)
4155 .AesEncryptionKey(128)
4156 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4157 .Padding(PaddingMode::NONE)
4158 .Authorization(unknown_param),
4159 &key_blob_, &key_characteristics));
4160 ASSERT_GT(key_blob_.size(), 0U);
4161
4162 // Unknown tags should not be returned in key characteristics.
4163 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4164 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4165 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4166 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4167
4168 // Encrypt without mentioning the unknown parameter.
4169 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4170 string message = "12345678901234567890123456789012";
4171 string ciphertext = EncryptMessage(message, params);
4172 EXPECT_EQ(message.size(), ciphertext.size());
4173
4174 // Decrypt including the unknown parameter.
4175 auto decrypt_params = AuthorizationSetBuilder()
4176 .BlockMode(BlockMode::ECB)
4177 .Padding(PaddingMode::NONE)
4178 .Authorization(unknown_param);
4179 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4180 EXPECT_EQ(message, plaintext);
4181}
4182
4183/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004184 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004185 *
4186 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4187 */
4188TEST_P(EncryptionOperationsTest, AesWrongMode) {
4189 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4190 .Authorization(TAG_NO_AUTH_REQUIRED)
4191 .AesEncryptionKey(128)
4192 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4193 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004194 ASSERT_GT(key_blob_.size(), 0U);
4195
Selene Huang31ab4042020-04-29 04:22:39 -07004196 EXPECT_EQ(
4197 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4198 Begin(KeyPurpose::ENCRYPT,
4199 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4200}
4201
4202/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004203 * EncryptionOperationsTest.AesWrongPadding
4204 *
4205 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4206 */
4207TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4208 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4209 .Authorization(TAG_NO_AUTH_REQUIRED)
4210 .AesEncryptionKey(128)
4211 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4212 .Padding(PaddingMode::NONE)));
4213 ASSERT_GT(key_blob_.size(), 0U);
4214
4215 EXPECT_EQ(
4216 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4217 Begin(KeyPurpose::ENCRYPT,
4218 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4219}
4220
4221/*
4222 * EncryptionOperationsTest.AesInvalidParams
4223 *
4224 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4225 */
4226TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4228 .Authorization(TAG_NO_AUTH_REQUIRED)
4229 .AesEncryptionKey(128)
4230 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4231 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4232 .Padding(PaddingMode::NONE)
4233 .Padding(PaddingMode::PKCS7)));
4234 ASSERT_GT(key_blob_.size(), 0U);
4235
4236 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4237 .BlockMode(BlockMode::CBC)
4238 .BlockMode(BlockMode::ECB)
4239 .Padding(PaddingMode::NONE));
4240 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4241 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4242
4243 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4244 .BlockMode(BlockMode::ECB)
4245 .Padding(PaddingMode::NONE)
4246 .Padding(PaddingMode::PKCS7));
4247 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4248 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4249}
4250
4251/*
Selene Huang31ab4042020-04-29 04:22:39 -07004252 * EncryptionOperationsTest.AesWrongPurpose
4253 *
4254 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4255 * specified.
4256 */
4257TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4258 auto err = GenerateKey(AuthorizationSetBuilder()
4259 .Authorization(TAG_NO_AUTH_REQUIRED)
4260 .AesKey(128)
4261 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4262 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4263 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4264 .Padding(PaddingMode::NONE));
4265 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4266 ASSERT_GT(key_blob_.size(), 0U);
4267
4268 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4269 .BlockMode(BlockMode::GCM)
4270 .Padding(PaddingMode::NONE)
4271 .Authorization(TAG_MAC_LENGTH, 128));
4272 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4273
4274 CheckedDeleteKey();
4275
4276 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4277 .Authorization(TAG_NO_AUTH_REQUIRED)
4278 .AesKey(128)
4279 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4280 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4281 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4282 .Padding(PaddingMode::NONE)));
4283
4284 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4285 .BlockMode(BlockMode::GCM)
4286 .Padding(PaddingMode::NONE)
4287 .Authorization(TAG_MAC_LENGTH, 128));
4288 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4289}
4290
4291/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004292 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004293 *
4294 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4295 * multiple of the block size and no padding is specified.
4296 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004297TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4298 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4299 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4300 .Authorization(TAG_NO_AUTH_REQUIRED)
4301 .AesEncryptionKey(128)
4302 .Authorization(TAG_BLOCK_MODE, blockMode)
4303 .Padding(PaddingMode::NONE)));
4304 // Message is slightly shorter than two blocks.
4305 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004306
David Drysdaled2cc8c22021-04-15 13:29:45 +01004307 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4308 AuthorizationSet out_params;
4309 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4310 string ciphertext;
4311 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4312 EXPECT_EQ(0U, ciphertext.size());
4313
4314 CheckedDeleteKey();
4315 }
Selene Huang31ab4042020-04-29 04:22:39 -07004316}
4317
4318/*
4319 * EncryptionOperationsTest.AesEcbPkcs7Padding
4320 *
4321 * Verifies that AES PKCS7 padding works for any message length.
4322 */
4323TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4325 .Authorization(TAG_NO_AUTH_REQUIRED)
4326 .AesEncryptionKey(128)
4327 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4328 .Padding(PaddingMode::PKCS7)));
4329
4330 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4331
4332 // Try various message lengths; all should work.
4333 for (size_t i = 0; i < 32; ++i) {
4334 string message(i, 'a');
4335 string ciphertext = EncryptMessage(message, params);
4336 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4337 string plaintext = DecryptMessage(ciphertext, params);
4338 EXPECT_EQ(message, plaintext);
4339 }
4340}
4341
4342/*
4343 * EncryptionOperationsTest.AesEcbWrongPadding
4344 *
4345 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4346 * specified.
4347 */
4348TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4350 .Authorization(TAG_NO_AUTH_REQUIRED)
4351 .AesEncryptionKey(128)
4352 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4353 .Padding(PaddingMode::NONE)));
4354
4355 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4356
4357 // Try various message lengths; all should fail
4358 for (size_t i = 0; i < 32; ++i) {
4359 string message(i, 'a');
4360 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4361 }
4362}
4363
4364/*
4365 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4366 *
4367 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4368 */
4369TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4371 .Authorization(TAG_NO_AUTH_REQUIRED)
4372 .AesEncryptionKey(128)
4373 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4374 .Padding(PaddingMode::PKCS7)));
4375
4376 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4377
4378 string message = "a";
4379 string ciphertext = EncryptMessage(message, params);
4380 EXPECT_EQ(16U, ciphertext.size());
4381 EXPECT_NE(ciphertext, message);
4382 ++ciphertext[ciphertext.size() / 2];
4383
4384 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4385 string plaintext;
4386 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4387}
4388
4389vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4390 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004391 EXPECT_TRUE(iv);
4392 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004393}
4394
4395/*
4396 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4397 *
4398 * Verifies that AES CTR mode works.
4399 */
4400TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4401 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4402 .Authorization(TAG_NO_AUTH_REQUIRED)
4403 .AesEncryptionKey(128)
4404 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4405 .Padding(PaddingMode::NONE)));
4406
4407 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4408
4409 string message = "123";
4410 AuthorizationSet out_params;
4411 string ciphertext1 = EncryptMessage(message, params, &out_params);
4412 vector<uint8_t> iv1 = CopyIv(out_params);
4413 EXPECT_EQ(16U, iv1.size());
4414
4415 EXPECT_EQ(message.size(), ciphertext1.size());
4416
4417 out_params.Clear();
4418 string ciphertext2 = EncryptMessage(message, params, &out_params);
4419 vector<uint8_t> iv2 = CopyIv(out_params);
4420 EXPECT_EQ(16U, iv2.size());
4421
4422 // IVs should be random, so ciphertexts should differ.
4423 EXPECT_NE(ciphertext1, ciphertext2);
4424
4425 auto params_iv1 =
4426 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4427 auto params_iv2 =
4428 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4429
4430 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4431 EXPECT_EQ(message, plaintext);
4432 plaintext = DecryptMessage(ciphertext2, params_iv2);
4433 EXPECT_EQ(message, plaintext);
4434
4435 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4436 plaintext = DecryptMessage(ciphertext1, params_iv2);
4437 EXPECT_NE(message, plaintext);
4438 plaintext = DecryptMessage(ciphertext2, params_iv1);
4439 EXPECT_NE(message, plaintext);
4440}
4441
4442/*
4443 * EncryptionOperationsTest.AesIncremental
4444 *
4445 * Verifies that AES works, all modes, when provided data in various size increments.
4446 */
4447TEST_P(EncryptionOperationsTest, AesIncremental) {
4448 auto block_modes = {
4449 BlockMode::ECB,
4450 BlockMode::CBC,
4451 BlockMode::CTR,
4452 BlockMode::GCM,
4453 };
4454
4455 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4456 .Authorization(TAG_NO_AUTH_REQUIRED)
4457 .AesEncryptionKey(128)
4458 .BlockMode(block_modes)
4459 .Padding(PaddingMode::NONE)
4460 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4461
4462 for (int increment = 1; increment <= 240; ++increment) {
4463 for (auto block_mode : block_modes) {
4464 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004465 auto params =
4466 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4467 if (block_mode == BlockMode::GCM) {
4468 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4469 }
Selene Huang31ab4042020-04-29 04:22:39 -07004470
4471 AuthorizationSet output_params;
4472 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4473
4474 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004475 string to_send;
4476 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004477 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004478 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004479 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4480 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004481
4482 switch (block_mode) {
4483 case BlockMode::GCM:
4484 EXPECT_EQ(message.size() + 16, ciphertext.size());
4485 break;
4486 case BlockMode::CTR:
4487 EXPECT_EQ(message.size(), ciphertext.size());
4488 break;
4489 case BlockMode::CBC:
4490 case BlockMode::ECB:
4491 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4492 break;
4493 }
4494
4495 auto iv = output_params.GetTagValue(TAG_NONCE);
4496 switch (block_mode) {
4497 case BlockMode::CBC:
4498 case BlockMode::GCM:
4499 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004500 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4501 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4502 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004503 break;
4504
4505 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004506 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004507 break;
4508 }
4509
4510 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4511 << "Decrypt begin() failed for block mode " << block_mode;
4512
4513 string plaintext;
4514 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004515 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004516 }
4517 ErrorCode error = Finish(to_send, &plaintext);
4518 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4519 << " and increment " << increment;
4520 if (error == ErrorCode::OK) {
4521 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4522 << block_mode << " and increment " << increment;
4523 }
4524 }
4525 }
4526}
4527
4528struct AesCtrSp80038aTestVector {
4529 const char* key;
4530 const char* nonce;
4531 const char* plaintext;
4532 const char* ciphertext;
4533};
4534
4535// These test vectors are taken from
4536// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4537static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4538 // AES-128
4539 {
4540 "2b7e151628aed2a6abf7158809cf4f3c",
4541 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4542 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4543 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4544 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4545 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4546 },
4547 // AES-192
4548 {
4549 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4550 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4551 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4552 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4553 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4554 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4555 },
4556 // AES-256
4557 {
4558 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4559 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4560 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4561 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4562 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4563 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4564 },
4565};
4566
4567/*
4568 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4569 *
4570 * Verifies AES CTR implementation against SP800-38A test vectors.
4571 */
4572TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4573 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4574 for (size_t i = 0; i < 3; i++) {
4575 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4576 const string key = hex2str(test.key);
4577 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4578 InvalidSizes.end())
4579 continue;
4580 const string nonce = hex2str(test.nonce);
4581 const string plaintext = hex2str(test.plaintext);
4582 const string ciphertext = hex2str(test.ciphertext);
4583 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4584 }
4585}
4586
4587/*
4588 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4589 *
4590 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4591 */
4592TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4594 .Authorization(TAG_NO_AUTH_REQUIRED)
4595 .AesEncryptionKey(128)
4596 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4597 .Padding(PaddingMode::PKCS7)));
4598 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4599 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4600}
4601
4602/*
4603 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4604 *
4605 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4606 */
4607TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4609 .Authorization(TAG_NO_AUTH_REQUIRED)
4610 .AesEncryptionKey(128)
4611 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4612 .Authorization(TAG_CALLER_NONCE)
4613 .Padding(PaddingMode::NONE)));
4614
4615 auto params = AuthorizationSetBuilder()
4616 .BlockMode(BlockMode::CTR)
4617 .Padding(PaddingMode::NONE)
4618 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4619 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4620
4621 params = AuthorizationSetBuilder()
4622 .BlockMode(BlockMode::CTR)
4623 .Padding(PaddingMode::NONE)
4624 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4625 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4626
4627 params = AuthorizationSetBuilder()
4628 .BlockMode(BlockMode::CTR)
4629 .Padding(PaddingMode::NONE)
4630 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4631 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4632}
4633
4634/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004635 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004636 *
4637 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4638 */
4639TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4641 .Authorization(TAG_NO_AUTH_REQUIRED)
4642 .AesEncryptionKey(128)
4643 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4644 .Padding(PaddingMode::NONE)));
4645 // Two-block message.
4646 string message = "12345678901234567890123456789012";
4647 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4648 AuthorizationSet out_params;
4649 string ciphertext1 = EncryptMessage(message, params, &out_params);
4650 vector<uint8_t> iv1 = CopyIv(out_params);
4651 EXPECT_EQ(message.size(), ciphertext1.size());
4652
4653 out_params.Clear();
4654
4655 string ciphertext2 = EncryptMessage(message, params, &out_params);
4656 vector<uint8_t> iv2 = CopyIv(out_params);
4657 EXPECT_EQ(message.size(), ciphertext2.size());
4658
4659 // IVs should be random, so ciphertexts should differ.
4660 EXPECT_NE(ciphertext1, ciphertext2);
4661
4662 params.push_back(TAG_NONCE, iv1);
4663 string plaintext = DecryptMessage(ciphertext1, params);
4664 EXPECT_EQ(message, plaintext);
4665}
4666
4667/*
4668 * EncryptionOperationsTest.AesCallerNonce
4669 *
4670 * Verifies that AES caller-provided nonces work correctly.
4671 */
4672TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4674 .Authorization(TAG_NO_AUTH_REQUIRED)
4675 .AesEncryptionKey(128)
4676 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4677 .Authorization(TAG_CALLER_NONCE)
4678 .Padding(PaddingMode::NONE)));
4679
4680 string message = "12345678901234567890123456789012";
4681
4682 // Don't specify nonce, should get a random one.
4683 AuthorizationSetBuilder params =
4684 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4685 AuthorizationSet out_params;
4686 string ciphertext = EncryptMessage(message, params, &out_params);
4687 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004688 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004689
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004690 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004691 string plaintext = DecryptMessage(ciphertext, params);
4692 EXPECT_EQ(message, plaintext);
4693
4694 // Now specify a nonce, should also work.
4695 params = AuthorizationSetBuilder()
4696 .BlockMode(BlockMode::CBC)
4697 .Padding(PaddingMode::NONE)
4698 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4699 out_params.Clear();
4700 ciphertext = EncryptMessage(message, params, &out_params);
4701
4702 // Decrypt with correct nonce.
4703 plaintext = DecryptMessage(ciphertext, params);
4704 EXPECT_EQ(message, plaintext);
4705
4706 // Try with wrong nonce.
4707 params = AuthorizationSetBuilder()
4708 .BlockMode(BlockMode::CBC)
4709 .Padding(PaddingMode::NONE)
4710 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4711 plaintext = DecryptMessage(ciphertext, params);
4712 EXPECT_NE(message, plaintext);
4713}
4714
4715/*
4716 * EncryptionOperationsTest.AesCallerNonceProhibited
4717 *
4718 * Verifies that caller-provided nonces are not permitted when not specified in the key
4719 * authorizations.
4720 */
4721TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4723 .Authorization(TAG_NO_AUTH_REQUIRED)
4724 .AesEncryptionKey(128)
4725 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4726 .Padding(PaddingMode::NONE)));
4727
4728 string message = "12345678901234567890123456789012";
4729
4730 // Don't specify nonce, should get a random one.
4731 AuthorizationSetBuilder params =
4732 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4733 AuthorizationSet out_params;
4734 string ciphertext = EncryptMessage(message, params, &out_params);
4735 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004736 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004737
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004738 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004739 string plaintext = DecryptMessage(ciphertext, params);
4740 EXPECT_EQ(message, plaintext);
4741
4742 // Now specify a nonce, should fail
4743 params = AuthorizationSetBuilder()
4744 .BlockMode(BlockMode::CBC)
4745 .Padding(PaddingMode::NONE)
4746 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4747 out_params.Clear();
4748 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4749}
4750
4751/*
4752 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4753 *
4754 * Verifies that AES GCM mode works.
4755 */
4756TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4757 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4758 .Authorization(TAG_NO_AUTH_REQUIRED)
4759 .AesEncryptionKey(128)
4760 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4761 .Padding(PaddingMode::NONE)
4762 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4763
4764 string aad = "foobar";
4765 string message = "123456789012345678901234567890123456";
4766
4767 auto begin_params = AuthorizationSetBuilder()
4768 .BlockMode(BlockMode::GCM)
4769 .Padding(PaddingMode::NONE)
4770 .Authorization(TAG_MAC_LENGTH, 128);
4771
Selene Huang31ab4042020-04-29 04:22:39 -07004772 // Encrypt
4773 AuthorizationSet begin_out_params;
4774 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4775 << "Begin encrypt";
4776 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004777 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4778 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004779 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4780
4781 // Grab nonce
4782 begin_params.push_back(begin_out_params);
4783
4784 // Decrypt.
4785 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004786 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004787 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004788 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004789 EXPECT_EQ(message.length(), plaintext.length());
4790 EXPECT_EQ(message, plaintext);
4791}
4792
4793/*
4794 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4795 *
4796 * Verifies that AES GCM mode works, even when there's a long delay
4797 * between operations.
4798 */
4799TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4801 .Authorization(TAG_NO_AUTH_REQUIRED)
4802 .AesEncryptionKey(128)
4803 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4804 .Padding(PaddingMode::NONE)
4805 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4806
4807 string aad = "foobar";
4808 string message = "123456789012345678901234567890123456";
4809
4810 auto begin_params = AuthorizationSetBuilder()
4811 .BlockMode(BlockMode::GCM)
4812 .Padding(PaddingMode::NONE)
4813 .Authorization(TAG_MAC_LENGTH, 128);
4814
Selene Huang31ab4042020-04-29 04:22:39 -07004815 // Encrypt
4816 AuthorizationSet begin_out_params;
4817 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4818 << "Begin encrypt";
4819 string ciphertext;
4820 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004821 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004822 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004823 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004824
4825 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4826
4827 // Grab nonce
4828 begin_params.push_back(begin_out_params);
4829
4830 // Decrypt.
4831 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4832 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004833 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004834 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004835 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004836 sleep(5);
4837 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4838 EXPECT_EQ(message.length(), plaintext.length());
4839 EXPECT_EQ(message, plaintext);
4840}
4841
4842/*
4843 * EncryptionOperationsTest.AesGcmDifferentNonces
4844 *
4845 * Verifies that encrypting the same data with different nonces produces different outputs.
4846 */
4847TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4848 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4849 .Authorization(TAG_NO_AUTH_REQUIRED)
4850 .AesEncryptionKey(128)
4851 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4852 .Padding(PaddingMode::NONE)
4853 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4854 .Authorization(TAG_CALLER_NONCE)));
4855
4856 string aad = "foobar";
4857 string message = "123456789012345678901234567890123456";
4858 string nonce1 = "000000000000";
4859 string nonce2 = "111111111111";
4860 string nonce3 = "222222222222";
4861
4862 string ciphertext1 =
4863 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4864 string ciphertext2 =
4865 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4866 string ciphertext3 =
4867 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4868
4869 ASSERT_NE(ciphertext1, ciphertext2);
4870 ASSERT_NE(ciphertext1, ciphertext3);
4871 ASSERT_NE(ciphertext2, ciphertext3);
4872}
4873
4874/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004875 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4876 *
4877 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4878 */
4879TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4881 .Authorization(TAG_NO_AUTH_REQUIRED)
4882 .AesEncryptionKey(128)
4883 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4884 .Padding(PaddingMode::NONE)
4885 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4886
4887 string aad = "foobar";
4888 string message = "123456789012345678901234567890123456";
4889
4890 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4891 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4892 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4893
4894 ASSERT_NE(ciphertext1, ciphertext2);
4895 ASSERT_NE(ciphertext1, ciphertext3);
4896 ASSERT_NE(ciphertext2, ciphertext3);
4897}
4898
4899/*
Selene Huang31ab4042020-04-29 04:22:39 -07004900 * EncryptionOperationsTest.AesGcmTooShortTag
4901 *
4902 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4903 */
4904TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4905 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4906 .Authorization(TAG_NO_AUTH_REQUIRED)
4907 .AesEncryptionKey(128)
4908 .BlockMode(BlockMode::GCM)
4909 .Padding(PaddingMode::NONE)
4910 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4911 string message = "123456789012345678901234567890123456";
4912 auto params = AuthorizationSetBuilder()
4913 .BlockMode(BlockMode::GCM)
4914 .Padding(PaddingMode::NONE)
4915 .Authorization(TAG_MAC_LENGTH, 96);
4916
4917 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4918}
4919
4920/*
4921 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4922 *
4923 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4924 */
4925TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4926 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4927 .Authorization(TAG_NO_AUTH_REQUIRED)
4928 .AesEncryptionKey(128)
4929 .BlockMode(BlockMode::GCM)
4930 .Padding(PaddingMode::NONE)
4931 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4932 string aad = "foobar";
4933 string message = "123456789012345678901234567890123456";
4934 auto params = AuthorizationSetBuilder()
4935 .BlockMode(BlockMode::GCM)
4936 .Padding(PaddingMode::NONE)
4937 .Authorization(TAG_MAC_LENGTH, 128);
4938
Selene Huang31ab4042020-04-29 04:22:39 -07004939 // Encrypt
4940 AuthorizationSet begin_out_params;
4941 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4942 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004943 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004944
4945 AuthorizationSet finish_out_params;
4946 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004947 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4948 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004949
4950 params = AuthorizationSetBuilder()
4951 .Authorizations(begin_out_params)
4952 .BlockMode(BlockMode::GCM)
4953 .Padding(PaddingMode::NONE)
4954 .Authorization(TAG_MAC_LENGTH, 96);
4955
4956 // Decrypt.
4957 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4958}
4959
4960/*
4961 * EncryptionOperationsTest.AesGcmCorruptKey
4962 *
4963 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4964 */
4965TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4966 const uint8_t nonce_bytes[] = {
4967 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4968 };
4969 string nonce = make_string(nonce_bytes);
4970 const uint8_t ciphertext_bytes[] = {
4971 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4972 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4973 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4974 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4975 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4976 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4977 };
4978 string ciphertext = make_string(ciphertext_bytes);
4979
4980 auto params = AuthorizationSetBuilder()
4981 .BlockMode(BlockMode::GCM)
4982 .Padding(PaddingMode::NONE)
4983 .Authorization(TAG_MAC_LENGTH, 128)
4984 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4985
4986 auto import_params = AuthorizationSetBuilder()
4987 .Authorization(TAG_NO_AUTH_REQUIRED)
4988 .AesEncryptionKey(128)
4989 .BlockMode(BlockMode::GCM)
4990 .Padding(PaddingMode::NONE)
4991 .Authorization(TAG_CALLER_NONCE)
4992 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4993
4994 // Import correct key and decrypt
4995 const uint8_t key_bytes[] = {
4996 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4997 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4998 };
4999 string key = make_string(key_bytes);
5000 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5001 string plaintext = DecryptMessage(ciphertext, params);
5002 CheckedDeleteKey();
5003
5004 // Corrupt key and attempt to decrypt
5005 key[0] = 0;
5006 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5007 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5008 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5009 CheckedDeleteKey();
5010}
5011
5012/*
5013 * EncryptionOperationsTest.AesGcmAadNoData
5014 *
5015 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5016 * encrypt.
5017 */
5018TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5020 .Authorization(TAG_NO_AUTH_REQUIRED)
5021 .AesEncryptionKey(128)
5022 .BlockMode(BlockMode::GCM)
5023 .Padding(PaddingMode::NONE)
5024 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5025
5026 string aad = "1234567890123456";
5027 auto params = AuthorizationSetBuilder()
5028 .BlockMode(BlockMode::GCM)
5029 .Padding(PaddingMode::NONE)
5030 .Authorization(TAG_MAC_LENGTH, 128);
5031
Selene Huang31ab4042020-04-29 04:22:39 -07005032 // Encrypt
5033 AuthorizationSet begin_out_params;
5034 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5035 string ciphertext;
5036 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005037 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5038 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005039 EXPECT_TRUE(finish_out_params.empty());
5040
5041 // Grab nonce
5042 params.push_back(begin_out_params);
5043
5044 // Decrypt.
5045 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005046 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005047 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005048 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005049
5050 EXPECT_TRUE(finish_out_params.empty());
5051
5052 EXPECT_EQ("", plaintext);
5053}
5054
5055/*
5056 * EncryptionOperationsTest.AesGcmMultiPartAad
5057 *
5058 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5059 * chunks.
5060 */
5061TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5062 const size_t tag_bits = 128;
5063 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5064 .Authorization(TAG_NO_AUTH_REQUIRED)
5065 .AesEncryptionKey(128)
5066 .BlockMode(BlockMode::GCM)
5067 .Padding(PaddingMode::NONE)
5068 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5069
5070 string message = "123456789012345678901234567890123456";
5071 auto begin_params = AuthorizationSetBuilder()
5072 .BlockMode(BlockMode::GCM)
5073 .Padding(PaddingMode::NONE)
5074 .Authorization(TAG_MAC_LENGTH, tag_bits);
5075 AuthorizationSet begin_out_params;
5076
Selene Huang31ab4042020-04-29 04:22:39 -07005077 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5078
5079 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005080 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5081 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005082 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005083 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5084 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005085
Selene Huang31ab4042020-04-29 04:22:39 -07005086 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005087 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005088
5089 // Grab nonce.
5090 begin_params.push_back(begin_out_params);
5091
5092 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005093 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005094 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005095 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005096 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005097 EXPECT_EQ(message, plaintext);
5098}
5099
5100/*
5101 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5102 *
5103 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5104 */
5105TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5106 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5107 .Authorization(TAG_NO_AUTH_REQUIRED)
5108 .AesEncryptionKey(128)
5109 .BlockMode(BlockMode::GCM)
5110 .Padding(PaddingMode::NONE)
5111 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5112
5113 string message = "123456789012345678901234567890123456";
5114 auto begin_params = AuthorizationSetBuilder()
5115 .BlockMode(BlockMode::GCM)
5116 .Padding(PaddingMode::NONE)
5117 .Authorization(TAG_MAC_LENGTH, 128);
5118 AuthorizationSet begin_out_params;
5119
Selene Huang31ab4042020-04-29 04:22:39 -07005120 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5121
Shawn Willden92d79c02021-02-19 07:31:55 -07005122 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005123 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005124 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5125 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005126
David Drysdaled2cc8c22021-04-15 13:29:45 +01005127 // The failure should have already cancelled the operation.
5128 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5129
Shawn Willden92d79c02021-02-19 07:31:55 -07005130 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005131}
5132
5133/*
5134 * EncryptionOperationsTest.AesGcmBadAad
5135 *
5136 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5137 */
5138TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5139 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5140 .Authorization(TAG_NO_AUTH_REQUIRED)
5141 .AesEncryptionKey(128)
5142 .BlockMode(BlockMode::GCM)
5143 .Padding(PaddingMode::NONE)
5144 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5145
5146 string message = "12345678901234567890123456789012";
5147 auto begin_params = AuthorizationSetBuilder()
5148 .BlockMode(BlockMode::GCM)
5149 .Padding(PaddingMode::NONE)
5150 .Authorization(TAG_MAC_LENGTH, 128);
5151
Selene Huang31ab4042020-04-29 04:22:39 -07005152 // Encrypt
5153 AuthorizationSet begin_out_params;
5154 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005155 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005156 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005157 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005158
5159 // Grab nonce
5160 begin_params.push_back(begin_out_params);
5161
Selene Huang31ab4042020-04-29 04:22:39 -07005162 // Decrypt.
5163 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005164 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005165 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005166 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005167}
5168
5169/*
5170 * EncryptionOperationsTest.AesGcmWrongNonce
5171 *
5172 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5173 */
5174TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5175 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5176 .Authorization(TAG_NO_AUTH_REQUIRED)
5177 .AesEncryptionKey(128)
5178 .BlockMode(BlockMode::GCM)
5179 .Padding(PaddingMode::NONE)
5180 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5181
5182 string message = "12345678901234567890123456789012";
5183 auto begin_params = AuthorizationSetBuilder()
5184 .BlockMode(BlockMode::GCM)
5185 .Padding(PaddingMode::NONE)
5186 .Authorization(TAG_MAC_LENGTH, 128);
5187
Selene Huang31ab4042020-04-29 04:22:39 -07005188 // Encrypt
5189 AuthorizationSet begin_out_params;
5190 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005191 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005192 string ciphertext;
5193 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005194 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005195
5196 // Wrong nonce
5197 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5198
5199 // Decrypt.
5200 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005201 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005202 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005203 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005204
5205 // With wrong nonce, should have gotten garbage plaintext (or none).
5206 EXPECT_NE(message, plaintext);
5207}
5208
5209/*
5210 * EncryptionOperationsTest.AesGcmCorruptTag
5211 *
5212 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5213 */
5214TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5215 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5216 .Authorization(TAG_NO_AUTH_REQUIRED)
5217 .AesEncryptionKey(128)
5218 .BlockMode(BlockMode::GCM)
5219 .Padding(PaddingMode::NONE)
5220 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5221
5222 string aad = "1234567890123456";
5223 string message = "123456789012345678901234567890123456";
5224
5225 auto params = AuthorizationSetBuilder()
5226 .BlockMode(BlockMode::GCM)
5227 .Padding(PaddingMode::NONE)
5228 .Authorization(TAG_MAC_LENGTH, 128);
5229
Selene Huang31ab4042020-04-29 04:22:39 -07005230 // Encrypt
5231 AuthorizationSet begin_out_params;
5232 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005233 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005234 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005235 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005236
5237 // Corrupt tag
5238 ++(*ciphertext.rbegin());
5239
5240 // Grab nonce
5241 params.push_back(begin_out_params);
5242
5243 // Decrypt.
5244 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005245 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005246 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005247 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005248}
5249
5250/*
5251 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5252 *
5253 * Verifies that 3DES is basically functional.
5254 */
5255TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5256 auto auths = AuthorizationSetBuilder()
5257 .TripleDesEncryptionKey(168)
5258 .BlockMode(BlockMode::ECB)
5259 .Authorization(TAG_NO_AUTH_REQUIRED)
5260 .Padding(PaddingMode::NONE);
5261
5262 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5263 // Two-block message.
5264 string message = "1234567890123456";
5265 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5266 string ciphertext1 = EncryptMessage(message, inParams);
5267 EXPECT_EQ(message.size(), ciphertext1.size());
5268
5269 string ciphertext2 = EncryptMessage(string(message), inParams);
5270 EXPECT_EQ(message.size(), ciphertext2.size());
5271
5272 // ECB is deterministic.
5273 EXPECT_EQ(ciphertext1, ciphertext2);
5274
5275 string plaintext = DecryptMessage(ciphertext1, inParams);
5276 EXPECT_EQ(message, plaintext);
5277}
5278
5279/*
5280 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5281 *
5282 * Verifies that CBC keys reject ECB usage.
5283 */
5284TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5285 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5286 .TripleDesEncryptionKey(168)
5287 .BlockMode(BlockMode::CBC)
5288 .Authorization(TAG_NO_AUTH_REQUIRED)
5289 .Padding(PaddingMode::NONE)));
5290
5291 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5292 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5293}
5294
5295/*
5296 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5297 *
5298 * Tests ECB mode with PKCS#7 padding, various message sizes.
5299 */
5300TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5302 .TripleDesEncryptionKey(168)
5303 .BlockMode(BlockMode::ECB)
5304 .Authorization(TAG_NO_AUTH_REQUIRED)
5305 .Padding(PaddingMode::PKCS7)));
5306
5307 for (size_t i = 0; i < 32; ++i) {
5308 string message(i, 'a');
5309 auto inParams =
5310 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5311 string ciphertext = EncryptMessage(message, inParams);
5312 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5313 string plaintext = DecryptMessage(ciphertext, inParams);
5314 EXPECT_EQ(message, plaintext);
5315 }
5316}
5317
5318/*
5319 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5320 *
5321 * Verifies that keys configured for no padding reject PKCS7 padding
5322 */
5323TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5325 .TripleDesEncryptionKey(168)
5326 .BlockMode(BlockMode::ECB)
5327 .Authorization(TAG_NO_AUTH_REQUIRED)
5328 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005329 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5330 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005331}
5332
5333/*
5334 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5335 *
5336 * Verifies that corrupted padding is detected.
5337 */
5338TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5340 .TripleDesEncryptionKey(168)
5341 .BlockMode(BlockMode::ECB)
5342 .Authorization(TAG_NO_AUTH_REQUIRED)
5343 .Padding(PaddingMode::PKCS7)));
5344
5345 string message = "a";
5346 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5347 EXPECT_EQ(8U, ciphertext.size());
5348 EXPECT_NE(ciphertext, message);
5349 ++ciphertext[ciphertext.size() / 2];
5350
5351 AuthorizationSetBuilder begin_params;
5352 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5353 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5354 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5355 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005356 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005357 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5358}
5359
5360struct TripleDesTestVector {
5361 const char* name;
5362 const KeyPurpose purpose;
5363 const BlockMode block_mode;
5364 const PaddingMode padding_mode;
5365 const char* key;
5366 const char* iv;
5367 const char* input;
5368 const char* output;
5369};
5370
5371// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5372// of the NIST vectors are multiples of the block size.
5373static const TripleDesTestVector kTripleDesTestVectors[] = {
5374 {
5375 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5376 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5377 "", // IV
5378 "329d86bdf1bc5af4", // input
5379 "d946c2756d78633f", // output
5380 },
5381 {
5382 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5383 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5384 "", // IV
5385 "6b1540781b01ce1997adae102dbf3c5b", // input
5386 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5387 },
5388 {
5389 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5390 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5391 "", // IV
5392 "6daad94ce08acfe7", // input
5393 "660e7d32dcc90e79", // output
5394 },
5395 {
5396 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5397 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5398 "", // IV
5399 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5400 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5401 },
5402 {
5403 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5404 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5405 "43f791134c5647ba", // IV
5406 "dcc153cef81d6f24", // input
5407 "92538bd8af18d3ba", // output
5408 },
5409 {
5410 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5411 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5412 "c2e999cb6249023c", // IV
5413 "c689aee38a301bb316da75db36f110b5", // input
5414 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5415 },
5416 {
5417 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5418 PaddingMode::PKCS7,
5419 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5420 "c2e999cb6249023c", // IV
5421 "c689aee38a301bb316da75db36f110b500", // input
5422 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5423 },
5424 {
5425 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5426 PaddingMode::PKCS7,
5427 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5428 "c2e999cb6249023c", // IV
5429 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5430 "c689aee38a301bb316da75db36f110b500", // output
5431 },
5432 {
5433 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5434 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5435 "41746c7e442d3681", // IV
5436 "c53a7b0ec40600fe", // input
5437 "d4f00eb455de1034", // output
5438 },
5439 {
5440 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5441 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5442 "3982bc02c3727d45", // IV
5443 "6006f10adef52991fcc777a1238bbb65", // input
5444 "edae09288e9e3bc05746d872b48e3b29", // output
5445 },
5446};
5447
5448/*
5449 * EncryptionOperationsTest.TripleDesTestVector
5450 *
5451 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5452 */
5453TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5454 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5455 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5456 SCOPED_TRACE(test->name);
5457 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5458 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5459 hex2str(test->output));
5460 }
5461}
5462
5463/*
5464 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5465 *
5466 * Validates CBC mode functionality.
5467 */
5468TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5470 .TripleDesEncryptionKey(168)
5471 .BlockMode(BlockMode::CBC)
5472 .Authorization(TAG_NO_AUTH_REQUIRED)
5473 .Padding(PaddingMode::NONE)));
5474
5475 ASSERT_GT(key_blob_.size(), 0U);
5476
5477 // Two-block message.
5478 string message = "1234567890123456";
5479 vector<uint8_t> iv1;
5480 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5481 EXPECT_EQ(message.size(), ciphertext1.size());
5482
5483 vector<uint8_t> iv2;
5484 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5485 EXPECT_EQ(message.size(), ciphertext2.size());
5486
5487 // IVs should be random, so ciphertexts should differ.
5488 EXPECT_NE(iv1, iv2);
5489 EXPECT_NE(ciphertext1, ciphertext2);
5490
5491 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5492 EXPECT_EQ(message, plaintext);
5493}
5494
5495/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005496 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5497 *
5498 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5499 */
5500TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5501 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5502 .TripleDesEncryptionKey(168)
5503 .BlockMode(BlockMode::CBC)
5504 .Authorization(TAG_NO_AUTH_REQUIRED)
5505 .Authorization(TAG_CALLER_NONCE)
5506 .Padding(PaddingMode::NONE)));
5507 auto params = AuthorizationSetBuilder()
5508 .BlockMode(BlockMode::CBC)
5509 .Padding(PaddingMode::NONE)
5510 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5511 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5512}
5513
5514/*
Selene Huang31ab4042020-04-29 04:22:39 -07005515 * EncryptionOperationsTest.TripleDesCallerIv
5516 *
5517 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5518 */
5519TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5521 .TripleDesEncryptionKey(168)
5522 .BlockMode(BlockMode::CBC)
5523 .Authorization(TAG_NO_AUTH_REQUIRED)
5524 .Authorization(TAG_CALLER_NONCE)
5525 .Padding(PaddingMode::NONE)));
5526 string message = "1234567890123456";
5527 vector<uint8_t> iv;
5528 // Don't specify IV, should get a random one.
5529 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5530 EXPECT_EQ(message.size(), ciphertext1.size());
5531 EXPECT_EQ(8U, iv.size());
5532
5533 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5534 EXPECT_EQ(message, plaintext);
5535
5536 // Now specify an IV, should also work.
5537 iv = AidlBuf("abcdefgh");
5538 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5539
5540 // Decrypt with correct IV.
5541 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5542 EXPECT_EQ(message, plaintext);
5543
5544 // Now try with wrong IV.
5545 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5546 EXPECT_NE(message, plaintext);
5547}
5548
5549/*
5550 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5551 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005552 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005553 */
5554TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5555 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5556 .TripleDesEncryptionKey(168)
5557 .BlockMode(BlockMode::CBC)
5558 .Authorization(TAG_NO_AUTH_REQUIRED)
5559 .Padding(PaddingMode::NONE)));
5560
5561 string message = "12345678901234567890123456789012";
5562 vector<uint8_t> iv;
5563 // Don't specify nonce, should get a random one.
5564 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5565 EXPECT_EQ(message.size(), ciphertext1.size());
5566 EXPECT_EQ(8U, iv.size());
5567
5568 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5569 EXPECT_EQ(message, plaintext);
5570
5571 // Now specify a nonce, should fail.
5572 auto input_params = AuthorizationSetBuilder()
5573 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5574 .BlockMode(BlockMode::CBC)
5575 .Padding(PaddingMode::NONE);
5576 AuthorizationSet output_params;
5577 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5578 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5579}
5580
5581/*
5582 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5583 *
5584 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5585 */
5586TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5587 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5588 .TripleDesEncryptionKey(168)
5589 .BlockMode(BlockMode::ECB)
5590 .Authorization(TAG_NO_AUTH_REQUIRED)
5591 .Padding(PaddingMode::NONE)));
5592 // Two-block message.
5593 string message = "1234567890123456";
5594 auto begin_params =
5595 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5596 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5597}
5598
5599/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005600 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005601 *
5602 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5603 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005604TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5605 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5607 .TripleDesEncryptionKey(168)
5608 .BlockMode(blockMode)
5609 .Authorization(TAG_NO_AUTH_REQUIRED)
5610 .Padding(PaddingMode::NONE)));
5611 // Message is slightly shorter than two blocks.
5612 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005613
David Drysdaled2cc8c22021-04-15 13:29:45 +01005614 auto begin_params =
5615 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5616 AuthorizationSet output_params;
5617 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5618 string ciphertext;
5619 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5620
5621 CheckedDeleteKey();
5622 }
Selene Huang31ab4042020-04-29 04:22:39 -07005623}
5624
5625/*
5626 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5627 *
5628 * Verifies that PKCS7 padding works correctly in CBC mode.
5629 */
5630TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5632 .TripleDesEncryptionKey(168)
5633 .BlockMode(BlockMode::CBC)
5634 .Authorization(TAG_NO_AUTH_REQUIRED)
5635 .Padding(PaddingMode::PKCS7)));
5636
5637 // Try various message lengths; all should work.
5638 for (size_t i = 0; i < 32; ++i) {
5639 string message(i, 'a');
5640 vector<uint8_t> iv;
5641 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5642 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5643 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5644 EXPECT_EQ(message, plaintext);
5645 }
5646}
5647
5648/*
5649 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5650 *
5651 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5652 */
5653TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5655 .TripleDesEncryptionKey(168)
5656 .BlockMode(BlockMode::CBC)
5657 .Authorization(TAG_NO_AUTH_REQUIRED)
5658 .Padding(PaddingMode::NONE)));
5659
5660 // Try various message lengths; all should fail.
5661 for (size_t i = 0; i < 32; ++i) {
5662 auto begin_params =
5663 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5664 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5665 }
5666}
5667
5668/*
5669 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5670 *
5671 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5672 */
5673TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5674 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5675 .TripleDesEncryptionKey(168)
5676 .BlockMode(BlockMode::CBC)
5677 .Authorization(TAG_NO_AUTH_REQUIRED)
5678 .Padding(PaddingMode::PKCS7)));
5679
5680 string message = "a";
5681 vector<uint8_t> iv;
5682 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5683 EXPECT_EQ(8U, ciphertext.size());
5684 EXPECT_NE(ciphertext, message);
5685 ++ciphertext[ciphertext.size() / 2];
5686
5687 auto begin_params = AuthorizationSetBuilder()
5688 .BlockMode(BlockMode::CBC)
5689 .Padding(PaddingMode::PKCS7)
5690 .Authorization(TAG_NONCE, iv);
5691 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5692 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005693 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005694 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5695}
5696
5697/*
5698 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5699 *
5700 * Verifies that 3DES CBC works with many different input sizes.
5701 */
5702TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5704 .TripleDesEncryptionKey(168)
5705 .BlockMode(BlockMode::CBC)
5706 .Authorization(TAG_NO_AUTH_REQUIRED)
5707 .Padding(PaddingMode::NONE)));
5708
5709 int increment = 7;
5710 string message(240, 'a');
5711 AuthorizationSet input_params =
5712 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5713 AuthorizationSet output_params;
5714 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5715
5716 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005717 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005718 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005719 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5720 EXPECT_EQ(message.size(), ciphertext.size());
5721
5722 // Move TAG_NONCE into input_params
5723 input_params = output_params;
5724 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5725 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5726 output_params.Clear();
5727
5728 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5729 string plaintext;
5730 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005731 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005732 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5733 EXPECT_EQ(ciphertext.size(), plaintext.size());
5734 EXPECT_EQ(message, plaintext);
5735}
5736
5737INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5738
5739typedef KeyMintAidlTestBase MaxOperationsTest;
5740
5741/*
5742 * MaxOperationsTest.TestLimitAes
5743 *
5744 * Verifies that the max uses per boot tag works correctly with AES keys.
5745 */
5746TEST_P(MaxOperationsTest, TestLimitAes) {
5747 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5748
5749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5750 .Authorization(TAG_NO_AUTH_REQUIRED)
5751 .AesEncryptionKey(128)
5752 .EcbMode()
5753 .Padding(PaddingMode::NONE)
5754 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5755
5756 string message = "1234567890123456";
5757
5758 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5759
5760 EncryptMessage(message, params);
5761 EncryptMessage(message, params);
5762 EncryptMessage(message, params);
5763
5764 // Fourth time should fail.
5765 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5766}
5767
5768/*
Qi Wud22ec842020-11-26 13:27:53 +08005769 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005770 *
5771 * Verifies that the max uses per boot tag works correctly with RSA keys.
5772 */
5773TEST_P(MaxOperationsTest, TestLimitRsa) {
5774 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5775
5776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5777 .Authorization(TAG_NO_AUTH_REQUIRED)
5778 .RsaSigningKey(1024, 65537)
5779 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005780 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5781 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005782
5783 string message = "1234567890123456";
5784
5785 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5786
5787 SignMessage(message, params);
5788 SignMessage(message, params);
5789 SignMessage(message, params);
5790
5791 // Fourth time should fail.
5792 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5793}
5794
5795INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5796
Qi Wud22ec842020-11-26 13:27:53 +08005797typedef KeyMintAidlTestBase UsageCountLimitTest;
5798
5799/*
Qi Wubeefae42021-01-28 23:16:37 +08005800 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005801 *
Qi Wubeefae42021-01-28 23:16:37 +08005802 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005803 */
Qi Wubeefae42021-01-28 23:16:37 +08005804TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005805 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5806
5807 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5808 .Authorization(TAG_NO_AUTH_REQUIRED)
5809 .AesEncryptionKey(128)
5810 .EcbMode()
5811 .Padding(PaddingMode::NONE)
5812 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5813
5814 // Check the usage count limit tag appears in the authorizations.
5815 AuthorizationSet auths;
5816 for (auto& entry : key_characteristics_) {
5817 auths.push_back(AuthorizationSet(entry.authorizations));
5818 }
5819 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5820 << "key usage count limit " << 1U << " missing";
5821
5822 string message = "1234567890123456";
5823 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5824
Qi Wubeefae42021-01-28 23:16:37 +08005825 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5826 AuthorizationSet keystore_auths =
5827 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5828
Qi Wud22ec842020-11-26 13:27:53 +08005829 // First usage of AES key should work.
5830 EncryptMessage(message, params);
5831
Qi Wud22ec842020-11-26 13:27:53 +08005832 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5833 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5834 // must be invalidated from secure storage (such as RPMB partition).
5835 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5836 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005837 // Usage count limit tag is enforced by keystore, keymint does nothing.
5838 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005839 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5840 }
5841}
5842
5843/*
Qi Wubeefae42021-01-28 23:16:37 +08005844 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005845 *
Qi Wubeefae42021-01-28 23:16:37 +08005846 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005847 */
Qi Wubeefae42021-01-28 23:16:37 +08005848TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5849 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5850
5851 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5852 .Authorization(TAG_NO_AUTH_REQUIRED)
5853 .AesEncryptionKey(128)
5854 .EcbMode()
5855 .Padding(PaddingMode::NONE)
5856 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5857
5858 // Check the usage count limit tag appears in the authorizations.
5859 AuthorizationSet auths;
5860 for (auto& entry : key_characteristics_) {
5861 auths.push_back(AuthorizationSet(entry.authorizations));
5862 }
5863 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5864 << "key usage count limit " << 3U << " missing";
5865
5866 string message = "1234567890123456";
5867 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5868
5869 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5870 AuthorizationSet keystore_auths =
5871 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5872
5873 EncryptMessage(message, params);
5874 EncryptMessage(message, params);
5875 EncryptMessage(message, params);
5876
5877 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5878 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5879 // must be invalidated from secure storage (such as RPMB partition).
5880 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5881 } else {
5882 // Usage count limit tag is enforced by keystore, keymint does nothing.
5883 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5884 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5885 }
5886}
5887
5888/*
5889 * UsageCountLimitTest.TestSingleUseRsa
5890 *
5891 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5892 */
5893TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005894 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5895
5896 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5897 .Authorization(TAG_NO_AUTH_REQUIRED)
5898 .RsaSigningKey(1024, 65537)
5899 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005900 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5901 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005902
5903 // Check the usage count limit tag appears in the authorizations.
5904 AuthorizationSet auths;
5905 for (auto& entry : key_characteristics_) {
5906 auths.push_back(AuthorizationSet(entry.authorizations));
5907 }
5908 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5909 << "key usage count limit " << 1U << " missing";
5910
5911 string message = "1234567890123456";
5912 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5913
Qi Wubeefae42021-01-28 23:16:37 +08005914 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5915 AuthorizationSet keystore_auths =
5916 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5917
Qi Wud22ec842020-11-26 13:27:53 +08005918 // First usage of RSA key should work.
5919 SignMessage(message, params);
5920
Qi Wud22ec842020-11-26 13:27:53 +08005921 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5922 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5923 // must be invalidated from secure storage (such as RPMB partition).
5924 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5925 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005926 // Usage count limit tag is enforced by keystore, keymint does nothing.
5927 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5928 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5929 }
5930}
5931
5932/*
5933 * UsageCountLimitTest.TestLimitUseRsa
5934 *
5935 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5936 */
5937TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5938 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5939
5940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5941 .Authorization(TAG_NO_AUTH_REQUIRED)
5942 .RsaSigningKey(1024, 65537)
5943 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005944 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5945 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005946
5947 // Check the usage count limit tag appears in the authorizations.
5948 AuthorizationSet auths;
5949 for (auto& entry : key_characteristics_) {
5950 auths.push_back(AuthorizationSet(entry.authorizations));
5951 }
5952 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5953 << "key usage count limit " << 3U << " missing";
5954
5955 string message = "1234567890123456";
5956 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5957
5958 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5959 AuthorizationSet keystore_auths =
5960 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5961
5962 SignMessage(message, params);
5963 SignMessage(message, params);
5964 SignMessage(message, params);
5965
5966 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5967 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5968 // must be invalidated from secure storage (such as RPMB partition).
5969 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5970 } else {
5971 // Usage count limit tag is enforced by keystore, keymint does nothing.
5972 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005973 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5974 }
5975}
5976
Qi Wu8e727f72021-02-11 02:49:33 +08005977/*
5978 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5979 *
5980 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5981 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5982 * in hardware.
5983 */
5984TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5985 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5986
5987 auto error = GenerateKey(AuthorizationSetBuilder()
5988 .RsaSigningKey(2048, 65537)
5989 .Digest(Digest::NONE)
5990 .Padding(PaddingMode::NONE)
5991 .Authorization(TAG_NO_AUTH_REQUIRED)
5992 .Authorization(TAG_ROLLBACK_RESISTANCE)
5993 .SetDefaultValidity());
5994 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5995
5996 if (error == ErrorCode::OK) {
5997 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5998 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5999 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6000 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6001
6002 // The KeyMint should also enforce single use key in hardware when it supports rollback
6003 // resistance.
6004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6005 .Authorization(TAG_NO_AUTH_REQUIRED)
6006 .RsaSigningKey(1024, 65537)
6007 .NoDigestOrPadding()
6008 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6009 .SetDefaultValidity()));
6010
6011 // Check the usage count limit tag appears in the hardware authorizations.
6012 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6013 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6014 << "key usage count limit " << 1U << " missing";
6015
6016 string message = "1234567890123456";
6017 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6018
6019 // First usage of RSA key should work.
6020 SignMessage(message, params);
6021
6022 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6023 // must be invalidated from secure storage (such as RPMB partition).
6024 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6025 }
6026}
6027
Qi Wud22ec842020-11-26 13:27:53 +08006028INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6029
David Drysdale7de9feb2021-03-05 14:56:19 +00006030typedef KeyMintAidlTestBase GetHardwareInfoTest;
6031
6032TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6033 // Retrieving hardware info should give the same result each time.
6034 KeyMintHardwareInfo info;
6035 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6036 KeyMintHardwareInfo info2;
6037 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6038 EXPECT_EQ(info, info2);
6039}
6040
6041INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6042
Selene Huang31ab4042020-04-29 04:22:39 -07006043typedef KeyMintAidlTestBase AddEntropyTest;
6044
6045/*
6046 * AddEntropyTest.AddEntropy
6047 *
6048 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6049 * is actually added.
6050 */
6051TEST_P(AddEntropyTest, AddEntropy) {
6052 string data = "foo";
6053 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6054}
6055
6056/*
6057 * AddEntropyTest.AddEmptyEntropy
6058 *
6059 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6060 */
6061TEST_P(AddEntropyTest, AddEmptyEntropy) {
6062 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6063}
6064
6065/*
6066 * AddEntropyTest.AddLargeEntropy
6067 *
6068 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6069 */
6070TEST_P(AddEntropyTest, AddLargeEntropy) {
6071 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6072}
6073
David Drysdalebb3d85e2021-04-13 11:15:51 +01006074/*
6075 * AddEntropyTest.AddTooLargeEntropy
6076 *
6077 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6078 */
6079TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6080 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6081 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6082}
6083
Selene Huang31ab4042020-04-29 04:22:39 -07006084INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6085
Selene Huang31ab4042020-04-29 04:22:39 -07006086typedef KeyMintAidlTestBase KeyDeletionTest;
6087
6088/**
6089 * KeyDeletionTest.DeleteKey
6090 *
6091 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6092 * valid key blob.
6093 */
6094TEST_P(KeyDeletionTest, DeleteKey) {
6095 auto error = GenerateKey(AuthorizationSetBuilder()
6096 .RsaSigningKey(2048, 65537)
6097 .Digest(Digest::NONE)
6098 .Padding(PaddingMode::NONE)
6099 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006100 .Authorization(TAG_ROLLBACK_RESISTANCE)
6101 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006102 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6103
6104 // Delete must work if rollback protection is implemented
6105 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006106 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006107 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6108
6109 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6110
6111 string message = "12345678901234567890123456789012";
6112 AuthorizationSet begin_out_params;
6113 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6114 Begin(KeyPurpose::SIGN, key_blob_,
6115 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6116 &begin_out_params));
6117 AbortIfNeeded();
6118 key_blob_ = AidlBuf();
6119 }
6120}
6121
6122/**
6123 * KeyDeletionTest.DeleteInvalidKey
6124 *
6125 * This test checks that the HAL excepts invalid key blobs..
6126 */
6127TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6128 // Generate key just to check if rollback protection is implemented
6129 auto error = GenerateKey(AuthorizationSetBuilder()
6130 .RsaSigningKey(2048, 65537)
6131 .Digest(Digest::NONE)
6132 .Padding(PaddingMode::NONE)
6133 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006134 .Authorization(TAG_ROLLBACK_RESISTANCE)
6135 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006136 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6137
6138 // Delete must work if rollback protection is implemented
6139 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006140 AuthorizationSet enforced(SecLevelAuthorizations());
6141 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006142
6143 // Delete the key we don't care about the result at this point.
6144 DeleteKey();
6145
6146 // Now create an invalid key blob and delete it.
6147 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6148
6149 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6150 }
6151}
6152
6153/**
6154 * KeyDeletionTest.DeleteAllKeys
6155 *
6156 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6157 *
6158 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6159 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6160 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6161 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6162 * credentials stored in Keystore/Keymint.
6163 */
6164TEST_P(KeyDeletionTest, DeleteAllKeys) {
6165 if (!arm_deleteAllKeys) return;
6166 auto error = GenerateKey(AuthorizationSetBuilder()
6167 .RsaSigningKey(2048, 65537)
6168 .Digest(Digest::NONE)
6169 .Padding(PaddingMode::NONE)
6170 .Authorization(TAG_NO_AUTH_REQUIRED)
6171 .Authorization(TAG_ROLLBACK_RESISTANCE));
6172 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6173
6174 // Delete must work if rollback protection is implemented
6175 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006176 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006177 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6178
6179 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6180
6181 string message = "12345678901234567890123456789012";
6182 AuthorizationSet begin_out_params;
6183
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
6193INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6194
David Drysdaled2cc8c22021-04-15 13:29:45 +01006195typedef KeyMintAidlTestBase KeyUpgradeTest;
6196
6197/**
6198 * KeyUpgradeTest.UpgradeInvalidKey
6199 *
6200 * This test checks that the HAL excepts invalid key blobs..
6201 */
6202TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6203 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6204
6205 std::vector<uint8_t> new_blob;
6206 Status result = keymint_->upgradeKey(key_blob,
6207 AuthorizationSetBuilder()
6208 .Authorization(TAG_APPLICATION_ID, "clientid")
6209 .Authorization(TAG_APPLICATION_DATA, "appdata")
6210 .vector_data(),
6211 &new_blob);
6212 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6213}
6214
6215INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6216
Selene Huang31ab4042020-04-29 04:22:39 -07006217using UpgradeKeyTest = KeyMintAidlTestBase;
6218
6219/*
6220 * UpgradeKeyTest.UpgradeKey
6221 *
6222 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6223 */
6224TEST_P(UpgradeKeyTest, UpgradeKey) {
6225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6226 .AesEncryptionKey(128)
6227 .Padding(PaddingMode::NONE)
6228 .Authorization(TAG_NO_AUTH_REQUIRED)));
6229
6230 auto result = UpgradeKey(key_blob_);
6231
6232 // Key doesn't need upgrading. Should get okay, but no new key blob.
6233 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6234}
6235
6236INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6237
6238using ClearOperationsTest = KeyMintAidlTestBase;
6239
6240/*
6241 * ClearSlotsTest.TooManyOperations
6242 *
6243 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6244 * operations are started without being finished or aborted. Also verifies
6245 * that aborting the operations clears the operations.
6246 *
6247 */
6248TEST_P(ClearOperationsTest, TooManyOperations) {
6249 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6250 .Authorization(TAG_NO_AUTH_REQUIRED)
6251 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006252 .Padding(PaddingMode::NONE)
6253 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006254
6255 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6256 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006257 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006258 AuthorizationSet out_params;
6259 ErrorCode result;
6260 size_t i;
6261
6262 for (i = 0; i < max_operations; i++) {
6263 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6264 if (ErrorCode::OK != result) {
6265 break;
6266 }
6267 }
6268 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6269 // Try again just in case there's a weird overflow bug
6270 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6271 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6272 for (size_t j = 0; j < i; j++) {
6273 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6274 << "Aboort failed for i = " << j << std::endl;
6275 }
6276 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6277 AbortIfNeeded();
6278}
6279
6280INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6281
6282typedef KeyMintAidlTestBase TransportLimitTest;
6283
6284/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006285 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006286 *
6287 * Verifies that passing input data to finish succeeds as expected.
6288 */
6289TEST_P(TransportLimitTest, LargeFinishInput) {
6290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6291 .Authorization(TAG_NO_AUTH_REQUIRED)
6292 .AesEncryptionKey(128)
6293 .BlockMode(BlockMode::ECB)
6294 .Padding(PaddingMode::NONE)));
6295
6296 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6297 auto cipher_params =
6298 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6299
6300 AuthorizationSet out_params;
6301 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6302
6303 string plain_message = std::string(1 << msg_size, 'x');
6304 string encrypted_message;
6305 auto rc = Finish(plain_message, &encrypted_message);
6306
6307 EXPECT_EQ(ErrorCode::OK, rc);
6308 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6309 << "Encrypt finish returned OK, but did not consume all of the given input";
6310 cipher_params.push_back(out_params);
6311
6312 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6313
6314 string decrypted_message;
6315 rc = Finish(encrypted_message, &decrypted_message);
6316 EXPECT_EQ(ErrorCode::OK, rc);
6317 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6318 << "Decrypt finish returned OK, did not consume all of the given input";
6319 }
6320}
6321
6322INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6323
David Zeuthene0c40892021-01-08 12:54:11 -05006324typedef KeyMintAidlTestBase KeyAgreementTest;
6325
6326int CurveToOpenSslCurveName(EcCurve curve) {
6327 switch (curve) {
6328 case EcCurve::P_224:
6329 return NID_secp224r1;
6330 case EcCurve::P_256:
6331 return NID_X9_62_prime256v1;
6332 case EcCurve::P_384:
6333 return NID_secp384r1;
6334 case EcCurve::P_521:
6335 return NID_secp521r1;
6336 }
6337}
6338
6339/*
6340 * KeyAgreementTest.Ecdh
6341 *
6342 * Verifies that ECDH works for all curves
6343 */
6344TEST_P(KeyAgreementTest, Ecdh) {
6345 // Because it's possible to use this API with keys on different curves, we
6346 // check all N^2 combinations where N is the number of supported
6347 // curves.
6348 //
6349 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6350 // lot more curves we can be smart about things and just pick |otherCurve| so
6351 // it's not |curve| and that way we end up with only 2*N runs
6352 //
6353 for (auto curve : ValidCurves()) {
6354 for (auto localCurve : ValidCurves()) {
6355 // Generate EC key locally (with access to private key material)
6356 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6357 int curveName = CurveToOpenSslCurveName(localCurve);
6358 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6359 ASSERT_NE(group, nullptr);
6360 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6361 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6362 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6363 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6364
6365 // Get encoded form of the public part of the locally generated key...
6366 unsigned char* p = nullptr;
6367 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6368 ASSERT_GT(encodedPublicKeySize, 0);
6369 vector<uint8_t> encodedPublicKey(
6370 reinterpret_cast<const uint8_t*>(p),
6371 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6372 OPENSSL_free(p);
6373
6374 // Generate EC key in KeyMint (only access to public key material)
6375 vector<uint8_t> challenge = {0x41, 0x42};
6376 EXPECT_EQ(
6377 ErrorCode::OK,
6378 GenerateKey(AuthorizationSetBuilder()
6379 .Authorization(TAG_NO_AUTH_REQUIRED)
6380 .Authorization(TAG_EC_CURVE, curve)
6381 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6382 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6383 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006384 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6385 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006386 << "Failed to generate key";
6387 ASSERT_GT(cert_chain_.size(), 0);
6388 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6389 ASSERT_NE(kmKeyCert, nullptr);
6390 // Check that keyAgreement (bit 4) is set in KeyUsage
6391 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6392 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6393 ASSERT_NE(kmPkey, nullptr);
6394 if (dump_Attestations) {
6395 for (size_t n = 0; n < cert_chain_.size(); n++) {
6396 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6397 }
6398 }
6399
6400 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6401 if (curve != localCurve) {
6402 // If the keys are using different curves KeyMint should fail with
6403 // ErrorCode:INVALID_ARGUMENT. Check that.
6404 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6405 string ZabFromKeyMintStr;
6406 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6407 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6408 &ZabFromKeyMintStr));
6409
6410 } else {
6411 // Otherwise if the keys are using the same curve, it should work.
6412 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6413 string ZabFromKeyMintStr;
6414 EXPECT_EQ(ErrorCode::OK,
6415 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6416 &ZabFromKeyMintStr));
6417 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6418
6419 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6420 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6421 ASSERT_NE(ctx, nullptr);
6422 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6423 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6424 size_t ZabFromTestLen = 0;
6425 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6426 vector<uint8_t> ZabFromTest;
6427 ZabFromTest.resize(ZabFromTestLen);
6428 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6429
6430 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6431 }
6432
6433 CheckedDeleteKey();
6434 }
6435 }
6436}
6437
6438INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6439
David Drysdaled2cc8c22021-04-15 13:29:45 +01006440using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6441
6442// This is a problematic test, as it can render the device under test permanently unusable.
6443// Re-enable and run at your own risk.
6444TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6445 auto result = DestroyAttestationIds();
6446 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6447}
6448
6449INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6450
Shawn Willdend659c7c2021-02-19 14:51:51 -07006451using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006452
David Drysdale216d9922021-05-18 11:43:31 +01006453/*
6454 * EarlyBootKeyTest.CreateEarlyBootKeys
6455 *
6456 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6457 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006458TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdale216d9922021-05-18 11:43:31 +01006459 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006460 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6461 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6462
David Drysdaleeaab0f22021-05-27 12:00:53 +01006463 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6464 ASSERT_GT(keyData.blob.size(), 0U);
6465 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6466 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6467 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006468 CheckedDeleteKey(&aesKeyData.blob);
6469 CheckedDeleteKey(&hmacKeyData.blob);
6470 CheckedDeleteKey(&rsaKeyData.blob);
6471 CheckedDeleteKey(&ecdsaKeyData.blob);
6472}
6473
David Drysdale216d9922021-05-18 11:43:31 +01006474/*
David Drysdaleeaab0f22021-05-27 12:00:53 +01006475 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6476 *
6477 * Verifies that creating an early boot key with attestation succeeds.
6478 */
6479TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6480 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6481 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6482 builder->AttestationChallenge("challenge");
6483 builder->AttestationApplicationId("app_id");
6484 });
6485
6486 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6487 ASSERT_GT(keyData.blob.size(), 0U);
6488 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6489 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6490 }
6491 CheckedDeleteKey(&aesKeyData.blob);
6492 CheckedDeleteKey(&hmacKeyData.blob);
6493 CheckedDeleteKey(&rsaKeyData.blob);
6494 CheckedDeleteKey(&ecdsaKeyData.blob);
6495}
6496
6497/*
6498 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdale216d9922021-05-18 11:43:31 +01006499 *
6500 * Verifies that using early boot keys at a later stage fails.
6501 */
6502TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6503 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6504 .Authorization(TAG_NO_AUTH_REQUIRED)
6505 .Authorization(TAG_EARLY_BOOT_ONLY)
6506 .HmacKey(128)
6507 .Digest(Digest::SHA_2_256)
6508 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6509 AuthorizationSet output_params;
6510 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6511 AuthorizationSetBuilder()
6512 .Digest(Digest::SHA_2_256)
6513 .Authorization(TAG_MAC_LENGTH, 256),
6514 &output_params));
6515}
6516
6517/*
6518 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6519 *
6520 * Verifies that importing early boot keys fails.
6521 */
6522TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6523 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6524 .Authorization(TAG_NO_AUTH_REQUIRED)
6525 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdale308916b2021-06-08 15:46:11 +01006526 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale216d9922021-05-18 11:43:31 +01006527 .Digest(Digest::SHA_2_256)
6528 .SetDefaultValidity(),
6529 KeyFormat::PKCS8, ec_256_key));
6530}
6531
David Drysdaled2cc8c22021-04-15 13:29:45 +01006532// 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 +00006533// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6534// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6535// early boot, so you'll have to reboot between runs.
6536TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6537 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6538 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6539 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6540 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6541 EXPECT_TRUE(
6542 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6543 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6544 EXPECT_TRUE(
6545 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6546
6547 // Should be able to use keys, since early boot has not ended
6548 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6549 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6550 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6551 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6552
6553 // End early boot
6554 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6555 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6556
6557 // Should not be able to use already-created keys.
6558 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6559 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6560 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6561 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6562
6563 CheckedDeleteKey(&aesKeyData.blob);
6564 CheckedDeleteKey(&hmacKeyData.blob);
6565 CheckedDeleteKey(&rsaKeyData.blob);
6566 CheckedDeleteKey(&ecdsaKeyData.blob);
6567
6568 // Should not be able to create new keys
6569 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6570 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6571
6572 CheckedDeleteKey(&aesKeyData.blob);
6573 CheckedDeleteKey(&hmacKeyData.blob);
6574 CheckedDeleteKey(&rsaKeyData.blob);
6575 CheckedDeleteKey(&ecdsaKeyData.blob);
6576}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006577
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006578INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6579
Shawn Willdend659c7c2021-02-19 14:51:51 -07006580using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006581
6582// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6583// between runs... and on most test devices there are no enrolled credentials so it can't be
6584// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6585// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6586// a manual test process, which includes unlocking between runs, which is why it's included here.
6587// Well, that and the fact that it's the only test we can do without also making calls into the
6588// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6589// implications might be, so that may or may not be a solution.
6590TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6591 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6592 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6593
6594 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6595 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6596 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6597 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6598
6599 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006600 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006601 ASSERT_EQ(ErrorCode::OK, rc);
6602 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6603 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6604 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6605 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6606
6607 CheckedDeleteKey(&aesKeyData.blob);
6608 CheckedDeleteKey(&hmacKeyData.blob);
6609 CheckedDeleteKey(&rsaKeyData.blob);
6610 CheckedDeleteKey(&ecdsaKeyData.blob);
6611}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006612
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006613INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6614
Janis Danisevskis24c04702020-12-16 18:28:39 -08006615} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006616
6617int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006618 std::cout << "Testing ";
6619 auto halInstances =
6620 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6621 std::cout << "HAL instances:\n";
6622 for (auto& entry : halInstances) {
6623 std::cout << " " << entry << '\n';
6624 }
6625
Selene Huang31ab4042020-04-29 04:22:39 -07006626 ::testing::InitGoogleTest(&argc, argv);
6627 for (int i = 1; i < argc; ++i) {
6628 if (argv[i][0] == '-') {
6629 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006630 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6631 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006632 }
6633 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006634 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6635 dump_Attestations = true;
6636 } else {
6637 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006638 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006639 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6640 if (std::string(argv[i]) == "--check_patchLevels") {
6641 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6642 }
Selene Huang31ab4042020-04-29 04:22:39 -07006643 }
6644 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006645 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006646}