blob: d41d2707644acf66aaca2beb3d30cf7cd2184a19 [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 Drysdale37af4b32021-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 Drysdale300b5552021-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 Drysdale300b5552021-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 Drysdale300b5552021-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 Drysdale300b5552021-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 Drysdale300b5552021-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.
948 */
949TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
950 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
951 // instance.
952 std::shared_ptr<IRemotelyProvisionedComponent> rp;
953 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
954 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
955
956 // Generate a P-256 keypair to use as an attestation key.
957 MacedPublicKey macedPubKey;
958 std::vector<uint8_t> privateKeyBlob;
959 auto status =
960 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
961 ASSERT_TRUE(status.isOk());
962 vector<uint8_t> coseKeyData;
963 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
964
965 AttestationKey attestation_key;
966 attestation_key.keyBlob = std::move(privateKeyBlob);
967 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
968
969 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
970 auto challenge = "hello";
971 auto app_id = "foo";
972
973 vector<uint8_t> key_blob;
974 vector<KeyCharacteristics> key_characteristics;
975 ASSERT_EQ(ErrorCode::OK,
976 GenerateKey(AuthorizationSetBuilder()
977 .RsaSigningKey(key_size, 65537)
978 .Digest(Digest::NONE)
979 .Padding(PaddingMode::NONE)
980 .AttestationChallenge(challenge)
981 .AttestationApplicationId(app_id)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
985
986 ASSERT_GT(key_blob.size(), 0U);
987 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100988 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100989
990 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
991
992 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
993 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
994 << "Key size " << key_size << "missing";
995 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
996
997 // Attestation by itself is not valid (last entry is not self-signed).
998 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
999
1000 // The signature over the attested key should correspond to the P256 public key.
1001 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1002 ASSERT_TRUE(key_cert.get());
1003 EVP_PKEY_Ptr signing_pubkey;
1004 p256_pub_key(coseKeyData, &signing_pubkey);
1005 ASSERT_TRUE(signing_pubkey.get());
1006
1007 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1008 << "Verification of attested certificate failed "
1009 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1010
1011 CheckedDeleteKey(&key_blob);
1012 }
1013}
1014
1015/*
Selene Huang4f64c222021-04-13 19:54:36 -07001016 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1017 *
1018 * Verifies that keymint attestation for RSA encryption keys with challenge and
1019 * app id is also successful.
1020 */
1021TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1022 auto key_size = 2048;
1023 auto challenge = "hello";
1024 auto app_id = "foo";
1025
Selene Huang6e46f142021-04-20 19:20:11 -07001026 auto subject = "subj 2";
1027 vector<uint8_t> subject_der(make_name_from_str(subject));
1028
1029 uint64_t serial_int = 111166;
1030 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1031
Selene Huang4f64c222021-04-13 19:54:36 -07001032 vector<uint8_t> key_blob;
1033 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001034 ASSERT_EQ(ErrorCode::OK,
1035 GenerateKey(AuthorizationSetBuilder()
1036 .RsaEncryptionKey(key_size, 65537)
1037 .Padding(PaddingMode::NONE)
1038 .AttestationChallenge(challenge)
1039 .AttestationApplicationId(app_id)
1040 .Authorization(TAG_NO_AUTH_REQUIRED)
1041 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1042 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1043 .SetDefaultValidity(),
1044 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001045
1046 ASSERT_GT(key_blob.size(), 0U);
1047 AuthorizationSet auths;
1048 for (auto& entry : key_characteristics) {
1049 auths.push_back(AuthorizationSet(entry.authorizations));
1050 }
1051
1052 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1053 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1054
1055 // Verify that App data and ROT are NOT included.
1056 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1057 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1058
1059 // Check that some unexpected tags/values are NOT present.
1060 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1061 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1062
1063 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1064
1065 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1066 ASSERT_TRUE(os_ver);
1067 EXPECT_EQ(*os_ver, os_version());
1068
1069 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1070
1071 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1072 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1073 << "Key size " << key_size << "missing";
1074 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1075
Selene Huang6e46f142021-04-20 19:20:11 -07001076 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001077 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1078 ASSERT_GT(cert_chain_.size(), 0);
1079
1080 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1081 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1082 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1083 sw_enforced, hw_enforced, SecLevel(),
1084 cert_chain_[0].encodedCertificate));
1085
1086 CheckedDeleteKey(&key_blob);
1087}
1088
1089/*
1090 * NewKeyGenerationTest.RsaWithSelfSign
1091 *
1092 * Verifies that attesting to RSA key generation is successful, and returns
1093 * self signed certificate if no challenge is provided. And signing etc
1094 * works as expected.
1095 */
1096TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001097 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1098 vector<uint8_t> subject_der(make_name_from_str(subject));
1099
1100 uint64_t serial_int = 0;
1101 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1102
Selene Huang4f64c222021-04-13 19:54:36 -07001103 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1104 vector<uint8_t> key_blob;
1105 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001106 ASSERT_EQ(ErrorCode::OK,
1107 GenerateKey(AuthorizationSetBuilder()
1108 .RsaSigningKey(key_size, 65537)
1109 .Digest(Digest::NONE)
1110 .Padding(PaddingMode::NONE)
1111 .Authorization(TAG_NO_AUTH_REQUIRED)
1112 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1113 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1114 .SetDefaultValidity(),
1115 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001116
1117 ASSERT_GT(key_blob.size(), 0U);
1118 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001119 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001120
1121 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1122
1123 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1124 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1125 << "Key size " << key_size << "missing";
1126 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1127
Selene Huang6e46f142021-04-20 19:20:11 -07001128 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001129 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1130 ASSERT_EQ(cert_chain_.size(), 1);
1131
1132 CheckedDeleteKey(&key_blob);
1133 }
1134}
1135
1136/*
1137 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1138 *
1139 * Verifies that attesting to RSA checks for missing app ID.
1140 */
1141TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1142 auto challenge = "hello";
1143 vector<uint8_t> key_blob;
1144 vector<KeyCharacteristics> key_characteristics;
1145
1146 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1147 GenerateKey(AuthorizationSetBuilder()
1148 .RsaSigningKey(2048, 65537)
1149 .Digest(Digest::NONE)
1150 .Padding(PaddingMode::NONE)
1151 .AttestationChallenge(challenge)
1152 .Authorization(TAG_NO_AUTH_REQUIRED)
1153 .SetDefaultValidity(),
1154 &key_blob, &key_characteristics));
1155}
1156
1157/*
1158 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1159 *
1160 * Verifies that attesting to RSA ignores app id if challenge is missing.
1161 */
1162TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1163 auto key_size = 2048;
1164 auto app_id = "foo";
1165
Selene Huang6e46f142021-04-20 19:20:11 -07001166 auto subject = "cert subj 2";
1167 vector<uint8_t> subject_der(make_name_from_str(subject));
1168
1169 uint64_t serial_int = 1;
1170 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1171
Selene Huang4f64c222021-04-13 19:54:36 -07001172 vector<uint8_t> key_blob;
1173 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001174 ASSERT_EQ(ErrorCode::OK,
1175 GenerateKey(AuthorizationSetBuilder()
1176 .RsaSigningKey(key_size, 65537)
1177 .Digest(Digest::NONE)
1178 .Padding(PaddingMode::NONE)
1179 .AttestationApplicationId(app_id)
1180 .Authorization(TAG_NO_AUTH_REQUIRED)
1181 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1182 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1183 .SetDefaultValidity(),
1184 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001185
1186 ASSERT_GT(key_blob.size(), 0U);
1187 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001188 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001189
1190 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1191
1192 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1193 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1194 << "Key size " << key_size << "missing";
1195 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1196
Selene Huang6e46f142021-04-20 19:20:11 -07001197 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001198 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1199 ASSERT_EQ(cert_chain_.size(), 1);
1200
1201 CheckedDeleteKey(&key_blob);
1202}
1203
1204/*
Qi Wud22ec842020-11-26 13:27:53 +08001205 * NewKeyGenerationTest.LimitedUsageRsa
1206 *
1207 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1208 * resulting keys have correct characteristics.
1209 */
1210TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1211 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1212 vector<uint8_t> key_blob;
1213 vector<KeyCharacteristics> key_characteristics;
1214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1215 .RsaSigningKey(key_size, 65537)
1216 .Digest(Digest::NONE)
1217 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001218 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1219 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001220 &key_blob, &key_characteristics));
1221
1222 ASSERT_GT(key_blob.size(), 0U);
1223 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001224 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001225
1226 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1227
1228 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1229 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1230 << "Key size " << key_size << "missing";
1231 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1232
1233 // Check the usage count limit tag appears in the authorizations.
1234 AuthorizationSet auths;
1235 for (auto& entry : key_characteristics) {
1236 auths.push_back(AuthorizationSet(entry.authorizations));
1237 }
1238 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1239 << "key usage count limit " << 1U << " missing";
1240
1241 CheckedDeleteKey(&key_blob);
1242 }
1243}
1244
1245/*
Qi Wubeefae42021-01-28 23:16:37 +08001246 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1247 *
1248 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1249 * resulting keys have correct characteristics and attestation.
1250 */
1251TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001252 auto challenge = "hello";
1253 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001254
Selene Huang6e46f142021-04-20 19:20:11 -07001255 auto subject = "cert subj 2";
1256 vector<uint8_t> subject_der(make_name_from_str(subject));
1257
1258 uint64_t serial_int = 66;
1259 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1260
Selene Huang4f64c222021-04-13 19:54:36 -07001261 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001262 vector<uint8_t> key_blob;
1263 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001264 ASSERT_EQ(ErrorCode::OK,
1265 GenerateKey(AuthorizationSetBuilder()
1266 .RsaSigningKey(key_size, 65537)
1267 .Digest(Digest::NONE)
1268 .Padding(PaddingMode::NONE)
1269 .AttestationChallenge(challenge)
1270 .AttestationApplicationId(app_id)
1271 .Authorization(TAG_NO_AUTH_REQUIRED)
1272 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1273 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1274 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1275 .SetDefaultValidity(),
1276 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001277
1278 ASSERT_GT(key_blob.size(), 0U);
1279 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001280 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001281
1282 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1283
1284 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1285 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1286 << "Key size " << key_size << "missing";
1287 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1288
1289 // Check the usage count limit tag appears in the authorizations.
1290 AuthorizationSet auths;
1291 for (auto& entry : key_characteristics) {
1292 auths.push_back(AuthorizationSet(entry.authorizations));
1293 }
1294 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1295 << "key usage count limit " << 1U << " missing";
1296
1297 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001298 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001299 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001300 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001301
1302 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1303 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1304 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1305 sw_enforced, hw_enforced, SecLevel(),
1306 cert_chain_[0].encodedCertificate));
1307
1308 CheckedDeleteKey(&key_blob);
1309 }
1310}
1311
1312/*
Selene Huang31ab4042020-04-29 04:22:39 -07001313 * NewKeyGenerationTest.NoInvalidRsaSizes
1314 *
1315 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1316 */
1317TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1318 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1319 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001320 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001321 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1322 GenerateKey(AuthorizationSetBuilder()
1323 .RsaSigningKey(key_size, 65537)
1324 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001325 .Padding(PaddingMode::NONE)
1326 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001327 &key_blob, &key_characteristics));
1328 }
1329}
1330
1331/*
1332 * NewKeyGenerationTest.RsaNoDefaultSize
1333 *
1334 * Verifies that failing to specify a key size for RSA key generation returns
1335 * UNSUPPORTED_KEY_SIZE.
1336 */
1337TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1338 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1339 GenerateKey(AuthorizationSetBuilder()
1340 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1341 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001342 .SigningKey()
1343 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001344}
1345
1346/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001347 * NewKeyGenerationTest.RsaMissingParams
1348 *
1349 * Verifies that omitting optional tags works.
1350 */
1351TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1352 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1353 ASSERT_EQ(ErrorCode::OK,
1354 GenerateKey(
1355 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1356 CheckedDeleteKey();
1357 }
1358}
1359
1360/*
Selene Huang31ab4042020-04-29 04:22:39 -07001361 * NewKeyGenerationTest.Ecdsa
1362 *
1363 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1364 * have correct characteristics.
1365 */
1366TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001367 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001368 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001369 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001371 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001372 .Digest(Digest::NONE)
1373 .SetDefaultValidity(),
1374 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001375 ASSERT_GT(key_blob.size(), 0U);
1376 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001377 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001378
Shawn Willden7f424372021-01-10 18:06:50 -07001379 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001380
1381 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001382 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001383
1384 CheckedDeleteKey(&key_blob);
1385 }
1386}
1387
1388/*
Selene Huang4f64c222021-04-13 19:54:36 -07001389 * NewKeyGenerationTest.EcdsaAttestation
1390 *
1391 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1392 * an attestation will be generated.
1393 */
1394TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1395 auto challenge = "hello";
1396 auto app_id = "foo";
1397
Selene Huang6e46f142021-04-20 19:20:11 -07001398 auto subject = "cert subj 2";
1399 vector<uint8_t> subject_der(make_name_from_str(subject));
1400
1401 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1402 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1403
David Drysdaledf09e542021-06-08 15:46:11 +01001404 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001405 vector<uint8_t> key_blob;
1406 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001407 ASSERT_EQ(ErrorCode::OK,
1408 GenerateKey(AuthorizationSetBuilder()
1409 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001410 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001411 .Digest(Digest::NONE)
1412 .AttestationChallenge(challenge)
1413 .AttestationApplicationId(app_id)
1414 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1415 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1416 .SetDefaultValidity(),
1417 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001418 ASSERT_GT(key_blob.size(), 0U);
1419 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001420 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001421
1422 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1423
1424 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001425 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001426
1427 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1428 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001429 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001430
1431 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1432 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1433 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1434 sw_enforced, hw_enforced, SecLevel(),
1435 cert_chain_[0].encodedCertificate));
1436
1437 CheckedDeleteKey(&key_blob);
1438 }
1439}
1440
1441/*
David Drysdale37af4b32021-05-14 16:46:59 +01001442 * NewKeyGenerationTest.EcdsaAttestationTags
1443 *
1444 * Verifies that creation of an attested ECDSA key includes various tags in the
1445 * attestation extension.
1446 */
1447TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1448 auto challenge = "hello";
1449 auto app_id = "foo";
1450 auto subject = "cert subj 2";
1451 vector<uint8_t> subject_der(make_name_from_str(subject));
1452 uint64_t serial_int = 0x1010;
1453 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1454 const AuthorizationSetBuilder base_builder =
1455 AuthorizationSetBuilder()
1456 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001457 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001458 .Digest(Digest::NONE)
1459 .AttestationChallenge(challenge)
1460 .AttestationApplicationId(app_id)
1461 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1462 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1463 .SetDefaultValidity();
1464
1465 // Various tags that map to fields in the attestation extension ASN.1 schema.
1466 auto extra_tags = AuthorizationSetBuilder()
1467 .Authorization(TAG_ROLLBACK_RESISTANCE)
1468 .Authorization(TAG_EARLY_BOOT_ONLY)
1469 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1470 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1471 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1472 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1473 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1474 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1475 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1476 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1477 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1478 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1479 for (const KeyParameter& tag : extra_tags) {
1480 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1481 vector<uint8_t> key_blob;
1482 vector<KeyCharacteristics> key_characteristics;
1483 AuthorizationSetBuilder builder = base_builder;
1484 builder.push_back(tag);
1485 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1486 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1487 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1488 continue;
1489 }
1490 if (result == ErrorCode::UNSUPPORTED_TAG &&
1491 (tag.tag == TAG_ALLOW_WHILE_ON_BODY || tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1492 // Optional tag not supported by this KeyMint implementation.
1493 continue;
1494 }
1495 ASSERT_EQ(result, ErrorCode::OK);
1496 ASSERT_GT(key_blob.size(), 0U);
1497
1498 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1499 ASSERT_GT(cert_chain_.size(), 0);
1500 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1501
1502 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1503 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1504 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID) {
1505 // Expect to find most of the extra tags in the key characteristics
1506 // of the generated key (but not for ATTESTATION_APPLICATION_ID).
1507 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1508 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1509 }
1510
1511 // Verifying the attestation record will check for the specific tag because
1512 // it's included in the authorizations.
1513 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1514 SecLevel(), cert_chain_[0].encodedCertificate));
1515
1516 CheckedDeleteKey(&key_blob);
1517 }
1518
1519 // Device attestation IDs should be rejected for normal attestation requests; these fields
1520 // are only used for device unique attestation.
1521 auto invalid_tags = AuthorizationSetBuilder()
1522 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1523 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1524 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1525 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1526 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1527 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1528 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1529 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1530 for (const KeyParameter& tag : invalid_tags) {
1531 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1532 vector<uint8_t> key_blob;
1533 vector<KeyCharacteristics> key_characteristics;
1534 AuthorizationSetBuilder builder =
1535 AuthorizationSetBuilder()
1536 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001537 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001538 .Digest(Digest::NONE)
1539 .AttestationChallenge(challenge)
1540 .AttestationApplicationId(app_id)
1541 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1542 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1543 .SetDefaultValidity();
1544 builder.push_back(tag);
1545 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1546 GenerateKey(builder, &key_blob, &key_characteristics));
1547 }
1548}
1549
1550/*
1551 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1552 *
1553 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1554 */
1555TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1556 auto challenge = "hello";
1557 auto attest_app_id = "foo";
1558 auto subject = "cert subj 2";
1559 vector<uint8_t> subject_der(make_name_from_str(subject));
1560 uint64_t serial_int = 0x1010;
1561 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1562
1563 // Earlier versions of the attestation extension schema included a slot:
1564 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1565 // This should never have been included, and should never be filled in.
1566 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1567 // to confirm that this field never makes it into the attestation extension.
1568 vector<uint8_t> key_blob;
1569 vector<KeyCharacteristics> key_characteristics;
1570 auto result = GenerateKey(AuthorizationSetBuilder()
1571 .Authorization(TAG_NO_AUTH_REQUIRED)
1572 .EcdsaSigningKey(EcCurve::P_256)
1573 .Digest(Digest::NONE)
1574 .AttestationChallenge(challenge)
1575 .AttestationApplicationId(attest_app_id)
1576 .Authorization(TAG_APPLICATION_ID, "client_id")
1577 .Authorization(TAG_APPLICATION_DATA, "appdata")
1578 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1579 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1580 .SetDefaultValidity(),
1581 &key_blob, &key_characteristics);
1582 ASSERT_EQ(result, ErrorCode::OK);
1583 ASSERT_GT(key_blob.size(), 0U);
1584
1585 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1586 ASSERT_GT(cert_chain_.size(), 0);
1587 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1588
1589 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1590 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1591 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1592 SecLevel(), cert_chain_[0].encodedCertificate));
1593
1594 // Check that the app id is not in the cert.
1595 string app_id = "clientid";
1596 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1597 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1598 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1599 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1600 cert_chain_[0].encodedCertificate.end());
1601
1602 CheckedDeleteKey(&key_blob);
1603}
1604
1605/*
Selene Huang4f64c222021-04-13 19:54:36 -07001606 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1607 *
1608 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1609 * the key will generate a self signed attestation.
1610 */
1611TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001612 auto subject = "cert subj 2";
1613 vector<uint8_t> subject_der(make_name_from_str(subject));
1614
1615 uint64_t serial_int = 0x123456FFF1234;
1616 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1617
David Drysdaledf09e542021-06-08 15:46:11 +01001618 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001619 vector<uint8_t> key_blob;
1620 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001621 ASSERT_EQ(ErrorCode::OK,
1622 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001623 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001624 .Digest(Digest::NONE)
1625 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1626 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1627 .SetDefaultValidity(),
1628 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001629 ASSERT_GT(key_blob.size(), 0U);
1630 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001631 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001632
1633 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1634
1635 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001636 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001637
1638 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001639 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001640 ASSERT_EQ(cert_chain_.size(), 1);
1641
1642 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1643 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1644
1645 CheckedDeleteKey(&key_blob);
1646 }
1647}
1648
1649/*
1650 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1651 *
1652 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1653 * app id must also be provided or else it will fail.
1654 */
1655TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1656 auto challenge = "hello";
1657 vector<uint8_t> key_blob;
1658 vector<KeyCharacteristics> key_characteristics;
1659
1660 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1661 GenerateKey(AuthorizationSetBuilder()
1662 .EcdsaSigningKey(EcCurve::P_256)
1663 .Digest(Digest::NONE)
1664 .AttestationChallenge(challenge)
1665 .SetDefaultValidity(),
1666 &key_blob, &key_characteristics));
1667}
1668
1669/*
1670 * NewKeyGenerationTest.EcdsaIgnoreAppId
1671 *
1672 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1673 * any appid will be ignored, and keymint will generate a self sign certificate.
1674 */
1675TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1676 auto app_id = "foo";
1677
David Drysdaledf09e542021-06-08 15:46:11 +01001678 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001679 vector<uint8_t> key_blob;
1680 vector<KeyCharacteristics> key_characteristics;
1681 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001682 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001683 .Digest(Digest::NONE)
1684 .AttestationApplicationId(app_id)
1685 .SetDefaultValidity(),
1686 &key_blob, &key_characteristics));
1687
1688 ASSERT_GT(key_blob.size(), 0U);
1689 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001690 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001691
1692 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1693
1694 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001695 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001696
1697 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1698 ASSERT_EQ(cert_chain_.size(), 1);
1699
1700 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1701 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1702
1703 CheckedDeleteKey(&key_blob);
1704 }
1705}
1706
1707/*
1708 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1709 *
1710 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1711 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1712 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1713 * to specify how many following bytes will be used to encode the length.
1714 */
1715TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1716 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001717 std::vector<uint32_t> app_id_lengths{143, 258};
1718
1719 for (uint32_t length : app_id_lengths) {
1720 const string app_id(length, 'a');
1721 vector<uint8_t> key_blob;
1722 vector<KeyCharacteristics> key_characteristics;
1723 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1724 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001725 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001726 .Digest(Digest::NONE)
1727 .AttestationChallenge(challenge)
1728 .AttestationApplicationId(app_id)
1729 .SetDefaultValidity(),
1730 &key_blob, &key_characteristics));
1731 ASSERT_GT(key_blob.size(), 0U);
1732 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001733 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001734
1735 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1736
1737 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001738 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001739
1740 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1741 ASSERT_GT(cert_chain_.size(), 0);
1742
1743 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1744 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1745 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1746 sw_enforced, hw_enforced, SecLevel(),
1747 cert_chain_[0].encodedCertificate));
1748
1749 CheckedDeleteKey(&key_blob);
1750 }
1751}
1752
1753/*
Qi Wud22ec842020-11-26 13:27:53 +08001754 * NewKeyGenerationTest.LimitedUsageEcdsa
1755 *
1756 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1757 * resulting keys have correct characteristics.
1758 */
1759TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001760 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001761 vector<uint8_t> key_blob;
1762 vector<KeyCharacteristics> key_characteristics;
1763 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001764 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001765 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001766 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1767 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001768 &key_blob, &key_characteristics));
1769
1770 ASSERT_GT(key_blob.size(), 0U);
1771 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001772 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001773
1774 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1775
1776 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001777 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001778
1779 // Check the usage count limit tag appears in the authorizations.
1780 AuthorizationSet auths;
1781 for (auto& entry : key_characteristics) {
1782 auths.push_back(AuthorizationSet(entry.authorizations));
1783 }
1784 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1785 << "key usage count limit " << 1U << " missing";
1786
1787 CheckedDeleteKey(&key_blob);
1788 }
1789}
1790
1791/*
Selene Huang31ab4042020-04-29 04:22:39 -07001792 * NewKeyGenerationTest.EcdsaDefaultSize
1793 *
David Drysdaledf09e542021-06-08 15:46:11 +01001794 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001795 * UNSUPPORTED_KEY_SIZE.
1796 */
1797TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1798 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1799 GenerateKey(AuthorizationSetBuilder()
1800 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1801 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001802 .Digest(Digest::NONE)
1803 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001804}
1805
1806/*
1807 * NewKeyGenerationTest.EcdsaInvalidSize
1808 *
1809 * Verifies that specifying an invalid key size for EC key generation returns
1810 * UNSUPPORTED_KEY_SIZE.
1811 */
1812TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001813 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001814 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001815 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001816 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001817 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001818 .Digest(Digest::NONE)
1819 .SetDefaultValidity(),
1820 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001821 }
1822
David Drysdaledf09e542021-06-08 15:46:11 +01001823 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1824 GenerateKey(AuthorizationSetBuilder()
1825 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1826 .Authorization(TAG_KEY_SIZE, 190)
1827 .SigningKey()
1828 .Digest(Digest::NONE)
1829 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001830}
1831
1832/*
1833 * NewKeyGenerationTest.EcdsaMismatchKeySize
1834 *
1835 * Verifies that specifying mismatched key size and curve for EC key generation returns
1836 * INVALID_ARGUMENT.
1837 */
1838TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1839 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1840
David Drysdaledf09e542021-06-08 15:46:11 +01001841 auto result = GenerateKey(AuthorizationSetBuilder()
1842 .Authorization(TAG_KEY_SIZE, 224)
1843 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1844 .Digest(Digest::NONE)
1845 .SetDefaultValidity());
1846 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT ||
1847 result == ErrorCode::UNSUPPORTED_ALGORITHM);
Selene Huang31ab4042020-04-29 04:22:39 -07001848}
1849
1850/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001851 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001852 *
1853 * Verifies that keymint does not support any curve designated as unsupported.
1854 */
1855TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1856 Digest digest;
1857 if (SecLevel() == SecurityLevel::STRONGBOX) {
1858 digest = Digest::SHA_2_256;
1859 } else {
1860 digest = Digest::SHA_2_512;
1861 }
1862 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001863 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1864 .EcdsaSigningKey(curve)
1865 .Digest(digest)
1866 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001867 << "Failed to generate key on curve: " << curve;
1868 CheckedDeleteKey();
1869 }
1870}
1871
1872/*
1873 * NewKeyGenerationTest.Hmac
1874 *
1875 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1876 * characteristics.
1877 */
1878TEST_P(NewKeyGenerationTest, Hmac) {
1879 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1880 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001881 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001882 constexpr size_t key_size = 128;
1883 ASSERT_EQ(ErrorCode::OK,
1884 GenerateKey(
1885 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1886 TAG_MIN_MAC_LENGTH, 128),
1887 &key_blob, &key_characteristics));
1888
1889 ASSERT_GT(key_blob.size(), 0U);
1890 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001891 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001892
Shawn Willden7f424372021-01-10 18:06:50 -07001893 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1894 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1895 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1896 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001897
1898 CheckedDeleteKey(&key_blob);
1899 }
1900}
1901
1902/*
Selene Huang4f64c222021-04-13 19:54:36 -07001903 * NewKeyGenerationTest.HmacNoAttestation
1904 *
1905 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1906 * and app id are provided.
1907 */
1908TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1909 auto challenge = "hello";
1910 auto app_id = "foo";
1911
1912 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1913 vector<uint8_t> key_blob;
1914 vector<KeyCharacteristics> key_characteristics;
1915 constexpr size_t key_size = 128;
1916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1917 .HmacKey(key_size)
1918 .Digest(digest)
1919 .AttestationChallenge(challenge)
1920 .AttestationApplicationId(app_id)
1921 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1922 &key_blob, &key_characteristics));
1923
1924 ASSERT_GT(key_blob.size(), 0U);
1925 ASSERT_EQ(cert_chain_.size(), 0);
1926 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001927 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001928
1929 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1930 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1931 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1932 << "Key size " << key_size << "missing";
1933
1934 CheckedDeleteKey(&key_blob);
1935 }
1936}
1937
1938/*
Qi Wud22ec842020-11-26 13:27:53 +08001939 * NewKeyGenerationTest.LimitedUsageHmac
1940 *
1941 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1942 * resulting keys have correct characteristics.
1943 */
1944TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1945 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1946 vector<uint8_t> key_blob;
1947 vector<KeyCharacteristics> key_characteristics;
1948 constexpr size_t key_size = 128;
1949 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1950 .HmacKey(key_size)
1951 .Digest(digest)
1952 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1953 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1954 &key_blob, &key_characteristics));
1955
1956 ASSERT_GT(key_blob.size(), 0U);
1957 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001958 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001959
1960 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1961 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1962 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1963 << "Key size " << key_size << "missing";
1964
1965 // Check the usage count limit tag appears in the authorizations.
1966 AuthorizationSet auths;
1967 for (auto& entry : key_characteristics) {
1968 auths.push_back(AuthorizationSet(entry.authorizations));
1969 }
1970 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1971 << "key usage count limit " << 1U << " missing";
1972
1973 CheckedDeleteKey(&key_blob);
1974 }
1975}
1976
1977/*
Selene Huang31ab4042020-04-29 04:22:39 -07001978 * NewKeyGenerationTest.HmacCheckKeySizes
1979 *
1980 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1981 */
1982TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1983 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1984 if (key_size < 64 || key_size % 8 != 0) {
1985 // To keep this test from being very slow, we only test a random fraction of
1986 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1987 // them, we expect to run ~40 of them in each run.
1988 if (key_size % 8 == 0 || random() % 10 == 0) {
1989 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1990 GenerateKey(AuthorizationSetBuilder()
1991 .HmacKey(key_size)
1992 .Digest(Digest::SHA_2_256)
1993 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1994 << "HMAC key size " << key_size << " invalid";
1995 }
1996 } else {
1997 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1998 .HmacKey(key_size)
1999 .Digest(Digest::SHA_2_256)
2000 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2001 << "Failed to generate HMAC key of size " << key_size;
2002 CheckedDeleteKey();
2003 }
2004 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002005 if (SecLevel() == SecurityLevel::STRONGBOX) {
2006 // STRONGBOX devices must not support keys larger than 512 bits.
2007 size_t key_size = 520;
2008 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2009 GenerateKey(AuthorizationSetBuilder()
2010 .HmacKey(key_size)
2011 .Digest(Digest::SHA_2_256)
2012 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2013 << "HMAC key size " << key_size << " unexpectedly valid";
2014 }
Selene Huang31ab4042020-04-29 04:22:39 -07002015}
2016
2017/*
2018 * NewKeyGenerationTest.HmacCheckMinMacLengths
2019 *
2020 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2021 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2022 * specific MAC length that failed, so reproducing a failed run will be easy.
2023 */
2024TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2025 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2026 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2027 // To keep this test from being very long, we only test a random fraction of
2028 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2029 // we expect to run ~17 of them in each run.
2030 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2031 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2032 GenerateKey(AuthorizationSetBuilder()
2033 .HmacKey(128)
2034 .Digest(Digest::SHA_2_256)
2035 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2036 << "HMAC min mac length " << min_mac_length << " invalid.";
2037 }
2038 } else {
2039 EXPECT_EQ(ErrorCode::OK,
2040 GenerateKey(AuthorizationSetBuilder()
2041 .HmacKey(128)
2042 .Digest(Digest::SHA_2_256)
2043 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2044 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2045 CheckedDeleteKey();
2046 }
2047 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002048
2049 // Minimum MAC length must be no more than 512 bits.
2050 size_t min_mac_length = 520;
2051 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2052 GenerateKey(AuthorizationSetBuilder()
2053 .HmacKey(128)
2054 .Digest(Digest::SHA_2_256)
2055 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2056 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002057}
2058
2059/*
2060 * NewKeyGenerationTest.HmacMultipleDigests
2061 *
2062 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2063 */
2064TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2065 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2066
2067 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2068 GenerateKey(AuthorizationSetBuilder()
2069 .HmacKey(128)
2070 .Digest(Digest::SHA1)
2071 .Digest(Digest::SHA_2_256)
2072 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2073}
2074
2075/*
2076 * NewKeyGenerationTest.HmacDigestNone
2077 *
2078 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2079 */
2080TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2081 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2082 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2083 128)));
2084
2085 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2086 GenerateKey(AuthorizationSetBuilder()
2087 .HmacKey(128)
2088 .Digest(Digest::NONE)
2089 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2090}
2091
Selene Huang4f64c222021-04-13 19:54:36 -07002092/*
2093 * NewKeyGenerationTest.AesNoAttestation
2094 *
2095 * Verifies that attestation parameters to AES keys are ignored and generateKey
2096 * will succeed.
2097 */
2098TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2099 auto challenge = "hello";
2100 auto app_id = "foo";
2101
2102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2103 .Authorization(TAG_NO_AUTH_REQUIRED)
2104 .AesEncryptionKey(128)
2105 .EcbMode()
2106 .Padding(PaddingMode::PKCS7)
2107 .AttestationChallenge(challenge)
2108 .AttestationApplicationId(app_id)));
2109
2110 ASSERT_EQ(cert_chain_.size(), 0);
2111}
2112
2113/*
2114 * NewKeyGenerationTest.TripleDesNoAttestation
2115 *
2116 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2117 * will be successful. No attestation should be generated.
2118 */
2119TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2120 auto challenge = "hello";
2121 auto app_id = "foo";
2122
2123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2124 .TripleDesEncryptionKey(168)
2125 .BlockMode(BlockMode::ECB)
2126 .Authorization(TAG_NO_AUTH_REQUIRED)
2127 .Padding(PaddingMode::NONE)
2128 .AttestationChallenge(challenge)
2129 .AttestationApplicationId(app_id)));
2130 ASSERT_EQ(cert_chain_.size(), 0);
2131}
2132
Selene Huang31ab4042020-04-29 04:22:39 -07002133INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2134
2135typedef KeyMintAidlTestBase SigningOperationsTest;
2136
2137/*
2138 * SigningOperationsTest.RsaSuccess
2139 *
2140 * Verifies that raw RSA signature operations succeed.
2141 */
2142TEST_P(SigningOperationsTest, RsaSuccess) {
2143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2144 .RsaSigningKey(2048, 65537)
2145 .Digest(Digest::NONE)
2146 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002147 .Authorization(TAG_NO_AUTH_REQUIRED)
2148 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002149 string message = "12345678901234567890123456789012";
2150 string signature = SignMessage(
2151 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002152 LocalVerifyMessage(message, signature,
2153 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2154}
2155
2156/*
2157 * SigningOperationsTest.RsaAllPaddingsAndDigests
2158 *
2159 * Verifies RSA signature/verification for all padding modes and digests.
2160 */
2161TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2162 auto authorizations = AuthorizationSetBuilder()
2163 .Authorization(TAG_NO_AUTH_REQUIRED)
2164 .RsaSigningKey(2048, 65537)
2165 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2166 .Padding(PaddingMode::NONE)
2167 .Padding(PaddingMode::RSA_PSS)
2168 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2169 .SetDefaultValidity();
2170
2171 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2172
2173 string message(128, 'a');
2174 string corrupt_message(message);
2175 ++corrupt_message[corrupt_message.size() / 2];
2176
2177 for (auto padding :
2178 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2179 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2180 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2181 // Digesting only makes sense with padding.
2182 continue;
2183 }
2184
2185 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2186 // PSS requires digesting.
2187 continue;
2188 }
2189
2190 string signature =
2191 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2192 LocalVerifyMessage(message, signature,
2193 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2194 }
2195 }
Selene Huang31ab4042020-04-29 04:22:39 -07002196}
2197
2198/*
2199 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2200 *
Shawn Willden7f424372021-01-10 18:06:50 -07002201 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002202 */
2203TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2204 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2205 .Authorization(TAG_NO_AUTH_REQUIRED)
2206 .RsaSigningKey(2048, 65537)
2207 .Digest(Digest::NONE)
2208 .Padding(PaddingMode::NONE)
2209 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002210 .Authorization(TAG_APPLICATION_DATA, "appdata")
2211 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002212
2213 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2214
Selene Huang31ab4042020-04-29 04:22:39 -07002215 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2216 Begin(KeyPurpose::SIGN,
2217 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2218 AbortIfNeeded();
2219 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2220 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2221 .Digest(Digest::NONE)
2222 .Padding(PaddingMode::NONE)
2223 .Authorization(TAG_APPLICATION_ID, "clientid")));
2224 AbortIfNeeded();
2225 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2226 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2227 .Digest(Digest::NONE)
2228 .Padding(PaddingMode::NONE)
2229 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2230 AbortIfNeeded();
2231 EXPECT_EQ(ErrorCode::OK,
2232 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2233 .Digest(Digest::NONE)
2234 .Padding(PaddingMode::NONE)
2235 .Authorization(TAG_APPLICATION_DATA, "appdata")
2236 .Authorization(TAG_APPLICATION_ID, "clientid")));
2237 AbortIfNeeded();
2238}
2239
2240/*
2241 * SigningOperationsTest.RsaPssSha256Success
2242 *
2243 * Verifies that RSA-PSS signature operations succeed.
2244 */
2245TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2247 .RsaSigningKey(2048, 65537)
2248 .Digest(Digest::SHA_2_256)
2249 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002250 .Authorization(TAG_NO_AUTH_REQUIRED)
2251 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002252 // Use large message, which won't work without digesting.
2253 string message(1024, 'a');
2254 string signature = SignMessage(
2255 message,
2256 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2257}
2258
2259/*
2260 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2261 *
2262 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2263 * supports only unpadded operations.
2264 */
2265TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2267 .RsaSigningKey(2048, 65537)
2268 .Digest(Digest::NONE)
2269 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002270 .Padding(PaddingMode::NONE)
2271 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002272 string message = "12345678901234567890123456789012";
2273 string signature;
2274
2275 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2276 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2277 .Digest(Digest::NONE)
2278 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2279}
2280
2281/*
2282 * SigningOperationsTest.NoUserConfirmation
2283 *
2284 * Verifies that keymint rejects signing operations for keys with
2285 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2286 * presented.
2287 */
2288TEST_P(SigningOperationsTest, NoUserConfirmation) {
2289 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2291 .RsaSigningKey(1024, 65537)
2292 .Digest(Digest::NONE)
2293 .Padding(PaddingMode::NONE)
2294 .Authorization(TAG_NO_AUTH_REQUIRED)
2295 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2296 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002297
2298 const string message = "12345678901234567890123456789012";
2299 EXPECT_EQ(ErrorCode::OK,
2300 Begin(KeyPurpose::SIGN,
2301 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2302 string signature;
2303 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2304}
2305
2306/*
2307 * SigningOperationsTest.RsaPkcs1Sha256Success
2308 *
2309 * Verifies that digested RSA-PKCS1 signature operations succeed.
2310 */
2311TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2313 .RsaSigningKey(2048, 65537)
2314 .Digest(Digest::SHA_2_256)
2315 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002316 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2317 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002318 string message(1024, 'a');
2319 string signature = SignMessage(message, AuthorizationSetBuilder()
2320 .Digest(Digest::SHA_2_256)
2321 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2322}
2323
2324/*
2325 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2326 *
2327 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2328 */
2329TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2331 .RsaSigningKey(2048, 65537)
2332 .Digest(Digest::NONE)
2333 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002334 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2335 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002336 string message(53, 'a');
2337 string signature = SignMessage(message, AuthorizationSetBuilder()
2338 .Digest(Digest::NONE)
2339 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2340}
2341
2342/*
2343 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2344 *
2345 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2346 * given a too-long message.
2347 */
2348TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2350 .RsaSigningKey(2048, 65537)
2351 .Digest(Digest::NONE)
2352 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002353 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2354 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002355 string message(257, 'a');
2356
2357 EXPECT_EQ(ErrorCode::OK,
2358 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2359 .Digest(Digest::NONE)
2360 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2361 string signature;
2362 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2363}
2364
2365/*
2366 * SigningOperationsTest.RsaPssSha512TooSmallKey
2367 *
2368 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2369 * used with a key that is too small for the message.
2370 *
2371 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2372 * keymint specification requires that salt_size == digest_size, so the message will be
2373 * digest_size * 2 +
2374 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2375 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2376 * for a 1024-bit key.
2377 */
2378TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2379 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2381 .RsaSigningKey(1024, 65537)
2382 .Digest(Digest::SHA_2_512)
2383 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002384 .Padding(PaddingMode::RSA_PSS)
2385 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002386 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2387 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2388 .Digest(Digest::SHA_2_512)
2389 .Padding(PaddingMode::RSA_PSS)));
2390}
2391
2392/*
2393 * SigningOperationsTest.RsaNoPaddingTooLong
2394 *
2395 * Verifies that raw RSA signature operations fail with the correct error code when
2396 * given a too-long message.
2397 */
2398TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2399 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2400 .RsaSigningKey(2048, 65537)
2401 .Digest(Digest::NONE)
2402 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002403 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2404 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002405 // One byte too long
2406 string message(2048 / 8 + 1, 'a');
2407 ASSERT_EQ(ErrorCode::OK,
2408 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2409 .Digest(Digest::NONE)
2410 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2411 string result;
2412 ErrorCode finish_error_code = Finish(message, &result);
2413 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2414 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2415
2416 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2417 message = string(128 * 1024, 'a');
2418 ASSERT_EQ(ErrorCode::OK,
2419 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2420 .Digest(Digest::NONE)
2421 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2422 finish_error_code = Finish(message, &result);
2423 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2424 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2425}
2426
2427/*
2428 * SigningOperationsTest.RsaAbort
2429 *
2430 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2431 * test, but the behavior should be algorithm and purpose-independent.
2432 */
2433TEST_P(SigningOperationsTest, RsaAbort) {
2434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2435 .RsaSigningKey(2048, 65537)
2436 .Digest(Digest::NONE)
2437 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002438 .Padding(PaddingMode::NONE)
2439 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002440
2441 ASSERT_EQ(ErrorCode::OK,
2442 Begin(KeyPurpose::SIGN,
2443 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2444 EXPECT_EQ(ErrorCode::OK, Abort());
2445
2446 // Another abort should fail
2447 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2448
2449 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002450 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002451}
2452
2453/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002454 * SigningOperationsTest.RsaNonUniqueParams
2455 *
2456 * Verifies that an operation with multiple padding modes is rejected.
2457 */
2458TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2459 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2460 .RsaSigningKey(2048, 65537)
2461 .Digest(Digest::NONE)
2462 .Digest(Digest::SHA1)
2463 .Authorization(TAG_NO_AUTH_REQUIRED)
2464 .Padding(PaddingMode::NONE)
2465 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2466 .SetDefaultValidity()));
2467
2468 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2469 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2470 .Digest(Digest::NONE)
2471 .Padding(PaddingMode::NONE)
2472 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2473
Tommy Chiuc93c4392021-05-11 18:36:50 +08002474 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2475 .Digest(Digest::NONE)
2476 .Digest(Digest::SHA1)
2477 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2478 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002479
2480 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2481 Begin(KeyPurpose::SIGN,
2482 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2483}
2484
2485/*
Selene Huang31ab4042020-04-29 04:22:39 -07002486 * SigningOperationsTest.RsaUnsupportedPadding
2487 *
2488 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2489 * with a padding mode inappropriate for RSA.
2490 */
2491TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2493 .RsaSigningKey(2048, 65537)
2494 .Authorization(TAG_NO_AUTH_REQUIRED)
2495 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002496 .Padding(PaddingMode::PKCS7)
2497 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002498 ASSERT_EQ(
2499 ErrorCode::UNSUPPORTED_PADDING_MODE,
2500 Begin(KeyPurpose::SIGN,
2501 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002502 CheckedDeleteKey();
2503
2504 ASSERT_EQ(ErrorCode::OK,
2505 GenerateKey(
2506 AuthorizationSetBuilder()
2507 .RsaSigningKey(2048, 65537)
2508 .Authorization(TAG_NO_AUTH_REQUIRED)
2509 .Digest(Digest::SHA_2_256 /* supported digest */)
2510 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2511 .SetDefaultValidity()));
2512 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2513 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2514 .Digest(Digest::SHA_2_256)
2515 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002516}
2517
2518/*
2519 * SigningOperationsTest.RsaPssNoDigest
2520 *
2521 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2522 */
2523TEST_P(SigningOperationsTest, RsaNoDigest) {
2524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2525 .RsaSigningKey(2048, 65537)
2526 .Authorization(TAG_NO_AUTH_REQUIRED)
2527 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002528 .Padding(PaddingMode::RSA_PSS)
2529 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002530 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2531 Begin(KeyPurpose::SIGN,
2532 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2533
2534 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2535 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2536}
2537
2538/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002539 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002540 *
2541 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2542 * supported in some cases (as validated in other tests), but a mode must be specified.
2543 */
2544TEST_P(SigningOperationsTest, RsaNoPadding) {
2545 // Padding must be specified
2546 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2547 .RsaKey(2048, 65537)
2548 .Authorization(TAG_NO_AUTH_REQUIRED)
2549 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002550 .Digest(Digest::NONE)
2551 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002552 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2553 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2554}
2555
2556/*
2557 * SigningOperationsTest.RsaShortMessage
2558 *
2559 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2560 */
2561TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2563 .Authorization(TAG_NO_AUTH_REQUIRED)
2564 .RsaSigningKey(2048, 65537)
2565 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002566 .Padding(PaddingMode::NONE)
2567 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002568
2569 // Barely shorter
2570 string message(2048 / 8 - 1, 'a');
2571 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2572
2573 // Much shorter
2574 message = "a";
2575 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2576}
2577
2578/*
2579 * SigningOperationsTest.RsaSignWithEncryptionKey
2580 *
2581 * Verifies that RSA encryption keys cannot be used to sign.
2582 */
2583TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2585 .Authorization(TAG_NO_AUTH_REQUIRED)
2586 .RsaEncryptionKey(2048, 65537)
2587 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002588 .Padding(PaddingMode::NONE)
2589 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002590 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2591 Begin(KeyPurpose::SIGN,
2592 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2593}
2594
2595/*
2596 * SigningOperationsTest.RsaSignTooLargeMessage
2597 *
2598 * Verifies that attempting a raw signature of a message which is the same length as the key,
2599 * but numerically larger than the public modulus, fails with the correct error.
2600 */
2601TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2603 .Authorization(TAG_NO_AUTH_REQUIRED)
2604 .RsaSigningKey(2048, 65537)
2605 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002606 .Padding(PaddingMode::NONE)
2607 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002608
2609 // Largest possible message will always be larger than the public modulus.
2610 string message(2048 / 8, static_cast<char>(0xff));
2611 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2612 .Authorization(TAG_NO_AUTH_REQUIRED)
2613 .Digest(Digest::NONE)
2614 .Padding(PaddingMode::NONE)));
2615 string signature;
2616 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2617}
2618
2619/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002620 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2621 *
2622 * Verifies ECDSA signature/verification for all digests and curves.
2623 */
2624TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2625 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2626
2627 string message = "1234567890";
2628 string corrupt_message = "2234567890";
2629 for (auto curve : ValidCurves()) {
2630 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2631 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2632 .Authorization(TAG_NO_AUTH_REQUIRED)
2633 .EcdsaSigningKey(curve)
2634 .Digest(digests)
2635 .SetDefaultValidity());
2636 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2637 if (error != ErrorCode::OK) {
2638 continue;
2639 }
2640
2641 for (auto digest : digests) {
2642 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2643 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2644 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2645 }
2646
2647 auto rc = DeleteKey();
2648 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2649 }
2650}
2651
2652/*
Selene Huang31ab4042020-04-29 04:22:39 -07002653 * SigningOperationsTest.EcdsaAllCurves
2654 *
2655 * Verifies that ECDSA operations succeed with all possible curves.
2656 */
2657TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2658 for (auto curve : ValidCurves()) {
2659 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2660 .Authorization(TAG_NO_AUTH_REQUIRED)
2661 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002662 .Digest(Digest::SHA_2_256)
2663 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002664 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2665 if (error != ErrorCode::OK) continue;
2666
2667 string message(1024, 'a');
2668 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2669 CheckedDeleteKey();
2670 }
2671}
2672
2673/*
2674 * SigningOperationsTest.EcdsaNoDigestHugeData
2675 *
2676 * Verifies that ECDSA operations support very large messages, even without digesting. This
2677 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2678 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2679 * the framework.
2680 */
2681TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2683 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002684 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002685 .Digest(Digest::NONE)
2686 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002687 string message(1 * 1024, 'a');
2688 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2689}
2690
2691/*
2692 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2693 *
2694 * Verifies that using an EC key requires the correct app ID/data.
2695 */
2696TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2697 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2698 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002699 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002700 .Digest(Digest::NONE)
2701 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002702 .Authorization(TAG_APPLICATION_DATA, "appdata")
2703 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002704
2705 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2706
Selene Huang31ab4042020-04-29 04:22:39 -07002707 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2708 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2709 AbortIfNeeded();
2710 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2711 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2712 .Digest(Digest::NONE)
2713 .Authorization(TAG_APPLICATION_ID, "clientid")));
2714 AbortIfNeeded();
2715 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2716 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2717 .Digest(Digest::NONE)
2718 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2719 AbortIfNeeded();
2720 EXPECT_EQ(ErrorCode::OK,
2721 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2722 .Digest(Digest::NONE)
2723 .Authorization(TAG_APPLICATION_DATA, "appdata")
2724 .Authorization(TAG_APPLICATION_ID, "clientid")));
2725 AbortIfNeeded();
2726}
2727
2728/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002729 * SigningOperationsTest.EcdsaIncompatibleDigest
2730 *
2731 * Verifies that using an EC key requires compatible digest.
2732 */
2733TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2735 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002736 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002737 .Digest(Digest::NONE)
2738 .Digest(Digest::SHA1)
2739 .SetDefaultValidity()));
2740 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2741 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2742 AbortIfNeeded();
2743}
2744
2745/*
Selene Huang31ab4042020-04-29 04:22:39 -07002746 * SigningOperationsTest.AesEcbSign
2747 *
2748 * Verifies that attempts to use AES keys to sign fail in the correct way.
2749 */
2750TEST_P(SigningOperationsTest, AesEcbSign) {
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .SigningKey()
2754 .AesEncryptionKey(128)
2755 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2756
2757 AuthorizationSet out_params;
2758 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2759 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2760 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2761 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2762}
2763
2764/*
2765 * SigningOperationsTest.HmacAllDigests
2766 *
2767 * Verifies that HMAC works with all digests.
2768 */
2769TEST_P(SigningOperationsTest, HmacAllDigests) {
2770 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2772 .Authorization(TAG_NO_AUTH_REQUIRED)
2773 .HmacKey(128)
2774 .Digest(digest)
2775 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2776 << "Failed to create HMAC key with digest " << digest;
2777 string message = "12345678901234567890123456789012";
2778 string signature = MacMessage(message, digest, 160);
2779 EXPECT_EQ(160U / 8U, signature.size())
2780 << "Failed to sign with HMAC key with digest " << digest;
2781 CheckedDeleteKey();
2782 }
2783}
2784
2785/*
2786 * SigningOperationsTest.HmacSha256TooLargeMacLength
2787 *
2788 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2789 * digest size.
2790 */
2791TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2792 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2793 .Authorization(TAG_NO_AUTH_REQUIRED)
2794 .HmacKey(128)
2795 .Digest(Digest::SHA_2_256)
2796 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2797 AuthorizationSet output_params;
2798 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2799 AuthorizationSetBuilder()
2800 .Digest(Digest::SHA_2_256)
2801 .Authorization(TAG_MAC_LENGTH, 264),
2802 &output_params));
2803}
2804
2805/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002806 * SigningOperationsTest.HmacSha256InvalidMacLength
2807 *
2808 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2809 * not a multiple of 8.
2810 */
2811TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2813 .Authorization(TAG_NO_AUTH_REQUIRED)
2814 .HmacKey(128)
2815 .Digest(Digest::SHA_2_256)
2816 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2817 AuthorizationSet output_params;
2818 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2819 AuthorizationSetBuilder()
2820 .Digest(Digest::SHA_2_256)
2821 .Authorization(TAG_MAC_LENGTH, 161),
2822 &output_params));
2823}
2824
2825/*
Selene Huang31ab4042020-04-29 04:22:39 -07002826 * SigningOperationsTest.HmacSha256TooSmallMacLength
2827 *
2828 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2829 * specified minimum MAC length.
2830 */
2831TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2832 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2833 .Authorization(TAG_NO_AUTH_REQUIRED)
2834 .HmacKey(128)
2835 .Digest(Digest::SHA_2_256)
2836 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2837 AuthorizationSet output_params;
2838 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2839 AuthorizationSetBuilder()
2840 .Digest(Digest::SHA_2_256)
2841 .Authorization(TAG_MAC_LENGTH, 120),
2842 &output_params));
2843}
2844
2845/*
2846 * SigningOperationsTest.HmacRfc4231TestCase3
2847 *
2848 * Validates against the test vectors from RFC 4231 test case 3.
2849 */
2850TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2851 string key(20, 0xaa);
2852 string message(50, 0xdd);
2853 uint8_t sha_224_expected[] = {
2854 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2855 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2856 };
2857 uint8_t sha_256_expected[] = {
2858 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2859 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2860 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2861 };
2862 uint8_t sha_384_expected[] = {
2863 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2864 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2865 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2866 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2867 };
2868 uint8_t sha_512_expected[] = {
2869 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2870 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2871 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2872 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2873 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2874 };
2875
2876 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2877 if (SecLevel() != SecurityLevel::STRONGBOX) {
2878 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2879 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2880 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2881 }
2882}
2883
2884/*
2885 * SigningOperationsTest.HmacRfc4231TestCase5
2886 *
2887 * Validates against the test vectors from RFC 4231 test case 5.
2888 */
2889TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2890 string key(20, 0x0c);
2891 string message = "Test With Truncation";
2892
2893 uint8_t sha_224_expected[] = {
2894 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2895 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2896 };
2897 uint8_t sha_256_expected[] = {
2898 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2899 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2900 };
2901 uint8_t sha_384_expected[] = {
2902 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2903 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2904 };
2905 uint8_t sha_512_expected[] = {
2906 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2907 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2908 };
2909
2910 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2911 if (SecLevel() != SecurityLevel::STRONGBOX) {
2912 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2913 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2914 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2915 }
2916}
2917
2918INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2919
2920typedef KeyMintAidlTestBase VerificationOperationsTest;
2921
2922/*
Selene Huang31ab4042020-04-29 04:22:39 -07002923 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2924 *
2925 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2926 */
2927TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2928 string key_material = "HelloThisIsAKey";
2929
2930 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002931 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002932 EXPECT_EQ(ErrorCode::OK,
2933 ImportKey(AuthorizationSetBuilder()
2934 .Authorization(TAG_NO_AUTH_REQUIRED)
2935 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2936 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2937 .Digest(Digest::SHA_2_256)
2938 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2939 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2940 EXPECT_EQ(ErrorCode::OK,
2941 ImportKey(AuthorizationSetBuilder()
2942 .Authorization(TAG_NO_AUTH_REQUIRED)
2943 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2944 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2945 .Digest(Digest::SHA_2_256)
2946 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2947 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2948
2949 string message = "This is a message.";
2950 string signature = SignMessage(
2951 signing_key, message,
2952 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2953
2954 // Signing key should not work.
2955 AuthorizationSet out_params;
2956 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2957 Begin(KeyPurpose::VERIFY, signing_key,
2958 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2959
2960 // Verification key should work.
2961 VerifyMessage(verification_key, message, signature,
2962 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2963
2964 CheckedDeleteKey(&signing_key);
2965 CheckedDeleteKey(&verification_key);
2966}
2967
2968INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2969
2970typedef KeyMintAidlTestBase ExportKeyTest;
2971
2972/*
2973 * ExportKeyTest.RsaUnsupportedKeyFormat
2974 *
2975 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2976 */
2977// TODO(seleneh) add ExportKey to GenerateKey
2978// check result
2979
2980class ImportKeyTest : public KeyMintAidlTestBase {
2981 public:
2982 template <TagType tag_type, Tag tag, typename ValueT>
2983 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2984 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002985 for (auto& entry : key_characteristics_) {
2986 if (entry.securityLevel == SecLevel()) {
2987 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2988 << "Tag " << tag << " with value " << expected
2989 << " not found at security level" << entry.securityLevel;
2990 } else {
2991 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2992 << "Tag " << tag << " found at security level " << entry.securityLevel;
2993 }
Selene Huang31ab4042020-04-29 04:22:39 -07002994 }
2995 }
2996
2997 void CheckOrigin() {
2998 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002999 // Origin isn't a crypto param, but it always lives with them.
3000 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003001 }
3002};
3003
3004/*
3005 * ImportKeyTest.RsaSuccess
3006 *
3007 * Verifies that importing and using an RSA key pair works correctly.
3008 */
3009TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003010 uint32_t key_size;
3011 string key;
3012
3013 if (SecLevel() == SecurityLevel::STRONGBOX) {
3014 key_size = 2048;
3015 key = rsa_2048_key;
3016 } else {
3017 key_size = 1024;
3018 key = rsa_key;
3019 }
3020
Selene Huang31ab4042020-04-29 04:22:39 -07003021 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3022 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003023 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003024 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003025 .Padding(PaddingMode::RSA_PSS)
3026 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003027 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003028
3029 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003030 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003031 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3032 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3033 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3034 CheckOrigin();
3035
3036 string message(1024 / 8, 'a');
3037 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3038 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003039 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003040}
3041
3042/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003043 * ImportKeyTest.RsaSuccessWithoutParams
3044 *
3045 * Verifies that importing and using an RSA key pair without specifying parameters
3046 * works correctly.
3047 */
3048TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3049 uint32_t key_size;
3050 string key;
3051
3052 if (SecLevel() == SecurityLevel::STRONGBOX) {
3053 key_size = 2048;
3054 key = rsa_2048_key;
3055 } else {
3056 key_size = 1024;
3057 key = rsa_key;
3058 }
3059
3060 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3061 .Authorization(TAG_NO_AUTH_REQUIRED)
3062 .SigningKey()
3063 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3064 .Digest(Digest::SHA_2_256)
3065 .Padding(PaddingMode::RSA_PSS)
3066 .SetDefaultValidity(),
3067 KeyFormat::PKCS8, key));
3068
3069 // Key size and public exponent are determined from the imported key material.
3070 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3071 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3072
3073 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3074 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3075 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3076 CheckOrigin();
3077
3078 string message(1024 / 8, 'a');
3079 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3080 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003081 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003082}
3083
3084/*
Selene Huang31ab4042020-04-29 04:22:39 -07003085 * ImportKeyTest.RsaKeySizeMismatch
3086 *
3087 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3088 * correct way.
3089 */
3090TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3091 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3092 ImportKey(AuthorizationSetBuilder()
3093 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3094 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003095 .Padding(PaddingMode::NONE)
3096 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003097 KeyFormat::PKCS8, rsa_key));
3098}
3099
3100/*
3101 * ImportKeyTest.RsaPublicExponentMismatch
3102 *
3103 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3104 * fails in the correct way.
3105 */
3106TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3107 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3108 ImportKey(AuthorizationSetBuilder()
3109 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3110 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003111 .Padding(PaddingMode::NONE)
3112 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003113 KeyFormat::PKCS8, rsa_key));
3114}
3115
3116/*
3117 * ImportKeyTest.EcdsaSuccess
3118 *
3119 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3120 */
3121TEST_P(ImportKeyTest, EcdsaSuccess) {
3122 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3123 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003124 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003125 .Digest(Digest::SHA_2_256)
3126 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003127 KeyFormat::PKCS8, ec_256_key));
3128
3129 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003130 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3131 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3132
3133 CheckOrigin();
3134
3135 string message(32, 'a');
3136 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3137 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003138 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003139}
3140
3141/*
3142 * ImportKeyTest.EcdsaP256RFC5915Success
3143 *
3144 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3145 * correctly.
3146 */
3147TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3148 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3149 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003150 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003151 .Digest(Digest::SHA_2_256)
3152 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003153 KeyFormat::PKCS8, ec_256_key_rfc5915));
3154
3155 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003156 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3157 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3158
3159 CheckOrigin();
3160
3161 string message(32, 'a');
3162 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3163 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003164 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003165}
3166
3167/*
3168 * ImportKeyTest.EcdsaP256SEC1Success
3169 *
3170 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3171 */
3172TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3173 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3174 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003175 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003176 .Digest(Digest::SHA_2_256)
3177 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003178 KeyFormat::PKCS8, ec_256_key_sec1));
3179
3180 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003181 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3182 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3183
3184 CheckOrigin();
3185
3186 string message(32, 'a');
3187 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3188 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003189 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003190}
3191
3192/*
3193 * ImportKeyTest.Ecdsa521Success
3194 *
3195 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3196 */
3197TEST_P(ImportKeyTest, Ecdsa521Success) {
3198 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3199 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3200 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003201 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003202 .Digest(Digest::SHA_2_256)
3203 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003204 KeyFormat::PKCS8, ec_521_key));
3205
3206 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003207 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3208 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3209 CheckOrigin();
3210
3211 string message(32, 'a');
3212 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3213 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003214 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003215}
3216
3217/*
Selene Huang31ab4042020-04-29 04:22:39 -07003218 * ImportKeyTest.EcdsaCurveMismatch
3219 *
3220 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3221 * the correct way.
3222 */
3223TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3224 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3225 ImportKey(AuthorizationSetBuilder()
3226 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003227 .Digest(Digest::NONE)
3228 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003229 KeyFormat::PKCS8, ec_256_key));
3230}
3231
3232/*
3233 * ImportKeyTest.AesSuccess
3234 *
3235 * Verifies that importing and using an AES key works.
3236 */
3237TEST_P(ImportKeyTest, AesSuccess) {
3238 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3239 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3240 .Authorization(TAG_NO_AUTH_REQUIRED)
3241 .AesEncryptionKey(key.size() * 8)
3242 .EcbMode()
3243 .Padding(PaddingMode::PKCS7),
3244 KeyFormat::RAW, key));
3245
3246 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3247 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3248 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3249 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3250 CheckOrigin();
3251
3252 string message = "Hello World!";
3253 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3254 string ciphertext = EncryptMessage(message, params);
3255 string plaintext = DecryptMessage(ciphertext, params);
3256 EXPECT_EQ(message, plaintext);
3257}
3258
3259/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003260 * ImportKeyTest.AesFailure
3261 *
3262 * Verifies that importing an invalid AES key fails.
3263 */
3264TEST_P(ImportKeyTest, AesFailure) {
3265 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3266 uint32_t bitlen = key.size() * 8;
3267 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003268 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003269 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003270 .Authorization(TAG_NO_AUTH_REQUIRED)
3271 .AesEncryptionKey(key_size)
3272 .EcbMode()
3273 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003274 KeyFormat::RAW, key);
3275 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003276 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3277 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003278 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003279
3280 // Explicit key size matches that of the provided key, but it's not a valid size.
3281 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3282 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3283 ImportKey(AuthorizationSetBuilder()
3284 .Authorization(TAG_NO_AUTH_REQUIRED)
3285 .AesEncryptionKey(long_key.size() * 8)
3286 .EcbMode()
3287 .Padding(PaddingMode::PKCS7),
3288 KeyFormat::RAW, long_key));
3289 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3290 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3291 ImportKey(AuthorizationSetBuilder()
3292 .Authorization(TAG_NO_AUTH_REQUIRED)
3293 .AesEncryptionKey(short_key.size() * 8)
3294 .EcbMode()
3295 .Padding(PaddingMode::PKCS7),
3296 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003297}
3298
3299/*
3300 * ImportKeyTest.TripleDesSuccess
3301 *
3302 * Verifies that importing and using a 3DES key works.
3303 */
3304TEST_P(ImportKeyTest, TripleDesSuccess) {
3305 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3306 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3307 .Authorization(TAG_NO_AUTH_REQUIRED)
3308 .TripleDesEncryptionKey(168)
3309 .EcbMode()
3310 .Padding(PaddingMode::PKCS7),
3311 KeyFormat::RAW, key));
3312
3313 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3314 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3315 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3316 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3317 CheckOrigin();
3318
3319 string message = "Hello World!";
3320 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3321 string ciphertext = EncryptMessage(message, params);
3322 string plaintext = DecryptMessage(ciphertext, params);
3323 EXPECT_EQ(message, plaintext);
3324}
3325
3326/*
3327 * ImportKeyTest.TripleDesFailure
3328 *
3329 * Verifies that importing an invalid 3DES key fails.
3330 */
3331TEST_P(ImportKeyTest, TripleDesFailure) {
3332 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003333 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003334 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003335 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003336 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003337 .Authorization(TAG_NO_AUTH_REQUIRED)
3338 .TripleDesEncryptionKey(key_size)
3339 .EcbMode()
3340 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003341 KeyFormat::RAW, key);
3342 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003343 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3344 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003345 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003346 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003347 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003348 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3349 ImportKey(AuthorizationSetBuilder()
3350 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003351 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003352 .EcbMode()
3353 .Padding(PaddingMode::PKCS7),
3354 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003355 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003356 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3357 ImportKey(AuthorizationSetBuilder()
3358 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003359 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003360 .EcbMode()
3361 .Padding(PaddingMode::PKCS7),
3362 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003363}
3364
3365/*
3366 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003367 *
3368 * Verifies that importing and using an HMAC key works.
3369 */
3370TEST_P(ImportKeyTest, HmacKeySuccess) {
3371 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3372 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3373 .Authorization(TAG_NO_AUTH_REQUIRED)
3374 .HmacKey(key.size() * 8)
3375 .Digest(Digest::SHA_2_256)
3376 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3377 KeyFormat::RAW, key));
3378
3379 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3380 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3381 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3382 CheckOrigin();
3383
3384 string message = "Hello World!";
3385 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3386 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3387}
3388
3389INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3390
3391auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003392 // IKeyMintDevice.aidl
3393 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3394 "020100" // INTEGER length 1 value 0x00 (version)
3395 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3396 "934bf94e2aa28a3f83c9f79297250262"
3397 "fbe3276b5a1c91159bbfa3ef8957aac8"
3398 "4b59b30b455a79c2973480823d8b3863"
3399 "c3deef4a8e243590268d80e18751a0e1"
3400 "30f67ce6a1ace9f79b95e097474febc9"
3401 "81195b1d13a69086c0863f66a7b7fdb4"
3402 "8792227b1ac5e2489febdf087ab54864"
3403 "83033a6f001ca5d1ec1e27f5c30f4cec"
3404 "2642074a39ae68aee552e196627a8e3d"
3405 "867e67a8c01b11e75f13cca0a97ab668"
3406 "b50cda07a8ecb7cd8e3dd7009c963653"
3407 "4f6f239cffe1fc8daa466f78b676c711"
3408 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3409 "99b801597d5220e307eaa5bee507fb94"
3410 "d1fa69f9e519b2de315bac92c36f2ea1"
3411 "fa1df4478c0ddedeae8c70e0233cd098"
3412 "040c" // OCTET STRING length 0x0c (initializationVector)
3413 "d796b02c370f1fa4cc0124f1"
3414 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3415 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3416 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3417 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3418 "3106" // SET length 0x06
3419 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3420 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3421 // } end SET
3422 // } end [1]
3423 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3424 "020120" // INTEGER length 1 value 0x20 (AES)
3425 // } end [2]
3426 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3427 "02020100" // INTEGER length 2 value 0x100
3428 // } end [3]
3429 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3430 "3103" // SET length 0x03 {
3431 "020101" // INTEGER length 1 value 0x01 (ECB)
3432 // } end SET
3433 // } end [4]
3434 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3435 "3103" // SET length 0x03 {
3436 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3437 // } end SET
3438 // } end [5]
3439 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3440 // (noAuthRequired)
3441 "0500" // NULL
3442 // } end [503]
3443 // } end SEQUENCE (AuthorizationList)
3444 // } end SEQUENCE (KeyDescription)
3445 "0420" // OCTET STRING length 0x20 (encryptedKey)
3446 "ccd540855f833a5e1480bfd2d36faf3a"
3447 "eee15df5beabe2691bc82dde2a7aa910"
3448 "0410" // OCTET STRING length 0x10 (tag)
3449 "64c9f689c60ff6223ab6e6999e0eb6e5"
3450 // } SEQUENCE (SecureKeyWrapper)
3451);
Selene Huang31ab4042020-04-29 04:22:39 -07003452
3453auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003454 // IKeyMintDevice.aidl
3455 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3456 "020100" // INTEGER length 1 value 0x00 (version)
3457 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3458 "aad93ed5924f283b4bb5526fbe7a1412"
3459 "f9d9749ec30db9062b29e574a8546f33"
3460 "c88732452f5b8e6a391ee76c39ed1712"
3461 "c61d8df6213dec1cffbc17a8c6d04c7b"
3462 "30893d8daa9b2015213e219468215532"
3463 "07f8f9931c4caba23ed3bee28b36947e"
3464 "47f10e0a5c3dc51c988a628daad3e5e1"
3465 "f4005e79c2d5a96c284b4b8d7e4948f3"
3466 "31e5b85dd5a236f85579f3ea1d1b8484"
3467 "87470bdb0ab4f81a12bee42c99fe0df4"
3468 "bee3759453e69ad1d68a809ce06b949f"
3469 "7694a990429b2fe81e066ff43e56a216"
3470 "02db70757922a4bcc23ab89f1e35da77"
3471 "586775f423e519c2ea394caf48a28d0c"
3472 "8020f1dcf6b3a68ec246f615ae96dae9"
3473 "a079b1f6eb959033c1af5c125fd94168"
3474 "040c" // OCTET STRING length 0x0c (initializationVector)
3475 "6d9721d08589581ab49204a3"
3476 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3477 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3478 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3479 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3480 "3106" // SET length 0x06
3481 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3482 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3483 // } end SET
3484 // } end [1]
3485 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3486 "020120" // INTEGER length 1 value 0x20 (AES)
3487 // } end [2]
3488 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3489 "02020100" // INTEGER length 2 value 0x100
3490 // } end [3]
3491 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3492 "3103" // SET length 0x03 {
3493 "020101" // INTEGER length 1 value 0x01 (ECB)
3494 // } end SET
3495 // } end [4]
3496 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3497 "3103" // SET length 0x03 {
3498 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3499 // } end SET
3500 // } end [5]
3501 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3502 // (noAuthRequired)
3503 "0500" // NULL
3504 // } end [503]
3505 // } end SEQUENCE (AuthorizationList)
3506 // } end SEQUENCE (KeyDescription)
3507 "0420" // OCTET STRING length 0x20 (encryptedKey)
3508 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3509 "c20d1f99a9a024a76f35c8e2cab9b68d"
3510 "0410" // OCTET STRING length 0x10 (tag)
3511 "2560c70109ae67c030f00b98b512a670"
3512 // } SEQUENCE (SecureKeyWrapper)
3513);
Selene Huang31ab4042020-04-29 04:22:39 -07003514
3515auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003516 // RFC 5208 s5
3517 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3518 "020100" // INTEGER length 1 value 0x00 (version)
3519 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3520 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3521 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3522 "0500" // NULL (parameters)
3523 // } SEQUENCE (AlgorithmIdentifier)
3524 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3525 // RFC 8017 A.1.2
3526 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3527 "020100" // INTEGER length 1 value 0x00 (version)
3528 "02820101" // INTEGER length 0x0101 (modulus) value...
3529 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3530 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3531 "7b06e673a837313d56b1c725150a3fef" // 0x30
3532 "86acbddc41bb759c2854eae32d35841e" // 0x40
3533 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3534 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3535 "312d7bd5921ffaea1347c157406fef71" // 0x70
3536 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3537 "f4645c11f5c1374c3886427411c44979" // 0x90
3538 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3539 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3540 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3541 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3542 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3543 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3544 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3545 "55" // 0x101
3546 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3547 "02820100" // INTEGER length 0x100 (privateExponent) value...
3548 "431447b6251908112b1ee76f99f3711a" // 0x10
3549 "52b6630960046c2de70de188d833f8b8" // 0x20
3550 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3551 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3552 "e710b630a03adc683b5d2c43080e52be" // 0x50
3553 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3554 "822bccff087d63c940ba8a45f670feb2" // 0x70
3555 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3556 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3557 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3558 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3559 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3560 "52659d5a5ba05b663737a8696281865b" // 0xd0
3561 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3562 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3563 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3564 "028181" // INTEGER length 0x81 (prime1) value...
3565 "00de392e18d682c829266cc3454e1d61" // 0x10
3566 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3567 "ff841be5bac82a164c5970007047b8c5" // 0x30
3568 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3569 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3570 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3571 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3572 "9e91346130748a6e3c124f9149d71c74" // 0x80
3573 "35"
3574 "028181" // INTEGER length 0x81 (prime2) value...
3575 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3576 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3577 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3578 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3579 "9ed39a2d934c880440aed8832f984316" // 0x50
3580 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3581 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3582 "b880677c068e1be936e81288815252a8" // 0x80
3583 "a1"
3584 "028180" // INTEGER length 0x80 (exponent1) value...
3585 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3586 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3587 "5a063212a4f105a3764743e53281988a" // 0x30
3588 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3589 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3590 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3591 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3592 "4719d6e2b9439823719cd08bcd031781" // 0x80
3593 "028181" // INTEGER length 0x81 (exponent2) value...
3594 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3595 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3596 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3597 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3598 "1254186af30b22c10582a8a43e34fe94" // 0x50
3599 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3600 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3601 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3602 "61"
3603 "028181" // INTEGER length 0x81 (coefficient) value...
3604 "00c931617c77829dfb1270502be9195c" // 0x10
3605 "8f2830885f57dba869536811e6864236" // 0x20
3606 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3607 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3608 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3609 "959356210723287b0affcc9f727044d4" // 0x60
3610 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3611 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3612 "22"
3613 // } SEQUENCE
3614 // } SEQUENCE ()
3615);
Selene Huang31ab4042020-04-29 04:22:39 -07003616
3617string zero_masking_key =
3618 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3619string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3620
3621class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3622
3623TEST_P(ImportWrappedKeyTest, Success) {
3624 auto wrapping_key_desc = AuthorizationSetBuilder()
3625 .RsaEncryptionKey(2048, 65537)
3626 .Digest(Digest::SHA_2_256)
3627 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003628 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3629 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003630
3631 ASSERT_EQ(ErrorCode::OK,
3632 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3633 AuthorizationSetBuilder()
3634 .Digest(Digest::SHA_2_256)
3635 .Padding(PaddingMode::RSA_OAEP)));
3636
3637 string message = "Hello World!";
3638 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3639 string ciphertext = EncryptMessage(message, params);
3640 string plaintext = DecryptMessage(ciphertext, params);
3641 EXPECT_EQ(message, plaintext);
3642}
3643
David Drysdaled2cc8c22021-04-15 13:29:45 +01003644/*
3645 * ImportWrappedKeyTest.SuccessSidsIgnored
3646 *
3647 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3648 * include Tag:USER_SECURE_ID.
3649 */
3650TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3651 auto wrapping_key_desc = AuthorizationSetBuilder()
3652 .RsaEncryptionKey(2048, 65537)
3653 .Digest(Digest::SHA_2_256)
3654 .Padding(PaddingMode::RSA_OAEP)
3655 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3656 .SetDefaultValidity();
3657
3658 int64_t password_sid = 42;
3659 int64_t biometric_sid = 24;
3660 ASSERT_EQ(ErrorCode::OK,
3661 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3662 AuthorizationSetBuilder()
3663 .Digest(Digest::SHA_2_256)
3664 .Padding(PaddingMode::RSA_OAEP),
3665 password_sid, biometric_sid));
3666
3667 string message = "Hello World!";
3668 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3669 string ciphertext = EncryptMessage(message, params);
3670 string plaintext = DecryptMessage(ciphertext, params);
3671 EXPECT_EQ(message, plaintext);
3672}
3673
Selene Huang31ab4042020-04-29 04:22:39 -07003674TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3675 auto wrapping_key_desc = AuthorizationSetBuilder()
3676 .RsaEncryptionKey(2048, 65537)
3677 .Digest(Digest::SHA_2_256)
3678 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003679 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3680 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003681
3682 ASSERT_EQ(ErrorCode::OK,
3683 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3684 AuthorizationSetBuilder()
3685 .Digest(Digest::SHA_2_256)
3686 .Padding(PaddingMode::RSA_OAEP)));
3687}
3688
3689TEST_P(ImportWrappedKeyTest, WrongMask) {
3690 auto wrapping_key_desc = AuthorizationSetBuilder()
3691 .RsaEncryptionKey(2048, 65537)
3692 .Digest(Digest::SHA_2_256)
3693 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003694 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3695 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003696
3697 ASSERT_EQ(
3698 ErrorCode::VERIFICATION_FAILED,
3699 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3700 AuthorizationSetBuilder()
3701 .Digest(Digest::SHA_2_256)
3702 .Padding(PaddingMode::RSA_OAEP)));
3703}
3704
3705TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3706 auto wrapping_key_desc = AuthorizationSetBuilder()
3707 .RsaEncryptionKey(2048, 65537)
3708 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003709 .Padding(PaddingMode::RSA_OAEP)
3710 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003711
3712 ASSERT_EQ(
3713 ErrorCode::INCOMPATIBLE_PURPOSE,
3714 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3715 AuthorizationSetBuilder()
3716 .Digest(Digest::SHA_2_256)
3717 .Padding(PaddingMode::RSA_OAEP)));
3718}
3719
David Drysdaled2cc8c22021-04-15 13:29:45 +01003720TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3721 auto wrapping_key_desc = AuthorizationSetBuilder()
3722 .RsaEncryptionKey(2048, 65537)
3723 .Digest(Digest::SHA_2_256)
3724 .Padding(PaddingMode::RSA_PSS)
3725 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3726 .SetDefaultValidity();
3727
3728 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3729 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3730 AuthorizationSetBuilder()
3731 .Digest(Digest::SHA_2_256)
3732 .Padding(PaddingMode::RSA_OAEP)));
3733}
3734
3735TEST_P(ImportWrappedKeyTest, WrongDigest) {
3736 auto wrapping_key_desc = AuthorizationSetBuilder()
3737 .RsaEncryptionKey(2048, 65537)
3738 .Digest(Digest::SHA_2_512)
3739 .Padding(PaddingMode::RSA_OAEP)
3740 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3741 .SetDefaultValidity();
3742
3743 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3744 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3745 AuthorizationSetBuilder()
3746 .Digest(Digest::SHA_2_256)
3747 .Padding(PaddingMode::RSA_OAEP)));
3748}
3749
Selene Huang31ab4042020-04-29 04:22:39 -07003750INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3751
3752typedef KeyMintAidlTestBase EncryptionOperationsTest;
3753
3754/*
3755 * EncryptionOperationsTest.RsaNoPaddingSuccess
3756 *
David Drysdale59cae642021-05-12 13:52:03 +01003757 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003758 */
3759TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003760 for (uint64_t exponent : {3, 65537}) {
3761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3762 .Authorization(TAG_NO_AUTH_REQUIRED)
3763 .RsaEncryptionKey(2048, exponent)
3764 .Padding(PaddingMode::NONE)
3765 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003766
David Drysdaled2cc8c22021-04-15 13:29:45 +01003767 string message = string(2048 / 8, 'a');
3768 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003769 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003770 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003771
David Drysdale59cae642021-05-12 13:52:03 +01003772 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003773 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003774
David Drysdaled2cc8c22021-04-15 13:29:45 +01003775 // Unpadded RSA is deterministic
3776 EXPECT_EQ(ciphertext1, ciphertext2);
3777
3778 CheckedDeleteKey();
3779 }
Selene Huang31ab4042020-04-29 04:22:39 -07003780}
3781
3782/*
3783 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3784 *
David Drysdale59cae642021-05-12 13:52:03 +01003785 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003786 */
3787TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3789 .Authorization(TAG_NO_AUTH_REQUIRED)
3790 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003791 .Padding(PaddingMode::NONE)
3792 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003793
3794 string message = "1";
3795 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3796
David Drysdale59cae642021-05-12 13:52:03 +01003797 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003798 EXPECT_EQ(2048U / 8, ciphertext.size());
3799
3800 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3801 string plaintext = DecryptMessage(ciphertext, params);
3802
3803 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003804}
3805
3806/*
Selene Huang31ab4042020-04-29 04:22:39 -07003807 * EncryptionOperationsTest.RsaOaepSuccess
3808 *
David Drysdale59cae642021-05-12 13:52:03 +01003809 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003810 */
3811TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3812 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3813
3814 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003815 ASSERT_EQ(ErrorCode::OK,
3816 GenerateKey(AuthorizationSetBuilder()
3817 .Authorization(TAG_NO_AUTH_REQUIRED)
3818 .RsaEncryptionKey(key_size, 65537)
3819 .Padding(PaddingMode::RSA_OAEP)
3820 .Digest(digests)
3821 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3822 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003823
3824 string message = "Hello";
3825
3826 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003827 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3828
3829 auto params = AuthorizationSetBuilder()
3830 .Digest(digest)
3831 .Padding(PaddingMode::RSA_OAEP)
3832 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3833 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003834 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3835 EXPECT_EQ(key_size / 8, ciphertext1.size());
3836
David Drysdale59cae642021-05-12 13:52:03 +01003837 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003838 EXPECT_EQ(key_size / 8, ciphertext2.size());
3839
3840 // OAEP randomizes padding so every result should be different (with astronomically high
3841 // probability).
3842 EXPECT_NE(ciphertext1, ciphertext2);
3843
3844 string plaintext1 = DecryptMessage(ciphertext1, params);
3845 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3846 string plaintext2 = DecryptMessage(ciphertext2, params);
3847 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3848
3849 // Decrypting corrupted ciphertext should fail.
3850 size_t offset_to_corrupt = random() % ciphertext1.size();
3851 char corrupt_byte;
3852 do {
3853 corrupt_byte = static_cast<char>(random() % 256);
3854 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3855 ciphertext1[offset_to_corrupt] = corrupt_byte;
3856
3857 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3858 string result;
3859 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3860 EXPECT_EQ(0U, result.size());
3861 }
3862}
3863
3864/*
3865 * EncryptionOperationsTest.RsaOaepInvalidDigest
3866 *
David Drysdale59cae642021-05-12 13:52:03 +01003867 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003868 * without a digest.
3869 */
3870TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3872 .Authorization(TAG_NO_AUTH_REQUIRED)
3873 .RsaEncryptionKey(2048, 65537)
3874 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003875 .Digest(Digest::NONE)
3876 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003877
3878 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003879 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003880}
3881
3882/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003883 * EncryptionOperationsTest.RsaOaepInvalidPadding
3884 *
David Drysdale59cae642021-05-12 13:52:03 +01003885 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003886 * with a padding value that is only suitable for signing/verifying.
3887 */
3888TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3890 .Authorization(TAG_NO_AUTH_REQUIRED)
3891 .RsaEncryptionKey(2048, 65537)
3892 .Padding(PaddingMode::RSA_PSS)
3893 .Digest(Digest::NONE)
3894 .SetDefaultValidity()));
3895
3896 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003897 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003898}
3899
3900/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003901 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003902 *
David Drysdale59cae642021-05-12 13:52:03 +01003903 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003904 * with a different digest than was used to encrypt.
3905 */
3906TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3907 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3908
3909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3910 .Authorization(TAG_NO_AUTH_REQUIRED)
3911 .RsaEncryptionKey(1024, 65537)
3912 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003913 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3914 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003915 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003916 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003917 message,
3918 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3919
3920 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3921 .Digest(Digest::SHA_2_256)
3922 .Padding(PaddingMode::RSA_OAEP)));
3923 string result;
3924 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3925 EXPECT_EQ(0U, result.size());
3926}
3927
3928/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003929 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3930 *
David Drysdale59cae642021-05-12 13:52:03 +01003931 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003932 * digests.
3933 */
3934TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3935 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3936
3937 size_t key_size = 2048; // Need largish key for SHA-512 test.
3938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3939 .OaepMGFDigest(digests)
3940 .Authorization(TAG_NO_AUTH_REQUIRED)
3941 .RsaEncryptionKey(key_size, 65537)
3942 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003943 .Digest(Digest::SHA_2_256)
3944 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003945
3946 string message = "Hello";
3947
3948 for (auto digest : digests) {
3949 auto params = AuthorizationSetBuilder()
3950 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3951 .Digest(Digest::SHA_2_256)
3952 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003953 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003954 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3955 EXPECT_EQ(key_size / 8, ciphertext1.size());
3956
David Drysdale59cae642021-05-12 13:52:03 +01003957 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003958 EXPECT_EQ(key_size / 8, ciphertext2.size());
3959
3960 // OAEP randomizes padding so every result should be different (with astronomically high
3961 // probability).
3962 EXPECT_NE(ciphertext1, ciphertext2);
3963
3964 string plaintext1 = DecryptMessage(ciphertext1, params);
3965 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3966 string plaintext2 = DecryptMessage(ciphertext2, params);
3967 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3968
3969 // Decrypting corrupted ciphertext should fail.
3970 size_t offset_to_corrupt = random() % ciphertext1.size();
3971 char corrupt_byte;
3972 do {
3973 corrupt_byte = static_cast<char>(random() % 256);
3974 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3975 ciphertext1[offset_to_corrupt] = corrupt_byte;
3976
3977 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3978 string result;
3979 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3980 EXPECT_EQ(0U, result.size());
3981 }
3982}
3983
3984/*
3985 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3986 *
David Drysdale59cae642021-05-12 13:52:03 +01003987 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003988 * with incompatible MGF digest.
3989 */
3990TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3991 ASSERT_EQ(ErrorCode::OK,
3992 GenerateKey(AuthorizationSetBuilder()
3993 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3994 .Authorization(TAG_NO_AUTH_REQUIRED)
3995 .RsaEncryptionKey(2048, 65537)
3996 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003997 .Digest(Digest::SHA_2_256)
3998 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003999 string message = "Hello World!";
4000
4001 auto params = AuthorizationSetBuilder()
4002 .Padding(PaddingMode::RSA_OAEP)
4003 .Digest(Digest::SHA_2_256)
4004 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004005 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004006}
4007
4008/*
4009 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4010 *
4011 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4012 * with unsupported MGF digest.
4013 */
4014TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4015 ASSERT_EQ(ErrorCode::OK,
4016 GenerateKey(AuthorizationSetBuilder()
4017 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4018 .Authorization(TAG_NO_AUTH_REQUIRED)
4019 .RsaEncryptionKey(2048, 65537)
4020 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004021 .Digest(Digest::SHA_2_256)
4022 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004023 string message = "Hello World!";
4024
4025 auto params = AuthorizationSetBuilder()
4026 .Padding(PaddingMode::RSA_OAEP)
4027 .Digest(Digest::SHA_2_256)
4028 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004029 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004030}
4031
4032/*
Selene Huang31ab4042020-04-29 04:22:39 -07004033 * EncryptionOperationsTest.RsaPkcs1Success
4034 *
4035 * Verifies that RSA PKCS encryption/decrypts works.
4036 */
4037TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4038 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4039 .Authorization(TAG_NO_AUTH_REQUIRED)
4040 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004041 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4042 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004043
4044 string message = "Hello World!";
4045 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004046 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004047 EXPECT_EQ(2048U / 8, ciphertext1.size());
4048
David Drysdale59cae642021-05-12 13:52:03 +01004049 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004050 EXPECT_EQ(2048U / 8, ciphertext2.size());
4051
4052 // PKCS1 v1.5 randomizes padding so every result should be different.
4053 EXPECT_NE(ciphertext1, ciphertext2);
4054
4055 string plaintext = DecryptMessage(ciphertext1, params);
4056 EXPECT_EQ(message, plaintext);
4057
4058 // Decrypting corrupted ciphertext should fail.
4059 size_t offset_to_corrupt = random() % ciphertext1.size();
4060 char corrupt_byte;
4061 do {
4062 corrupt_byte = static_cast<char>(random() % 256);
4063 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4064 ciphertext1[offset_to_corrupt] = corrupt_byte;
4065
4066 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4067 string result;
4068 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4069 EXPECT_EQ(0U, result.size());
4070}
4071
4072/*
Selene Huang31ab4042020-04-29 04:22:39 -07004073 * EncryptionOperationsTest.EcdsaEncrypt
4074 *
4075 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4076 */
4077TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4079 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004080 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004081 .Digest(Digest::NONE)
4082 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004083 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4084 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4085 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4086}
4087
4088/*
4089 * EncryptionOperationsTest.HmacEncrypt
4090 *
4091 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4092 */
4093TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4094 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4095 .Authorization(TAG_NO_AUTH_REQUIRED)
4096 .HmacKey(128)
4097 .Digest(Digest::SHA_2_256)
4098 .Padding(PaddingMode::NONE)
4099 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4100 auto params = AuthorizationSetBuilder()
4101 .Digest(Digest::SHA_2_256)
4102 .Padding(PaddingMode::NONE)
4103 .Authorization(TAG_MAC_LENGTH, 128);
4104 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4105 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4106}
4107
4108/*
4109 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4110 *
4111 * Verifies that AES ECB mode works.
4112 */
4113TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4115 .Authorization(TAG_NO_AUTH_REQUIRED)
4116 .AesEncryptionKey(128)
4117 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4118 .Padding(PaddingMode::NONE)));
4119
4120 ASSERT_GT(key_blob_.size(), 0U);
4121 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4122
4123 // Two-block message.
4124 string message = "12345678901234567890123456789012";
4125 string ciphertext1 = EncryptMessage(message, params);
4126 EXPECT_EQ(message.size(), ciphertext1.size());
4127
4128 string ciphertext2 = EncryptMessage(string(message), params);
4129 EXPECT_EQ(message.size(), ciphertext2.size());
4130
4131 // ECB is deterministic.
4132 EXPECT_EQ(ciphertext1, ciphertext2);
4133
4134 string plaintext = DecryptMessage(ciphertext1, params);
4135 EXPECT_EQ(message, plaintext);
4136}
4137
4138/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004139 * EncryptionOperationsTest.AesEcbUnknownTag
4140 *
4141 * Verifies that AES ECB operations ignore unknown tags.
4142 */
4143TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4144 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4145 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4146 KeyParameter unknown_param;
4147 unknown_param.tag = unknown_tag;
4148
4149 vector<KeyCharacteristics> key_characteristics;
4150 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4151 .Authorization(TAG_NO_AUTH_REQUIRED)
4152 .AesEncryptionKey(128)
4153 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4154 .Padding(PaddingMode::NONE)
4155 .Authorization(unknown_param),
4156 &key_blob_, &key_characteristics));
4157 ASSERT_GT(key_blob_.size(), 0U);
4158
4159 // Unknown tags should not be returned in key characteristics.
4160 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4161 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4162 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4163 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4164
4165 // Encrypt without mentioning the unknown parameter.
4166 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4167 string message = "12345678901234567890123456789012";
4168 string ciphertext = EncryptMessage(message, params);
4169 EXPECT_EQ(message.size(), ciphertext.size());
4170
4171 // Decrypt including the unknown parameter.
4172 auto decrypt_params = AuthorizationSetBuilder()
4173 .BlockMode(BlockMode::ECB)
4174 .Padding(PaddingMode::NONE)
4175 .Authorization(unknown_param);
4176 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4177 EXPECT_EQ(message, plaintext);
4178}
4179
4180/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004181 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004182 *
4183 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4184 */
4185TEST_P(EncryptionOperationsTest, AesWrongMode) {
4186 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4187 .Authorization(TAG_NO_AUTH_REQUIRED)
4188 .AesEncryptionKey(128)
4189 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4190 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004191 ASSERT_GT(key_blob_.size(), 0U);
4192
Selene Huang31ab4042020-04-29 04:22:39 -07004193 EXPECT_EQ(
4194 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4195 Begin(KeyPurpose::ENCRYPT,
4196 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4197}
4198
4199/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004200 * EncryptionOperationsTest.AesWrongPadding
4201 *
4202 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4203 */
4204TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4206 .Authorization(TAG_NO_AUTH_REQUIRED)
4207 .AesEncryptionKey(128)
4208 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4209 .Padding(PaddingMode::NONE)));
4210 ASSERT_GT(key_blob_.size(), 0U);
4211
4212 EXPECT_EQ(
4213 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4214 Begin(KeyPurpose::ENCRYPT,
4215 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4216}
4217
4218/*
4219 * EncryptionOperationsTest.AesInvalidParams
4220 *
4221 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4222 */
4223TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4225 .Authorization(TAG_NO_AUTH_REQUIRED)
4226 .AesEncryptionKey(128)
4227 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4228 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4229 .Padding(PaddingMode::NONE)
4230 .Padding(PaddingMode::PKCS7)));
4231 ASSERT_GT(key_blob_.size(), 0U);
4232
4233 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4234 .BlockMode(BlockMode::CBC)
4235 .BlockMode(BlockMode::ECB)
4236 .Padding(PaddingMode::NONE));
4237 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4238 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4239
4240 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4241 .BlockMode(BlockMode::ECB)
4242 .Padding(PaddingMode::NONE)
4243 .Padding(PaddingMode::PKCS7));
4244 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4245 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4246}
4247
4248/*
Selene Huang31ab4042020-04-29 04:22:39 -07004249 * EncryptionOperationsTest.AesWrongPurpose
4250 *
4251 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4252 * specified.
4253 */
4254TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4255 auto err = GenerateKey(AuthorizationSetBuilder()
4256 .Authorization(TAG_NO_AUTH_REQUIRED)
4257 .AesKey(128)
4258 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4259 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4260 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4261 .Padding(PaddingMode::NONE));
4262 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4263 ASSERT_GT(key_blob_.size(), 0U);
4264
4265 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4266 .BlockMode(BlockMode::GCM)
4267 .Padding(PaddingMode::NONE)
4268 .Authorization(TAG_MAC_LENGTH, 128));
4269 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4270
4271 CheckedDeleteKey();
4272
4273 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4274 .Authorization(TAG_NO_AUTH_REQUIRED)
4275 .AesKey(128)
4276 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4277 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4278 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4279 .Padding(PaddingMode::NONE)));
4280
4281 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4282 .BlockMode(BlockMode::GCM)
4283 .Padding(PaddingMode::NONE)
4284 .Authorization(TAG_MAC_LENGTH, 128));
4285 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4286}
4287
4288/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004289 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004290 *
4291 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4292 * multiple of the block size and no padding is specified.
4293 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004294TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4295 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4297 .Authorization(TAG_NO_AUTH_REQUIRED)
4298 .AesEncryptionKey(128)
4299 .Authorization(TAG_BLOCK_MODE, blockMode)
4300 .Padding(PaddingMode::NONE)));
4301 // Message is slightly shorter than two blocks.
4302 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004303
David Drysdaled2cc8c22021-04-15 13:29:45 +01004304 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4305 AuthorizationSet out_params;
4306 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4307 string ciphertext;
4308 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4309 EXPECT_EQ(0U, ciphertext.size());
4310
4311 CheckedDeleteKey();
4312 }
Selene Huang31ab4042020-04-29 04:22:39 -07004313}
4314
4315/*
4316 * EncryptionOperationsTest.AesEcbPkcs7Padding
4317 *
4318 * Verifies that AES PKCS7 padding works for any message length.
4319 */
4320TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4322 .Authorization(TAG_NO_AUTH_REQUIRED)
4323 .AesEncryptionKey(128)
4324 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4325 .Padding(PaddingMode::PKCS7)));
4326
4327 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4328
4329 // Try various message lengths; all should work.
4330 for (size_t i = 0; i < 32; ++i) {
4331 string message(i, 'a');
4332 string ciphertext = EncryptMessage(message, params);
4333 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4334 string plaintext = DecryptMessage(ciphertext, params);
4335 EXPECT_EQ(message, plaintext);
4336 }
4337}
4338
4339/*
4340 * EncryptionOperationsTest.AesEcbWrongPadding
4341 *
4342 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4343 * specified.
4344 */
4345TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4346 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4347 .Authorization(TAG_NO_AUTH_REQUIRED)
4348 .AesEncryptionKey(128)
4349 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4350 .Padding(PaddingMode::NONE)));
4351
4352 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4353
4354 // Try various message lengths; all should fail
4355 for (size_t i = 0; i < 32; ++i) {
4356 string message(i, 'a');
4357 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4358 }
4359}
4360
4361/*
4362 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4363 *
4364 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4365 */
4366TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4368 .Authorization(TAG_NO_AUTH_REQUIRED)
4369 .AesEncryptionKey(128)
4370 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4371 .Padding(PaddingMode::PKCS7)));
4372
4373 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4374
4375 string message = "a";
4376 string ciphertext = EncryptMessage(message, params);
4377 EXPECT_EQ(16U, ciphertext.size());
4378 EXPECT_NE(ciphertext, message);
4379 ++ciphertext[ciphertext.size() / 2];
4380
4381 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4382 string plaintext;
4383 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4384}
4385
4386vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4387 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004388 EXPECT_TRUE(iv);
4389 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004390}
4391
4392/*
4393 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4394 *
4395 * Verifies that AES CTR mode works.
4396 */
4397TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4399 .Authorization(TAG_NO_AUTH_REQUIRED)
4400 .AesEncryptionKey(128)
4401 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4402 .Padding(PaddingMode::NONE)));
4403
4404 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4405
4406 string message = "123";
4407 AuthorizationSet out_params;
4408 string ciphertext1 = EncryptMessage(message, params, &out_params);
4409 vector<uint8_t> iv1 = CopyIv(out_params);
4410 EXPECT_EQ(16U, iv1.size());
4411
4412 EXPECT_EQ(message.size(), ciphertext1.size());
4413
4414 out_params.Clear();
4415 string ciphertext2 = EncryptMessage(message, params, &out_params);
4416 vector<uint8_t> iv2 = CopyIv(out_params);
4417 EXPECT_EQ(16U, iv2.size());
4418
4419 // IVs should be random, so ciphertexts should differ.
4420 EXPECT_NE(ciphertext1, ciphertext2);
4421
4422 auto params_iv1 =
4423 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4424 auto params_iv2 =
4425 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4426
4427 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4428 EXPECT_EQ(message, plaintext);
4429 plaintext = DecryptMessage(ciphertext2, params_iv2);
4430 EXPECT_EQ(message, plaintext);
4431
4432 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4433 plaintext = DecryptMessage(ciphertext1, params_iv2);
4434 EXPECT_NE(message, plaintext);
4435 plaintext = DecryptMessage(ciphertext2, params_iv1);
4436 EXPECT_NE(message, plaintext);
4437}
4438
4439/*
4440 * EncryptionOperationsTest.AesIncremental
4441 *
4442 * Verifies that AES works, all modes, when provided data in various size increments.
4443 */
4444TEST_P(EncryptionOperationsTest, AesIncremental) {
4445 auto block_modes = {
4446 BlockMode::ECB,
4447 BlockMode::CBC,
4448 BlockMode::CTR,
4449 BlockMode::GCM,
4450 };
4451
4452 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4453 .Authorization(TAG_NO_AUTH_REQUIRED)
4454 .AesEncryptionKey(128)
4455 .BlockMode(block_modes)
4456 .Padding(PaddingMode::NONE)
4457 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4458
4459 for (int increment = 1; increment <= 240; ++increment) {
4460 for (auto block_mode : block_modes) {
4461 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004462 auto params =
4463 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4464 if (block_mode == BlockMode::GCM) {
4465 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4466 }
Selene Huang31ab4042020-04-29 04:22:39 -07004467
4468 AuthorizationSet output_params;
4469 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4470
4471 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004472 string to_send;
4473 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004474 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004475 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004476 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4477 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004478
4479 switch (block_mode) {
4480 case BlockMode::GCM:
4481 EXPECT_EQ(message.size() + 16, ciphertext.size());
4482 break;
4483 case BlockMode::CTR:
4484 EXPECT_EQ(message.size(), ciphertext.size());
4485 break;
4486 case BlockMode::CBC:
4487 case BlockMode::ECB:
4488 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4489 break;
4490 }
4491
4492 auto iv = output_params.GetTagValue(TAG_NONCE);
4493 switch (block_mode) {
4494 case BlockMode::CBC:
4495 case BlockMode::GCM:
4496 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004497 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4498 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4499 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004500 break;
4501
4502 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004503 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004504 break;
4505 }
4506
4507 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4508 << "Decrypt begin() failed for block mode " << block_mode;
4509
4510 string plaintext;
4511 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004512 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004513 }
4514 ErrorCode error = Finish(to_send, &plaintext);
4515 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4516 << " and increment " << increment;
4517 if (error == ErrorCode::OK) {
4518 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4519 << block_mode << " and increment " << increment;
4520 }
4521 }
4522 }
4523}
4524
4525struct AesCtrSp80038aTestVector {
4526 const char* key;
4527 const char* nonce;
4528 const char* plaintext;
4529 const char* ciphertext;
4530};
4531
4532// These test vectors are taken from
4533// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4534static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4535 // AES-128
4536 {
4537 "2b7e151628aed2a6abf7158809cf4f3c",
4538 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4539 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4540 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4541 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4542 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4543 },
4544 // AES-192
4545 {
4546 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4547 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4548 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4549 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4550 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4551 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4552 },
4553 // AES-256
4554 {
4555 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4556 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4557 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4558 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4559 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4560 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4561 },
4562};
4563
4564/*
4565 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4566 *
4567 * Verifies AES CTR implementation against SP800-38A test vectors.
4568 */
4569TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4570 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4571 for (size_t i = 0; i < 3; i++) {
4572 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4573 const string key = hex2str(test.key);
4574 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4575 InvalidSizes.end())
4576 continue;
4577 const string nonce = hex2str(test.nonce);
4578 const string plaintext = hex2str(test.plaintext);
4579 const string ciphertext = hex2str(test.ciphertext);
4580 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4581 }
4582}
4583
4584/*
4585 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4586 *
4587 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4588 */
4589TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4591 .Authorization(TAG_NO_AUTH_REQUIRED)
4592 .AesEncryptionKey(128)
4593 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4594 .Padding(PaddingMode::PKCS7)));
4595 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4596 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4597}
4598
4599/*
4600 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4601 *
4602 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4603 */
4604TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4606 .Authorization(TAG_NO_AUTH_REQUIRED)
4607 .AesEncryptionKey(128)
4608 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4609 .Authorization(TAG_CALLER_NONCE)
4610 .Padding(PaddingMode::NONE)));
4611
4612 auto params = AuthorizationSetBuilder()
4613 .BlockMode(BlockMode::CTR)
4614 .Padding(PaddingMode::NONE)
4615 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4616 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4617
4618 params = AuthorizationSetBuilder()
4619 .BlockMode(BlockMode::CTR)
4620 .Padding(PaddingMode::NONE)
4621 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4622 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4623
4624 params = AuthorizationSetBuilder()
4625 .BlockMode(BlockMode::CTR)
4626 .Padding(PaddingMode::NONE)
4627 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4628 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4629}
4630
4631/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004632 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004633 *
4634 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4635 */
4636TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4638 .Authorization(TAG_NO_AUTH_REQUIRED)
4639 .AesEncryptionKey(128)
4640 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4641 .Padding(PaddingMode::NONE)));
4642 // Two-block message.
4643 string message = "12345678901234567890123456789012";
4644 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4645 AuthorizationSet out_params;
4646 string ciphertext1 = EncryptMessage(message, params, &out_params);
4647 vector<uint8_t> iv1 = CopyIv(out_params);
4648 EXPECT_EQ(message.size(), ciphertext1.size());
4649
4650 out_params.Clear();
4651
4652 string ciphertext2 = EncryptMessage(message, params, &out_params);
4653 vector<uint8_t> iv2 = CopyIv(out_params);
4654 EXPECT_EQ(message.size(), ciphertext2.size());
4655
4656 // IVs should be random, so ciphertexts should differ.
4657 EXPECT_NE(ciphertext1, ciphertext2);
4658
4659 params.push_back(TAG_NONCE, iv1);
4660 string plaintext = DecryptMessage(ciphertext1, params);
4661 EXPECT_EQ(message, plaintext);
4662}
4663
4664/*
4665 * EncryptionOperationsTest.AesCallerNonce
4666 *
4667 * Verifies that AES caller-provided nonces work correctly.
4668 */
4669TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4671 .Authorization(TAG_NO_AUTH_REQUIRED)
4672 .AesEncryptionKey(128)
4673 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4674 .Authorization(TAG_CALLER_NONCE)
4675 .Padding(PaddingMode::NONE)));
4676
4677 string message = "12345678901234567890123456789012";
4678
4679 // Don't specify nonce, should get a random one.
4680 AuthorizationSetBuilder params =
4681 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4682 AuthorizationSet out_params;
4683 string ciphertext = EncryptMessage(message, params, &out_params);
4684 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004685 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004686
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004687 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004688 string plaintext = DecryptMessage(ciphertext, params);
4689 EXPECT_EQ(message, plaintext);
4690
4691 // Now specify a nonce, should also work.
4692 params = AuthorizationSetBuilder()
4693 .BlockMode(BlockMode::CBC)
4694 .Padding(PaddingMode::NONE)
4695 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4696 out_params.Clear();
4697 ciphertext = EncryptMessage(message, params, &out_params);
4698
4699 // Decrypt with correct nonce.
4700 plaintext = DecryptMessage(ciphertext, params);
4701 EXPECT_EQ(message, plaintext);
4702
4703 // Try with wrong nonce.
4704 params = AuthorizationSetBuilder()
4705 .BlockMode(BlockMode::CBC)
4706 .Padding(PaddingMode::NONE)
4707 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4708 plaintext = DecryptMessage(ciphertext, params);
4709 EXPECT_NE(message, plaintext);
4710}
4711
4712/*
4713 * EncryptionOperationsTest.AesCallerNonceProhibited
4714 *
4715 * Verifies that caller-provided nonces are not permitted when not specified in the key
4716 * authorizations.
4717 */
4718TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4719 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4720 .Authorization(TAG_NO_AUTH_REQUIRED)
4721 .AesEncryptionKey(128)
4722 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4723 .Padding(PaddingMode::NONE)));
4724
4725 string message = "12345678901234567890123456789012";
4726
4727 // Don't specify nonce, should get a random one.
4728 AuthorizationSetBuilder params =
4729 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4730 AuthorizationSet out_params;
4731 string ciphertext = EncryptMessage(message, params, &out_params);
4732 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004733 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004734
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004735 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004736 string plaintext = DecryptMessage(ciphertext, params);
4737 EXPECT_EQ(message, plaintext);
4738
4739 // Now specify a nonce, should fail
4740 params = AuthorizationSetBuilder()
4741 .BlockMode(BlockMode::CBC)
4742 .Padding(PaddingMode::NONE)
4743 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4744 out_params.Clear();
4745 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4746}
4747
4748/*
4749 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4750 *
4751 * Verifies that AES GCM mode works.
4752 */
4753TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4755 .Authorization(TAG_NO_AUTH_REQUIRED)
4756 .AesEncryptionKey(128)
4757 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4758 .Padding(PaddingMode::NONE)
4759 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4760
4761 string aad = "foobar";
4762 string message = "123456789012345678901234567890123456";
4763
4764 auto begin_params = AuthorizationSetBuilder()
4765 .BlockMode(BlockMode::GCM)
4766 .Padding(PaddingMode::NONE)
4767 .Authorization(TAG_MAC_LENGTH, 128);
4768
Selene Huang31ab4042020-04-29 04:22:39 -07004769 // Encrypt
4770 AuthorizationSet begin_out_params;
4771 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4772 << "Begin encrypt";
4773 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004774 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4775 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004776 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4777
4778 // Grab nonce
4779 begin_params.push_back(begin_out_params);
4780
4781 // Decrypt.
4782 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004783 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004784 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004785 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004786 EXPECT_EQ(message.length(), plaintext.length());
4787 EXPECT_EQ(message, plaintext);
4788}
4789
4790/*
4791 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4792 *
4793 * Verifies that AES GCM mode works, even when there's a long delay
4794 * between operations.
4795 */
4796TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4798 .Authorization(TAG_NO_AUTH_REQUIRED)
4799 .AesEncryptionKey(128)
4800 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4801 .Padding(PaddingMode::NONE)
4802 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4803
4804 string aad = "foobar";
4805 string message = "123456789012345678901234567890123456";
4806
4807 auto begin_params = AuthorizationSetBuilder()
4808 .BlockMode(BlockMode::GCM)
4809 .Padding(PaddingMode::NONE)
4810 .Authorization(TAG_MAC_LENGTH, 128);
4811
Selene Huang31ab4042020-04-29 04:22:39 -07004812 // Encrypt
4813 AuthorizationSet begin_out_params;
4814 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4815 << "Begin encrypt";
4816 string ciphertext;
4817 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004818 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004819 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004820 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004821
4822 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4823
4824 // Grab nonce
4825 begin_params.push_back(begin_out_params);
4826
4827 // Decrypt.
4828 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4829 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004830 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004831 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004832 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004833 sleep(5);
4834 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4835 EXPECT_EQ(message.length(), plaintext.length());
4836 EXPECT_EQ(message, plaintext);
4837}
4838
4839/*
4840 * EncryptionOperationsTest.AesGcmDifferentNonces
4841 *
4842 * Verifies that encrypting the same data with different nonces produces different outputs.
4843 */
4844TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4846 .Authorization(TAG_NO_AUTH_REQUIRED)
4847 .AesEncryptionKey(128)
4848 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4849 .Padding(PaddingMode::NONE)
4850 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4851 .Authorization(TAG_CALLER_NONCE)));
4852
4853 string aad = "foobar";
4854 string message = "123456789012345678901234567890123456";
4855 string nonce1 = "000000000000";
4856 string nonce2 = "111111111111";
4857 string nonce3 = "222222222222";
4858
4859 string ciphertext1 =
4860 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4861 string ciphertext2 =
4862 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4863 string ciphertext3 =
4864 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4865
4866 ASSERT_NE(ciphertext1, ciphertext2);
4867 ASSERT_NE(ciphertext1, ciphertext3);
4868 ASSERT_NE(ciphertext2, ciphertext3);
4869}
4870
4871/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004872 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4873 *
4874 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4875 */
4876TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4878 .Authorization(TAG_NO_AUTH_REQUIRED)
4879 .AesEncryptionKey(128)
4880 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4881 .Padding(PaddingMode::NONE)
4882 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4883
4884 string aad = "foobar";
4885 string message = "123456789012345678901234567890123456";
4886
4887 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4888 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4889 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4890
4891 ASSERT_NE(ciphertext1, ciphertext2);
4892 ASSERT_NE(ciphertext1, ciphertext3);
4893 ASSERT_NE(ciphertext2, ciphertext3);
4894}
4895
4896/*
Selene Huang31ab4042020-04-29 04:22:39 -07004897 * EncryptionOperationsTest.AesGcmTooShortTag
4898 *
4899 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4900 */
4901TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4902 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4903 .Authorization(TAG_NO_AUTH_REQUIRED)
4904 .AesEncryptionKey(128)
4905 .BlockMode(BlockMode::GCM)
4906 .Padding(PaddingMode::NONE)
4907 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4908 string message = "123456789012345678901234567890123456";
4909 auto params = AuthorizationSetBuilder()
4910 .BlockMode(BlockMode::GCM)
4911 .Padding(PaddingMode::NONE)
4912 .Authorization(TAG_MAC_LENGTH, 96);
4913
4914 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4915}
4916
4917/*
4918 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4919 *
4920 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4921 */
4922TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4924 .Authorization(TAG_NO_AUTH_REQUIRED)
4925 .AesEncryptionKey(128)
4926 .BlockMode(BlockMode::GCM)
4927 .Padding(PaddingMode::NONE)
4928 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4929 string aad = "foobar";
4930 string message = "123456789012345678901234567890123456";
4931 auto params = AuthorizationSetBuilder()
4932 .BlockMode(BlockMode::GCM)
4933 .Padding(PaddingMode::NONE)
4934 .Authorization(TAG_MAC_LENGTH, 128);
4935
Selene Huang31ab4042020-04-29 04:22:39 -07004936 // Encrypt
4937 AuthorizationSet begin_out_params;
4938 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4939 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004940 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004941
4942 AuthorizationSet finish_out_params;
4943 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004944 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4945 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004946
4947 params = AuthorizationSetBuilder()
4948 .Authorizations(begin_out_params)
4949 .BlockMode(BlockMode::GCM)
4950 .Padding(PaddingMode::NONE)
4951 .Authorization(TAG_MAC_LENGTH, 96);
4952
4953 // Decrypt.
4954 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4955}
4956
4957/*
4958 * EncryptionOperationsTest.AesGcmCorruptKey
4959 *
4960 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4961 */
4962TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4963 const uint8_t nonce_bytes[] = {
4964 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4965 };
4966 string nonce = make_string(nonce_bytes);
4967 const uint8_t ciphertext_bytes[] = {
4968 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4969 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4970 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4971 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4972 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4973 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4974 };
4975 string ciphertext = make_string(ciphertext_bytes);
4976
4977 auto params = AuthorizationSetBuilder()
4978 .BlockMode(BlockMode::GCM)
4979 .Padding(PaddingMode::NONE)
4980 .Authorization(TAG_MAC_LENGTH, 128)
4981 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4982
4983 auto import_params = AuthorizationSetBuilder()
4984 .Authorization(TAG_NO_AUTH_REQUIRED)
4985 .AesEncryptionKey(128)
4986 .BlockMode(BlockMode::GCM)
4987 .Padding(PaddingMode::NONE)
4988 .Authorization(TAG_CALLER_NONCE)
4989 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4990
4991 // Import correct key and decrypt
4992 const uint8_t key_bytes[] = {
4993 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4994 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4995 };
4996 string key = make_string(key_bytes);
4997 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4998 string plaintext = DecryptMessage(ciphertext, params);
4999 CheckedDeleteKey();
5000
5001 // Corrupt key and attempt to decrypt
5002 key[0] = 0;
5003 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5004 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5005 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5006 CheckedDeleteKey();
5007}
5008
5009/*
5010 * EncryptionOperationsTest.AesGcmAadNoData
5011 *
5012 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5013 * encrypt.
5014 */
5015TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5016 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5017 .Authorization(TAG_NO_AUTH_REQUIRED)
5018 .AesEncryptionKey(128)
5019 .BlockMode(BlockMode::GCM)
5020 .Padding(PaddingMode::NONE)
5021 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5022
5023 string aad = "1234567890123456";
5024 auto params = AuthorizationSetBuilder()
5025 .BlockMode(BlockMode::GCM)
5026 .Padding(PaddingMode::NONE)
5027 .Authorization(TAG_MAC_LENGTH, 128);
5028
Selene Huang31ab4042020-04-29 04:22:39 -07005029 // Encrypt
5030 AuthorizationSet begin_out_params;
5031 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5032 string ciphertext;
5033 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005034 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5035 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005036 EXPECT_TRUE(finish_out_params.empty());
5037
5038 // Grab nonce
5039 params.push_back(begin_out_params);
5040
5041 // Decrypt.
5042 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005043 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005044 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005045 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005046
5047 EXPECT_TRUE(finish_out_params.empty());
5048
5049 EXPECT_EQ("", plaintext);
5050}
5051
5052/*
5053 * EncryptionOperationsTest.AesGcmMultiPartAad
5054 *
5055 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5056 * chunks.
5057 */
5058TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5059 const size_t tag_bits = 128;
5060 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5061 .Authorization(TAG_NO_AUTH_REQUIRED)
5062 .AesEncryptionKey(128)
5063 .BlockMode(BlockMode::GCM)
5064 .Padding(PaddingMode::NONE)
5065 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5066
5067 string message = "123456789012345678901234567890123456";
5068 auto begin_params = AuthorizationSetBuilder()
5069 .BlockMode(BlockMode::GCM)
5070 .Padding(PaddingMode::NONE)
5071 .Authorization(TAG_MAC_LENGTH, tag_bits);
5072 AuthorizationSet begin_out_params;
5073
Selene Huang31ab4042020-04-29 04:22:39 -07005074 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5075
5076 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005077 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5078 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005079 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005080 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5081 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005082
Selene Huang31ab4042020-04-29 04:22:39 -07005083 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005084 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005085
5086 // Grab nonce.
5087 begin_params.push_back(begin_out_params);
5088
5089 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005090 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005091 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005092 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005093 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005094 EXPECT_EQ(message, plaintext);
5095}
5096
5097/*
5098 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5099 *
5100 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5101 */
5102TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5104 .Authorization(TAG_NO_AUTH_REQUIRED)
5105 .AesEncryptionKey(128)
5106 .BlockMode(BlockMode::GCM)
5107 .Padding(PaddingMode::NONE)
5108 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5109
5110 string message = "123456789012345678901234567890123456";
5111 auto begin_params = AuthorizationSetBuilder()
5112 .BlockMode(BlockMode::GCM)
5113 .Padding(PaddingMode::NONE)
5114 .Authorization(TAG_MAC_LENGTH, 128);
5115 AuthorizationSet begin_out_params;
5116
Selene Huang31ab4042020-04-29 04:22:39 -07005117 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5118
Shawn Willden92d79c02021-02-19 07:31:55 -07005119 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005120 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005121 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5122 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005123
David Drysdaled2cc8c22021-04-15 13:29:45 +01005124 // The failure should have already cancelled the operation.
5125 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5126
Shawn Willden92d79c02021-02-19 07:31:55 -07005127 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005128}
5129
5130/*
5131 * EncryptionOperationsTest.AesGcmBadAad
5132 *
5133 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5134 */
5135TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5137 .Authorization(TAG_NO_AUTH_REQUIRED)
5138 .AesEncryptionKey(128)
5139 .BlockMode(BlockMode::GCM)
5140 .Padding(PaddingMode::NONE)
5141 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5142
5143 string message = "12345678901234567890123456789012";
5144 auto begin_params = AuthorizationSetBuilder()
5145 .BlockMode(BlockMode::GCM)
5146 .Padding(PaddingMode::NONE)
5147 .Authorization(TAG_MAC_LENGTH, 128);
5148
Selene Huang31ab4042020-04-29 04:22:39 -07005149 // Encrypt
5150 AuthorizationSet begin_out_params;
5151 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005152 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005153 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005154 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005155
5156 // Grab nonce
5157 begin_params.push_back(begin_out_params);
5158
Selene Huang31ab4042020-04-29 04:22:39 -07005159 // Decrypt.
5160 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005161 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005162 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005163 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005164}
5165
5166/*
5167 * EncryptionOperationsTest.AesGcmWrongNonce
5168 *
5169 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5170 */
5171TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5172 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5173 .Authorization(TAG_NO_AUTH_REQUIRED)
5174 .AesEncryptionKey(128)
5175 .BlockMode(BlockMode::GCM)
5176 .Padding(PaddingMode::NONE)
5177 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5178
5179 string message = "12345678901234567890123456789012";
5180 auto begin_params = AuthorizationSetBuilder()
5181 .BlockMode(BlockMode::GCM)
5182 .Padding(PaddingMode::NONE)
5183 .Authorization(TAG_MAC_LENGTH, 128);
5184
Selene Huang31ab4042020-04-29 04:22:39 -07005185 // Encrypt
5186 AuthorizationSet begin_out_params;
5187 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005188 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005189 string ciphertext;
5190 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005191 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005192
5193 // Wrong nonce
5194 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5195
5196 // Decrypt.
5197 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005198 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005199 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005200 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005201
5202 // With wrong nonce, should have gotten garbage plaintext (or none).
5203 EXPECT_NE(message, plaintext);
5204}
5205
5206/*
5207 * EncryptionOperationsTest.AesGcmCorruptTag
5208 *
5209 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5210 */
5211TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5213 .Authorization(TAG_NO_AUTH_REQUIRED)
5214 .AesEncryptionKey(128)
5215 .BlockMode(BlockMode::GCM)
5216 .Padding(PaddingMode::NONE)
5217 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5218
5219 string aad = "1234567890123456";
5220 string message = "123456789012345678901234567890123456";
5221
5222 auto params = AuthorizationSetBuilder()
5223 .BlockMode(BlockMode::GCM)
5224 .Padding(PaddingMode::NONE)
5225 .Authorization(TAG_MAC_LENGTH, 128);
5226
Selene Huang31ab4042020-04-29 04:22:39 -07005227 // Encrypt
5228 AuthorizationSet begin_out_params;
5229 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005230 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005231 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005232 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005233
5234 // Corrupt tag
5235 ++(*ciphertext.rbegin());
5236
5237 // Grab nonce
5238 params.push_back(begin_out_params);
5239
5240 // Decrypt.
5241 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005242 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005243 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005244 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005245}
5246
5247/*
5248 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5249 *
5250 * Verifies that 3DES is basically functional.
5251 */
5252TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5253 auto auths = AuthorizationSetBuilder()
5254 .TripleDesEncryptionKey(168)
5255 .BlockMode(BlockMode::ECB)
5256 .Authorization(TAG_NO_AUTH_REQUIRED)
5257 .Padding(PaddingMode::NONE);
5258
5259 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5260 // Two-block message.
5261 string message = "1234567890123456";
5262 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5263 string ciphertext1 = EncryptMessage(message, inParams);
5264 EXPECT_EQ(message.size(), ciphertext1.size());
5265
5266 string ciphertext2 = EncryptMessage(string(message), inParams);
5267 EXPECT_EQ(message.size(), ciphertext2.size());
5268
5269 // ECB is deterministic.
5270 EXPECT_EQ(ciphertext1, ciphertext2);
5271
5272 string plaintext = DecryptMessage(ciphertext1, inParams);
5273 EXPECT_EQ(message, plaintext);
5274}
5275
5276/*
5277 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5278 *
5279 * Verifies that CBC keys reject ECB usage.
5280 */
5281TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5283 .TripleDesEncryptionKey(168)
5284 .BlockMode(BlockMode::CBC)
5285 .Authorization(TAG_NO_AUTH_REQUIRED)
5286 .Padding(PaddingMode::NONE)));
5287
5288 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5289 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5290}
5291
5292/*
5293 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5294 *
5295 * Tests ECB mode with PKCS#7 padding, various message sizes.
5296 */
5297TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5299 .TripleDesEncryptionKey(168)
5300 .BlockMode(BlockMode::ECB)
5301 .Authorization(TAG_NO_AUTH_REQUIRED)
5302 .Padding(PaddingMode::PKCS7)));
5303
5304 for (size_t i = 0; i < 32; ++i) {
5305 string message(i, 'a');
5306 auto inParams =
5307 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5308 string ciphertext = EncryptMessage(message, inParams);
5309 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5310 string plaintext = DecryptMessage(ciphertext, inParams);
5311 EXPECT_EQ(message, plaintext);
5312 }
5313}
5314
5315/*
5316 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5317 *
5318 * Verifies that keys configured for no padding reject PKCS7 padding
5319 */
5320TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5322 .TripleDesEncryptionKey(168)
5323 .BlockMode(BlockMode::ECB)
5324 .Authorization(TAG_NO_AUTH_REQUIRED)
5325 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005326 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5327 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005328}
5329
5330/*
5331 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5332 *
5333 * Verifies that corrupted padding is detected.
5334 */
5335TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5337 .TripleDesEncryptionKey(168)
5338 .BlockMode(BlockMode::ECB)
5339 .Authorization(TAG_NO_AUTH_REQUIRED)
5340 .Padding(PaddingMode::PKCS7)));
5341
5342 string message = "a";
5343 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5344 EXPECT_EQ(8U, ciphertext.size());
5345 EXPECT_NE(ciphertext, message);
5346 ++ciphertext[ciphertext.size() / 2];
5347
5348 AuthorizationSetBuilder begin_params;
5349 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5350 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5351 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5352 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005353 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005354 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5355}
5356
5357struct TripleDesTestVector {
5358 const char* name;
5359 const KeyPurpose purpose;
5360 const BlockMode block_mode;
5361 const PaddingMode padding_mode;
5362 const char* key;
5363 const char* iv;
5364 const char* input;
5365 const char* output;
5366};
5367
5368// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5369// of the NIST vectors are multiples of the block size.
5370static const TripleDesTestVector kTripleDesTestVectors[] = {
5371 {
5372 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5373 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5374 "", // IV
5375 "329d86bdf1bc5af4", // input
5376 "d946c2756d78633f", // output
5377 },
5378 {
5379 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5380 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5381 "", // IV
5382 "6b1540781b01ce1997adae102dbf3c5b", // input
5383 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5384 },
5385 {
5386 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5387 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5388 "", // IV
5389 "6daad94ce08acfe7", // input
5390 "660e7d32dcc90e79", // output
5391 },
5392 {
5393 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5394 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5395 "", // IV
5396 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5397 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5398 },
5399 {
5400 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5401 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5402 "43f791134c5647ba", // IV
5403 "dcc153cef81d6f24", // input
5404 "92538bd8af18d3ba", // output
5405 },
5406 {
5407 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5408 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5409 "c2e999cb6249023c", // IV
5410 "c689aee38a301bb316da75db36f110b5", // input
5411 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5412 },
5413 {
5414 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5415 PaddingMode::PKCS7,
5416 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5417 "c2e999cb6249023c", // IV
5418 "c689aee38a301bb316da75db36f110b500", // input
5419 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5420 },
5421 {
5422 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5423 PaddingMode::PKCS7,
5424 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5425 "c2e999cb6249023c", // IV
5426 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5427 "c689aee38a301bb316da75db36f110b500", // output
5428 },
5429 {
5430 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5431 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5432 "41746c7e442d3681", // IV
5433 "c53a7b0ec40600fe", // input
5434 "d4f00eb455de1034", // output
5435 },
5436 {
5437 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5438 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5439 "3982bc02c3727d45", // IV
5440 "6006f10adef52991fcc777a1238bbb65", // input
5441 "edae09288e9e3bc05746d872b48e3b29", // output
5442 },
5443};
5444
5445/*
5446 * EncryptionOperationsTest.TripleDesTestVector
5447 *
5448 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5449 */
5450TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5451 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5452 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5453 SCOPED_TRACE(test->name);
5454 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5455 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5456 hex2str(test->output));
5457 }
5458}
5459
5460/*
5461 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5462 *
5463 * Validates CBC mode functionality.
5464 */
5465TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5467 .TripleDesEncryptionKey(168)
5468 .BlockMode(BlockMode::CBC)
5469 .Authorization(TAG_NO_AUTH_REQUIRED)
5470 .Padding(PaddingMode::NONE)));
5471
5472 ASSERT_GT(key_blob_.size(), 0U);
5473
5474 // Two-block message.
5475 string message = "1234567890123456";
5476 vector<uint8_t> iv1;
5477 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5478 EXPECT_EQ(message.size(), ciphertext1.size());
5479
5480 vector<uint8_t> iv2;
5481 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5482 EXPECT_EQ(message.size(), ciphertext2.size());
5483
5484 // IVs should be random, so ciphertexts should differ.
5485 EXPECT_NE(iv1, iv2);
5486 EXPECT_NE(ciphertext1, ciphertext2);
5487
5488 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5489 EXPECT_EQ(message, plaintext);
5490}
5491
5492/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005493 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5494 *
5495 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5496 */
5497TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5499 .TripleDesEncryptionKey(168)
5500 .BlockMode(BlockMode::CBC)
5501 .Authorization(TAG_NO_AUTH_REQUIRED)
5502 .Authorization(TAG_CALLER_NONCE)
5503 .Padding(PaddingMode::NONE)));
5504 auto params = AuthorizationSetBuilder()
5505 .BlockMode(BlockMode::CBC)
5506 .Padding(PaddingMode::NONE)
5507 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5508 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5509}
5510
5511/*
Selene Huang31ab4042020-04-29 04:22:39 -07005512 * EncryptionOperationsTest.TripleDesCallerIv
5513 *
5514 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5515 */
5516TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5518 .TripleDesEncryptionKey(168)
5519 .BlockMode(BlockMode::CBC)
5520 .Authorization(TAG_NO_AUTH_REQUIRED)
5521 .Authorization(TAG_CALLER_NONCE)
5522 .Padding(PaddingMode::NONE)));
5523 string message = "1234567890123456";
5524 vector<uint8_t> iv;
5525 // Don't specify IV, should get a random one.
5526 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5527 EXPECT_EQ(message.size(), ciphertext1.size());
5528 EXPECT_EQ(8U, iv.size());
5529
5530 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5531 EXPECT_EQ(message, plaintext);
5532
5533 // Now specify an IV, should also work.
5534 iv = AidlBuf("abcdefgh");
5535 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5536
5537 // Decrypt with correct IV.
5538 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5539 EXPECT_EQ(message, plaintext);
5540
5541 // Now try with wrong IV.
5542 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5543 EXPECT_NE(message, plaintext);
5544}
5545
5546/*
5547 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5548 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005549 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005550 */
5551TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5552 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5553 .TripleDesEncryptionKey(168)
5554 .BlockMode(BlockMode::CBC)
5555 .Authorization(TAG_NO_AUTH_REQUIRED)
5556 .Padding(PaddingMode::NONE)));
5557
5558 string message = "12345678901234567890123456789012";
5559 vector<uint8_t> iv;
5560 // Don't specify nonce, should get a random one.
5561 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5562 EXPECT_EQ(message.size(), ciphertext1.size());
5563 EXPECT_EQ(8U, iv.size());
5564
5565 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5566 EXPECT_EQ(message, plaintext);
5567
5568 // Now specify a nonce, should fail.
5569 auto input_params = AuthorizationSetBuilder()
5570 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5571 .BlockMode(BlockMode::CBC)
5572 .Padding(PaddingMode::NONE);
5573 AuthorizationSet output_params;
5574 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5575 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5576}
5577
5578/*
5579 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5580 *
5581 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5582 */
5583TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5585 .TripleDesEncryptionKey(168)
5586 .BlockMode(BlockMode::ECB)
5587 .Authorization(TAG_NO_AUTH_REQUIRED)
5588 .Padding(PaddingMode::NONE)));
5589 // Two-block message.
5590 string message = "1234567890123456";
5591 auto begin_params =
5592 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5593 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5594}
5595
5596/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005597 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005598 *
5599 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5600 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005601TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5602 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5604 .TripleDesEncryptionKey(168)
5605 .BlockMode(blockMode)
5606 .Authorization(TAG_NO_AUTH_REQUIRED)
5607 .Padding(PaddingMode::NONE)));
5608 // Message is slightly shorter than two blocks.
5609 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005610
David Drysdaled2cc8c22021-04-15 13:29:45 +01005611 auto begin_params =
5612 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5613 AuthorizationSet output_params;
5614 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5615 string ciphertext;
5616 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5617
5618 CheckedDeleteKey();
5619 }
Selene Huang31ab4042020-04-29 04:22:39 -07005620}
5621
5622/*
5623 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5624 *
5625 * Verifies that PKCS7 padding works correctly in CBC mode.
5626 */
5627TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5629 .TripleDesEncryptionKey(168)
5630 .BlockMode(BlockMode::CBC)
5631 .Authorization(TAG_NO_AUTH_REQUIRED)
5632 .Padding(PaddingMode::PKCS7)));
5633
5634 // Try various message lengths; all should work.
5635 for (size_t i = 0; i < 32; ++i) {
5636 string message(i, 'a');
5637 vector<uint8_t> iv;
5638 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5639 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5640 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5641 EXPECT_EQ(message, plaintext);
5642 }
5643}
5644
5645/*
5646 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5647 *
5648 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5649 */
5650TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5651 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5652 .TripleDesEncryptionKey(168)
5653 .BlockMode(BlockMode::CBC)
5654 .Authorization(TAG_NO_AUTH_REQUIRED)
5655 .Padding(PaddingMode::NONE)));
5656
5657 // Try various message lengths; all should fail.
5658 for (size_t i = 0; i < 32; ++i) {
5659 auto begin_params =
5660 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5661 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5662 }
5663}
5664
5665/*
5666 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5667 *
5668 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5669 */
5670TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5671 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5672 .TripleDesEncryptionKey(168)
5673 .BlockMode(BlockMode::CBC)
5674 .Authorization(TAG_NO_AUTH_REQUIRED)
5675 .Padding(PaddingMode::PKCS7)));
5676
5677 string message = "a";
5678 vector<uint8_t> iv;
5679 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5680 EXPECT_EQ(8U, ciphertext.size());
5681 EXPECT_NE(ciphertext, message);
5682 ++ciphertext[ciphertext.size() / 2];
5683
5684 auto begin_params = AuthorizationSetBuilder()
5685 .BlockMode(BlockMode::CBC)
5686 .Padding(PaddingMode::PKCS7)
5687 .Authorization(TAG_NONCE, iv);
5688 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5689 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005690 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005691 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5692}
5693
5694/*
5695 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5696 *
5697 * Verifies that 3DES CBC works with many different input sizes.
5698 */
5699TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5701 .TripleDesEncryptionKey(168)
5702 .BlockMode(BlockMode::CBC)
5703 .Authorization(TAG_NO_AUTH_REQUIRED)
5704 .Padding(PaddingMode::NONE)));
5705
5706 int increment = 7;
5707 string message(240, 'a');
5708 AuthorizationSet input_params =
5709 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5710 AuthorizationSet output_params;
5711 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5712
5713 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005714 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005715 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005716 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5717 EXPECT_EQ(message.size(), ciphertext.size());
5718
5719 // Move TAG_NONCE into input_params
5720 input_params = output_params;
5721 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5722 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5723 output_params.Clear();
5724
5725 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5726 string plaintext;
5727 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005728 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005729 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5730 EXPECT_EQ(ciphertext.size(), plaintext.size());
5731 EXPECT_EQ(message, plaintext);
5732}
5733
5734INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5735
5736typedef KeyMintAidlTestBase MaxOperationsTest;
5737
5738/*
5739 * MaxOperationsTest.TestLimitAes
5740 *
5741 * Verifies that the max uses per boot tag works correctly with AES keys.
5742 */
5743TEST_P(MaxOperationsTest, TestLimitAes) {
5744 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5745
5746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5747 .Authorization(TAG_NO_AUTH_REQUIRED)
5748 .AesEncryptionKey(128)
5749 .EcbMode()
5750 .Padding(PaddingMode::NONE)
5751 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5752
5753 string message = "1234567890123456";
5754
5755 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5756
5757 EncryptMessage(message, params);
5758 EncryptMessage(message, params);
5759 EncryptMessage(message, params);
5760
5761 // Fourth time should fail.
5762 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5763}
5764
5765/*
Qi Wud22ec842020-11-26 13:27:53 +08005766 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005767 *
5768 * Verifies that the max uses per boot tag works correctly with RSA keys.
5769 */
5770TEST_P(MaxOperationsTest, TestLimitRsa) {
5771 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5772
5773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5774 .Authorization(TAG_NO_AUTH_REQUIRED)
5775 .RsaSigningKey(1024, 65537)
5776 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005777 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5778 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005779
5780 string message = "1234567890123456";
5781
5782 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5783
5784 SignMessage(message, params);
5785 SignMessage(message, params);
5786 SignMessage(message, params);
5787
5788 // Fourth time should fail.
5789 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5790}
5791
5792INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5793
Qi Wud22ec842020-11-26 13:27:53 +08005794typedef KeyMintAidlTestBase UsageCountLimitTest;
5795
5796/*
Qi Wubeefae42021-01-28 23:16:37 +08005797 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005798 *
Qi Wubeefae42021-01-28 23:16:37 +08005799 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005800 */
Qi Wubeefae42021-01-28 23:16:37 +08005801TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005802 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5803
5804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5805 .Authorization(TAG_NO_AUTH_REQUIRED)
5806 .AesEncryptionKey(128)
5807 .EcbMode()
5808 .Padding(PaddingMode::NONE)
5809 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5810
5811 // Check the usage count limit tag appears in the authorizations.
5812 AuthorizationSet auths;
5813 for (auto& entry : key_characteristics_) {
5814 auths.push_back(AuthorizationSet(entry.authorizations));
5815 }
5816 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5817 << "key usage count limit " << 1U << " missing";
5818
5819 string message = "1234567890123456";
5820 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5821
Qi Wubeefae42021-01-28 23:16:37 +08005822 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5823 AuthorizationSet keystore_auths =
5824 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5825
Qi Wud22ec842020-11-26 13:27:53 +08005826 // First usage of AES key should work.
5827 EncryptMessage(message, params);
5828
Qi Wud22ec842020-11-26 13:27:53 +08005829 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5830 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5831 // must be invalidated from secure storage (such as RPMB partition).
5832 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5833 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005834 // Usage count limit tag is enforced by keystore, keymint does nothing.
5835 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005836 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5837 }
5838}
5839
5840/*
Qi Wubeefae42021-01-28 23:16:37 +08005841 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005842 *
Qi Wubeefae42021-01-28 23:16:37 +08005843 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005844 */
Qi Wubeefae42021-01-28 23:16:37 +08005845TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5846 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5847
5848 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5849 .Authorization(TAG_NO_AUTH_REQUIRED)
5850 .AesEncryptionKey(128)
5851 .EcbMode()
5852 .Padding(PaddingMode::NONE)
5853 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5854
5855 // Check the usage count limit tag appears in the authorizations.
5856 AuthorizationSet auths;
5857 for (auto& entry : key_characteristics_) {
5858 auths.push_back(AuthorizationSet(entry.authorizations));
5859 }
5860 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5861 << "key usage count limit " << 3U << " missing";
5862
5863 string message = "1234567890123456";
5864 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5865
5866 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5867 AuthorizationSet keystore_auths =
5868 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5869
5870 EncryptMessage(message, params);
5871 EncryptMessage(message, params);
5872 EncryptMessage(message, params);
5873
5874 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5875 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5876 // must be invalidated from secure storage (such as RPMB partition).
5877 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5878 } else {
5879 // Usage count limit tag is enforced by keystore, keymint does nothing.
5880 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5881 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5882 }
5883}
5884
5885/*
5886 * UsageCountLimitTest.TestSingleUseRsa
5887 *
5888 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5889 */
5890TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005891 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5892
5893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5894 .Authorization(TAG_NO_AUTH_REQUIRED)
5895 .RsaSigningKey(1024, 65537)
5896 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005897 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5898 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005899
5900 // Check the usage count limit tag appears in the authorizations.
5901 AuthorizationSet auths;
5902 for (auto& entry : key_characteristics_) {
5903 auths.push_back(AuthorizationSet(entry.authorizations));
5904 }
5905 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5906 << "key usage count limit " << 1U << " missing";
5907
5908 string message = "1234567890123456";
5909 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5910
Qi Wubeefae42021-01-28 23:16:37 +08005911 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5912 AuthorizationSet keystore_auths =
5913 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5914
Qi Wud22ec842020-11-26 13:27:53 +08005915 // First usage of RSA key should work.
5916 SignMessage(message, params);
5917
Qi Wud22ec842020-11-26 13:27:53 +08005918 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5919 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5920 // must be invalidated from secure storage (such as RPMB partition).
5921 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5922 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005923 // Usage count limit tag is enforced by keystore, keymint does nothing.
5924 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5925 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5926 }
5927}
5928
5929/*
5930 * UsageCountLimitTest.TestLimitUseRsa
5931 *
5932 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5933 */
5934TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5935 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5936
5937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5938 .Authorization(TAG_NO_AUTH_REQUIRED)
5939 .RsaSigningKey(1024, 65537)
5940 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005941 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5942 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005943
5944 // Check the usage count limit tag appears in the authorizations.
5945 AuthorizationSet auths;
5946 for (auto& entry : key_characteristics_) {
5947 auths.push_back(AuthorizationSet(entry.authorizations));
5948 }
5949 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5950 << "key usage count limit " << 3U << " missing";
5951
5952 string message = "1234567890123456";
5953 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5954
5955 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5956 AuthorizationSet keystore_auths =
5957 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5958
5959 SignMessage(message, params);
5960 SignMessage(message, params);
5961 SignMessage(message, params);
5962
5963 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5964 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5965 // must be invalidated from secure storage (such as RPMB partition).
5966 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5967 } else {
5968 // Usage count limit tag is enforced by keystore, keymint does nothing.
5969 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005970 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5971 }
5972}
5973
Qi Wu8e727f72021-02-11 02:49:33 +08005974/*
5975 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5976 *
5977 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5978 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5979 * in hardware.
5980 */
5981TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5982 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5983
5984 auto error = GenerateKey(AuthorizationSetBuilder()
5985 .RsaSigningKey(2048, 65537)
5986 .Digest(Digest::NONE)
5987 .Padding(PaddingMode::NONE)
5988 .Authorization(TAG_NO_AUTH_REQUIRED)
5989 .Authorization(TAG_ROLLBACK_RESISTANCE)
5990 .SetDefaultValidity());
5991 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5992
5993 if (error == ErrorCode::OK) {
5994 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5995 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5996 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5997 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5998
5999 // The KeyMint should also enforce single use key in hardware when it supports rollback
6000 // resistance.
6001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6002 .Authorization(TAG_NO_AUTH_REQUIRED)
6003 .RsaSigningKey(1024, 65537)
6004 .NoDigestOrPadding()
6005 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6006 .SetDefaultValidity()));
6007
6008 // Check the usage count limit tag appears in the hardware authorizations.
6009 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6010 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6011 << "key usage count limit " << 1U << " missing";
6012
6013 string message = "1234567890123456";
6014 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6015
6016 // First usage of RSA key should work.
6017 SignMessage(message, params);
6018
6019 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6020 // must be invalidated from secure storage (such as RPMB partition).
6021 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6022 }
6023}
6024
Qi Wud22ec842020-11-26 13:27:53 +08006025INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6026
David Drysdale7de9feb2021-03-05 14:56:19 +00006027typedef KeyMintAidlTestBase GetHardwareInfoTest;
6028
6029TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6030 // Retrieving hardware info should give the same result each time.
6031 KeyMintHardwareInfo info;
6032 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6033 KeyMintHardwareInfo info2;
6034 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6035 EXPECT_EQ(info, info2);
6036}
6037
6038INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6039
Selene Huang31ab4042020-04-29 04:22:39 -07006040typedef KeyMintAidlTestBase AddEntropyTest;
6041
6042/*
6043 * AddEntropyTest.AddEntropy
6044 *
6045 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6046 * is actually added.
6047 */
6048TEST_P(AddEntropyTest, AddEntropy) {
6049 string data = "foo";
6050 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6051}
6052
6053/*
6054 * AddEntropyTest.AddEmptyEntropy
6055 *
6056 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6057 */
6058TEST_P(AddEntropyTest, AddEmptyEntropy) {
6059 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6060}
6061
6062/*
6063 * AddEntropyTest.AddLargeEntropy
6064 *
6065 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6066 */
6067TEST_P(AddEntropyTest, AddLargeEntropy) {
6068 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6069}
6070
David Drysdalebb3d85e2021-04-13 11:15:51 +01006071/*
6072 * AddEntropyTest.AddTooLargeEntropy
6073 *
6074 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6075 */
6076TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6077 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6078 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6079}
6080
Selene Huang31ab4042020-04-29 04:22:39 -07006081INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6082
Selene Huang31ab4042020-04-29 04:22:39 -07006083typedef KeyMintAidlTestBase KeyDeletionTest;
6084
6085/**
6086 * KeyDeletionTest.DeleteKey
6087 *
6088 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6089 * valid key blob.
6090 */
6091TEST_P(KeyDeletionTest, DeleteKey) {
6092 auto error = GenerateKey(AuthorizationSetBuilder()
6093 .RsaSigningKey(2048, 65537)
6094 .Digest(Digest::NONE)
6095 .Padding(PaddingMode::NONE)
6096 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006097 .Authorization(TAG_ROLLBACK_RESISTANCE)
6098 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006099 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6100
6101 // Delete must work if rollback protection is implemented
6102 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006103 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006104 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6105
6106 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6107
6108 string message = "12345678901234567890123456789012";
6109 AuthorizationSet begin_out_params;
6110 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6111 Begin(KeyPurpose::SIGN, key_blob_,
6112 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6113 &begin_out_params));
6114 AbortIfNeeded();
6115 key_blob_ = AidlBuf();
6116 }
6117}
6118
6119/**
6120 * KeyDeletionTest.DeleteInvalidKey
6121 *
6122 * This test checks that the HAL excepts invalid key blobs..
6123 */
6124TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6125 // Generate key just to check if rollback protection is implemented
6126 auto error = GenerateKey(AuthorizationSetBuilder()
6127 .RsaSigningKey(2048, 65537)
6128 .Digest(Digest::NONE)
6129 .Padding(PaddingMode::NONE)
6130 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006131 .Authorization(TAG_ROLLBACK_RESISTANCE)
6132 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006133 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6134
6135 // Delete must work if rollback protection is implemented
6136 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006137 AuthorizationSet enforced(SecLevelAuthorizations());
6138 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006139
6140 // Delete the key we don't care about the result at this point.
6141 DeleteKey();
6142
6143 // Now create an invalid key blob and delete it.
6144 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6145
6146 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6147 }
6148}
6149
6150/**
6151 * KeyDeletionTest.DeleteAllKeys
6152 *
6153 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6154 *
6155 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6156 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6157 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6158 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6159 * credentials stored in Keystore/Keymint.
6160 */
6161TEST_P(KeyDeletionTest, DeleteAllKeys) {
6162 if (!arm_deleteAllKeys) return;
6163 auto error = GenerateKey(AuthorizationSetBuilder()
6164 .RsaSigningKey(2048, 65537)
6165 .Digest(Digest::NONE)
6166 .Padding(PaddingMode::NONE)
6167 .Authorization(TAG_NO_AUTH_REQUIRED)
6168 .Authorization(TAG_ROLLBACK_RESISTANCE));
6169 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6170
6171 // Delete must work if rollback protection is implemented
6172 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006173 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006174 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6175
6176 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6177
6178 string message = "12345678901234567890123456789012";
6179 AuthorizationSet begin_out_params;
6180
6181 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6182 Begin(KeyPurpose::SIGN, key_blob_,
6183 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6184 &begin_out_params));
6185 AbortIfNeeded();
6186 key_blob_ = AidlBuf();
6187 }
6188}
6189
6190INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6191
David Drysdaled2cc8c22021-04-15 13:29:45 +01006192typedef KeyMintAidlTestBase KeyUpgradeTest;
6193
6194/**
6195 * KeyUpgradeTest.UpgradeInvalidKey
6196 *
6197 * This test checks that the HAL excepts invalid key blobs..
6198 */
6199TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6200 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6201
6202 std::vector<uint8_t> new_blob;
6203 Status result = keymint_->upgradeKey(key_blob,
6204 AuthorizationSetBuilder()
6205 .Authorization(TAG_APPLICATION_ID, "clientid")
6206 .Authorization(TAG_APPLICATION_DATA, "appdata")
6207 .vector_data(),
6208 &new_blob);
6209 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6210}
6211
6212INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6213
Selene Huang31ab4042020-04-29 04:22:39 -07006214using UpgradeKeyTest = KeyMintAidlTestBase;
6215
6216/*
6217 * UpgradeKeyTest.UpgradeKey
6218 *
6219 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6220 */
6221TEST_P(UpgradeKeyTest, UpgradeKey) {
6222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6223 .AesEncryptionKey(128)
6224 .Padding(PaddingMode::NONE)
6225 .Authorization(TAG_NO_AUTH_REQUIRED)));
6226
6227 auto result = UpgradeKey(key_blob_);
6228
6229 // Key doesn't need upgrading. Should get okay, but no new key blob.
6230 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6231}
6232
6233INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6234
6235using ClearOperationsTest = KeyMintAidlTestBase;
6236
6237/*
6238 * ClearSlotsTest.TooManyOperations
6239 *
6240 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6241 * operations are started without being finished or aborted. Also verifies
6242 * that aborting the operations clears the operations.
6243 *
6244 */
6245TEST_P(ClearOperationsTest, TooManyOperations) {
6246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6247 .Authorization(TAG_NO_AUTH_REQUIRED)
6248 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006249 .Padding(PaddingMode::NONE)
6250 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006251
6252 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6253 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006254 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006255 AuthorizationSet out_params;
6256 ErrorCode result;
6257 size_t i;
6258
6259 for (i = 0; i < max_operations; i++) {
6260 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6261 if (ErrorCode::OK != result) {
6262 break;
6263 }
6264 }
6265 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6266 // Try again just in case there's a weird overflow bug
6267 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6268 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6269 for (size_t j = 0; j < i; j++) {
6270 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6271 << "Aboort failed for i = " << j << std::endl;
6272 }
6273 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6274 AbortIfNeeded();
6275}
6276
6277INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6278
6279typedef KeyMintAidlTestBase TransportLimitTest;
6280
6281/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006282 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006283 *
6284 * Verifies that passing input data to finish succeeds as expected.
6285 */
6286TEST_P(TransportLimitTest, LargeFinishInput) {
6287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6288 .Authorization(TAG_NO_AUTH_REQUIRED)
6289 .AesEncryptionKey(128)
6290 .BlockMode(BlockMode::ECB)
6291 .Padding(PaddingMode::NONE)));
6292
6293 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6294 auto cipher_params =
6295 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6296
6297 AuthorizationSet out_params;
6298 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6299
6300 string plain_message = std::string(1 << msg_size, 'x');
6301 string encrypted_message;
6302 auto rc = Finish(plain_message, &encrypted_message);
6303
6304 EXPECT_EQ(ErrorCode::OK, rc);
6305 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6306 << "Encrypt finish returned OK, but did not consume all of the given input";
6307 cipher_params.push_back(out_params);
6308
6309 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6310
6311 string decrypted_message;
6312 rc = Finish(encrypted_message, &decrypted_message);
6313 EXPECT_EQ(ErrorCode::OK, rc);
6314 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6315 << "Decrypt finish returned OK, did not consume all of the given input";
6316 }
6317}
6318
6319INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6320
David Zeuthene0c40892021-01-08 12:54:11 -05006321typedef KeyMintAidlTestBase KeyAgreementTest;
6322
6323int CurveToOpenSslCurveName(EcCurve curve) {
6324 switch (curve) {
6325 case EcCurve::P_224:
6326 return NID_secp224r1;
6327 case EcCurve::P_256:
6328 return NID_X9_62_prime256v1;
6329 case EcCurve::P_384:
6330 return NID_secp384r1;
6331 case EcCurve::P_521:
6332 return NID_secp521r1;
6333 }
6334}
6335
6336/*
6337 * KeyAgreementTest.Ecdh
6338 *
6339 * Verifies that ECDH works for all curves
6340 */
6341TEST_P(KeyAgreementTest, Ecdh) {
6342 // Because it's possible to use this API with keys on different curves, we
6343 // check all N^2 combinations where N is the number of supported
6344 // curves.
6345 //
6346 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6347 // lot more curves we can be smart about things and just pick |otherCurve| so
6348 // it's not |curve| and that way we end up with only 2*N runs
6349 //
6350 for (auto curve : ValidCurves()) {
6351 for (auto localCurve : ValidCurves()) {
6352 // Generate EC key locally (with access to private key material)
6353 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6354 int curveName = CurveToOpenSslCurveName(localCurve);
6355 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6356 ASSERT_NE(group, nullptr);
6357 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6358 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6359 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6360 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6361
6362 // Get encoded form of the public part of the locally generated key...
6363 unsigned char* p = nullptr;
6364 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6365 ASSERT_GT(encodedPublicKeySize, 0);
6366 vector<uint8_t> encodedPublicKey(
6367 reinterpret_cast<const uint8_t*>(p),
6368 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6369 OPENSSL_free(p);
6370
6371 // Generate EC key in KeyMint (only access to public key material)
6372 vector<uint8_t> challenge = {0x41, 0x42};
6373 EXPECT_EQ(
6374 ErrorCode::OK,
6375 GenerateKey(AuthorizationSetBuilder()
6376 .Authorization(TAG_NO_AUTH_REQUIRED)
6377 .Authorization(TAG_EC_CURVE, curve)
6378 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6379 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6380 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006381 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6382 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006383 << "Failed to generate key";
6384 ASSERT_GT(cert_chain_.size(), 0);
6385 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6386 ASSERT_NE(kmKeyCert, nullptr);
6387 // Check that keyAgreement (bit 4) is set in KeyUsage
6388 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6389 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6390 ASSERT_NE(kmPkey, nullptr);
6391 if (dump_Attestations) {
6392 for (size_t n = 0; n < cert_chain_.size(); n++) {
6393 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6394 }
6395 }
6396
6397 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6398 if (curve != localCurve) {
6399 // If the keys are using different curves KeyMint should fail with
6400 // ErrorCode:INVALID_ARGUMENT. Check that.
6401 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6402 string ZabFromKeyMintStr;
6403 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6404 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6405 &ZabFromKeyMintStr));
6406
6407 } else {
6408 // Otherwise if the keys are using the same curve, it should work.
6409 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6410 string ZabFromKeyMintStr;
6411 EXPECT_EQ(ErrorCode::OK,
6412 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6413 &ZabFromKeyMintStr));
6414 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6415
6416 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6417 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6418 ASSERT_NE(ctx, nullptr);
6419 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6420 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6421 size_t ZabFromTestLen = 0;
6422 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6423 vector<uint8_t> ZabFromTest;
6424 ZabFromTest.resize(ZabFromTestLen);
6425 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6426
6427 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6428 }
6429
6430 CheckedDeleteKey();
6431 }
6432 }
6433}
6434
6435INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6436
David Drysdaled2cc8c22021-04-15 13:29:45 +01006437using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6438
6439// This is a problematic test, as it can render the device under test permanently unusable.
6440// Re-enable and run at your own risk.
6441TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6442 auto result = DestroyAttestationIds();
6443 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6444}
6445
6446INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6447
Shawn Willdend659c7c2021-02-19 14:51:51 -07006448using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006449
David Drysdaledb0dcf52021-05-18 11:43:31 +01006450/*
6451 * EarlyBootKeyTest.CreateEarlyBootKeys
6452 *
6453 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6454 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006455TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006456 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006457 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6458 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6459
David Drysdaleadfe6112021-05-27 12:00:53 +01006460 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6461 ASSERT_GT(keyData.blob.size(), 0U);
6462 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6463 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6464 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006465 CheckedDeleteKey(&aesKeyData.blob);
6466 CheckedDeleteKey(&hmacKeyData.blob);
6467 CheckedDeleteKey(&rsaKeyData.blob);
6468 CheckedDeleteKey(&ecdsaKeyData.blob);
6469}
6470
David Drysdaledb0dcf52021-05-18 11:43:31 +01006471/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006472 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6473 *
6474 * Verifies that creating an early boot key with attestation succeeds.
6475 */
6476TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6477 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6478 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6479 builder->AttestationChallenge("challenge");
6480 builder->AttestationApplicationId("app_id");
6481 });
6482
6483 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6484 ASSERT_GT(keyData.blob.size(), 0U);
6485 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6486 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6487 }
6488 CheckedDeleteKey(&aesKeyData.blob);
6489 CheckedDeleteKey(&hmacKeyData.blob);
6490 CheckedDeleteKey(&rsaKeyData.blob);
6491 CheckedDeleteKey(&ecdsaKeyData.blob);
6492}
6493
6494/*
6495 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006496 *
6497 * Verifies that using early boot keys at a later stage fails.
6498 */
6499TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6500 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6501 .Authorization(TAG_NO_AUTH_REQUIRED)
6502 .Authorization(TAG_EARLY_BOOT_ONLY)
6503 .HmacKey(128)
6504 .Digest(Digest::SHA_2_256)
6505 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6506 AuthorizationSet output_params;
6507 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6508 AuthorizationSetBuilder()
6509 .Digest(Digest::SHA_2_256)
6510 .Authorization(TAG_MAC_LENGTH, 256),
6511 &output_params));
6512}
6513
6514/*
6515 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6516 *
6517 * Verifies that importing early boot keys fails.
6518 */
6519TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6520 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6521 .Authorization(TAG_NO_AUTH_REQUIRED)
6522 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006523 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006524 .Digest(Digest::SHA_2_256)
6525 .SetDefaultValidity(),
6526 KeyFormat::PKCS8, ec_256_key));
6527}
6528
David Drysdaled2cc8c22021-04-15 13:29:45 +01006529// 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 +00006530// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6531// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6532// early boot, so you'll have to reboot between runs.
6533TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6534 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6535 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6536 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6537 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6538 EXPECT_TRUE(
6539 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6540 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6541 EXPECT_TRUE(
6542 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6543
6544 // Should be able to use keys, since early boot has not ended
6545 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6546 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6547 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6548 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6549
6550 // End early boot
6551 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6552 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6553
6554 // Should not be able to use already-created keys.
6555 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6556 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6557 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6558 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6559
6560 CheckedDeleteKey(&aesKeyData.blob);
6561 CheckedDeleteKey(&hmacKeyData.blob);
6562 CheckedDeleteKey(&rsaKeyData.blob);
6563 CheckedDeleteKey(&ecdsaKeyData.blob);
6564
6565 // Should not be able to create new keys
6566 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6567 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6568
6569 CheckedDeleteKey(&aesKeyData.blob);
6570 CheckedDeleteKey(&hmacKeyData.blob);
6571 CheckedDeleteKey(&rsaKeyData.blob);
6572 CheckedDeleteKey(&ecdsaKeyData.blob);
6573}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006574
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006575INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6576
Shawn Willdend659c7c2021-02-19 14:51:51 -07006577using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006578
6579// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6580// between runs... and on most test devices there are no enrolled credentials so it can't be
6581// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6582// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6583// a manual test process, which includes unlocking between runs, which is why it's included here.
6584// Well, that and the fact that it's the only test we can do without also making calls into the
6585// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6586// implications might be, so that may or may not be a solution.
6587TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6588 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6589 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6590
6591 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6592 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6593 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6594 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6595
6596 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006597 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006598 ASSERT_EQ(ErrorCode::OK, rc);
6599 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6600 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6601 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6602 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6603
6604 CheckedDeleteKey(&aesKeyData.blob);
6605 CheckedDeleteKey(&hmacKeyData.blob);
6606 CheckedDeleteKey(&rsaKeyData.blob);
6607 CheckedDeleteKey(&ecdsaKeyData.blob);
6608}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006609
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006610INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6611
Janis Danisevskis24c04702020-12-16 18:28:39 -08006612} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006613
6614int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006615 std::cout << "Testing ";
6616 auto halInstances =
6617 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6618 std::cout << "HAL instances:\n";
6619 for (auto& entry : halInstances) {
6620 std::cout << " " << entry << '\n';
6621 }
6622
Selene Huang31ab4042020-04-29 04:22:39 -07006623 ::testing::InitGoogleTest(&argc, argv);
6624 for (int i = 1; i < argc; ++i) {
6625 if (argv[i][0] == '-') {
6626 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006627 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6628 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006629 }
6630 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006631 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6632 dump_Attestations = true;
6633 } else {
6634 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006635 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006636 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6637 if (std::string(argv[i]) == "--check_patchLevels") {
6638 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6639 }
Selene Huang31ab4042020-04-29 04:22:39 -07006640 }
6641 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006642 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006643}