blob: 5a87b83854dbd98365bec8727e51c500ede9a71e [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale92464372021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Selene Huang31ab4042020-04-29 04:22:39 -070074template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000075bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
76 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070077 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080078 if (auto p = authorizationValue(ttag, param)) {
79 return *p == expected_value;
80 }
81 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070082 });
83 return (it != set.end());
84}
85
86template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(),
89 [&](const KeyParameter& param) { return param.tag == tag; });
90 return (it != set.end());
91}
92
93constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
97 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
109
110string hex2str(string a) {
111 string b;
112 size_t num = a.size() / 2;
113 b.resize(num);
114 for (size_t i = 0; i < num; i++) {
115 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
116 }
117 return b;
118}
119
David Drysdaled2cc8c22021-04-15 13:29:45 +0100120string rsa_key = hex2str(
121 // RFC 5208 s5
122 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
123 "020100" // INTEGER length 1 value 0x00 (version)
124 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
125 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
126 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
127 "0500" // NULL (parameters)
128 // } end SEQUENCE (AlgorithmIdentifier)
129 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
130 // RFC 8017 A.1.2
131 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
132 "020100" // INTEGER length 1 value 0x00 (version)
133 "028181" // INTEGER length 0x81 value (modulus) ...
134 "00c6095409047d8634812d5a218176e4"
135 "5c41d60a75b13901f234226cffe77652"
136 "1c5a77b9e389417b71c0b6a44d13afe4"
137 "e4a2805d46c9da2935adb1ff0c1f24ea"
138 "06e62b20d776430a4d435157233c6f91"
139 "6783c30e310fcbd89b85c2d567711697"
140 "85ac12bca244abda72bfb19fc44d27c8"
141 "1e1d92de284f4061edfd99280745ea6d"
142 "25"
143 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
144 "028180" // INTEGER length 0x80 (privateExponent) value...
145 "1be0f04d9cae3718691f035338308e91"
146 "564b55899ffb5084d2460e6630257e05"
147 "b3ceab02972dfabcd6ce5f6ee2589eb6"
148 "7911ed0fac16e43a444b8c861e544a05"
149 "93365772f8baf6b22fc9e3c5f1024b06"
150 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
151 "ace7240290bef16c0b3f7f3cdd64ce3a"
152 "b5912cf6e32f39ab188358afcccd8081"
153 "0241" // INTEGER length 0x41 (prime1)
154 "00e4b49ef50f765d3b24dde01aceaaf1"
155 "30f2c76670a91a61ae08af497b4a82be"
156 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
157 "8c92bfab137fba2285227b83c342ff7c"
158 "55"
159 "0241" // INTEGER length 0x41 (prime2)
160 "00ddabb5839c4c7f6bf3d4183231f005"
161 "b31aa58affdda5c79e4cce217f6bc930"
162 "dbe563d480706c24e9ebfcab28a6cdef"
163 "d324b77e1bf7251b709092c24ff501fd"
164 "91"
165 "0240" // INTEGER length 0x40 (exponent1)
166 "23d4340eda3445d8cd26c14411da6fdc"
167 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
168 "842c1d280405bc2f6c1bea214a1d742a"
169 "b996b35b63a82a5e470fa88dbf823cdd"
170 "0240" // INTEGER length 0x40 (exponent2)
171 "1b7b57449ad30d1518249a5f56bb9829"
172 "4d4b6ac12ffc86940497a5a5837a6cf9"
173 "46262b494526d328c11e1126380fde04"
174 "c24f916dec250892db09a6d77cdba351"
175 "0240" // INTEGER length 0x40 (coefficient)
176 "7762cd8f4d050da56bd591adb515d24d"
177 "7ccd32cca0d05f866d583514bd7324d5"
178 "f33645e8ed8b4a1cb3cc4a1d67987399"
179 "f2a09f5b3fb68c88d5e5d90ac33492d6"
180 // } end SEQUENCE (PrivateKey)
181 // } end SEQUENCE (PrivateKeyInfo)
182);
Selene Huang31ab4042020-04-29 04:22:39 -0700183
Selene Huange5727e62021-04-13 22:41:20 -0700184/*
185 * DER-encoded PKCS#8 format RSA key. Generated using:
186 *
187 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
188 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100189string rsa_2048_key = hex2str(
190 // RFC 5208 s5
191 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
192 "020100" // INTEGER length 1 value 0x00 (version)
193 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
194 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
195 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
196 "0500" // NULL (parameters)
197 // } end SEQUENCE (AlgorithmIdentifier)
198 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
199 // RFC 8017 A.1.2
200 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
201 "020100" // INTEGER length 1 value 0x00 (version)
202 "02820101" // INTEGER length 0x101 value (modulus) ...
203 "00BEBC342B56D443B1299F9A6A7056E8"
204 "0A897E318476A5A18029E63B2ED739A6"
205 "1791D339F58DC763D9D14911F2EDEC38"
206 "3DEE11F6319B44510E7A3ECD9B79B973"
207 "82E49500ACF8117DC89CAF0E621F7775"
208 "6554A2FD4664BFE7AB8B59AB48340DBF"
209 "A27B93B5A81F6ECDEB02D0759307128D"
210 "F3E3BAD4055C8B840216DFAA5700670E"
211 "6C5126F0962FCB70FF308F25049164CC"
212 "F76CC2DA66A7DD9A81A714C2809D6918"
213 "6133D29D84568E892B6FFBF3199BDB14"
214 "383EE224407F190358F111A949552ABA"
215 "6714227D1BD7F6B20DD0CB88F9467B71"
216 "9339F33BFF35B3870B3F62204E4286B0"
217 "948EA348B524544B5F9838F29EE643B0"
218 "79EEF8A713B220D7806924CDF7295070"
219 "C5"
220 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
221 "02820100" // INTEGER length 0x100 (privateExponent) value...
222 "69F377F35F2F584EF075353CCD1CA997"
223 "38DB3DBC7C7FF35F9366CE176DFD1B13"
224 "5AB10030344ABF5FBECF1D4659FDEF1C"
225 "0FC430834BE1BE3911951377BB3D563A"
226 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
227 "2686C7B4B3C09A7B8354133E6F93F790"
228 "D59EAEB92E84C9A4339302CCE28FDF04"
229 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
230 "6AB706645BF074A4E4090D06FB163124"
231 "365FD5EE7A20D350E9958CC30D91326E"
232 "1B292E9EF5DB408EC42DAF737D201497"
233 "04D0A678A0FB5B5446863B099228A352"
234 "D604BA8091A164D01D5AB05397C71EAD"
235 "20BE2A08FC528FE442817809C787FEE4"
236 "AB97F97B9130D022153EDC6EB6CBE7B0"
237 "F8E3473F2E901209B5DB10F93604DB01"
238 "028181" // INTEGER length 0x81 (prime1)
239 "00E83C0998214941EA4F9293F1B77E2E"
240 "99E6CF305FAF358238E126124FEAF2EB"
241 "9724B2EA7B78E6032343821A80E55D1D"
242 "88FB12D220C3F41A56142FEC85796D19"
243 "17F1E8C774F142B67D3D6E7B7E6B4383"
244 "E94DB5929089DBB346D5BDAB40CC2D96"
245 "EE0409475E175C63BF78CFD744136740"
246 "838127EA723FF3FE7FA368C1311B4A4E"
247 "05"
248 "028181" // INTEGER length 0x81 (prime2)
249 "00D240FCC0F5D7715CDE21CB2DC86EA1"
250 "46132EA3B06F61FF2AF54BF38473F59D"
251 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
252 "B1B58C39F95E4798CCBB43E83D0119AC"
253 "F532F359CA743C85199F0286610E2009"
254 "97D7312917179AC9B67558773212EC96"
255 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
256 "94D94E066A0900B7B70E82A44FB30053"
257 "C1"
258 "028181" // INTEGER length 0x81 (exponent1)
259 "00AD15DA1CBD6A492B66851BA8C316D3"
260 "8AB700E2CFDDD926A658003513C54BAA"
261 "152B30021D667D20078F500F8AD3E7F3"
262 "945D74A891ED1A28EAD0FEEAEC8C14A8"
263 "E834CF46A13D1378C99D18940823CFDD"
264 "27EC5810D59339E0C34198AC638E09C8"
265 "7CBB1B634A9864AE9F4D5EB2D53514F6"
266 "7B4CAEC048C8AB849A02E397618F3271"
267 "35"
268 "028180" // INTEGER length 0x80 (exponent2)
269 "1FA2C1A5331880A92D8F3E281C617108"
270 "BF38244F16E352E69ED417C7153F9EC3"
271 "18F211839C643DCF8B4DD67CE2AC312E"
272 "95178D5D952F06B1BF779F4916924B70"
273 "F582A23F11304E02A5E7565AE22A35E7"
274 "4FECC8B6FDC93F92A1A37703E4CF0E63"
275 "783BD02EB716A7ECBBFA606B10B74D01"
276 "579522E7EF84D91FC522292108D902C1"
277 "028180" // INTEGER length 0x80 (coefficient)
278 "796FE3825F9DCC85DF22D58690065D93"
279 "898ACD65C087BEA8DA3A63BF4549B795"
280 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
281 "0D74F40DED8E1102C52152A31B6165F8"
282 "3A6722AECFCC35A493D7634664B888A0"
283 "8D3EB034F12EA28BFEE346E205D33482"
284 "7F778B16ED40872BD29FCB36536B6E93"
285 "FFB06778696B4A9D81BB0A9423E63DE5"
286 // } end SEQUENCE (PrivateKey)
287 // } end SEQUENCE (PrivateKeyInfo)
288);
Selene Huange5727e62021-04-13 22:41:20 -0700289
David Drysdaled2cc8c22021-04-15 13:29:45 +0100290string ec_256_key = hex2str(
291 // RFC 5208 s5
292 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
293 "020100" // INTEGER length 1 value 0 (version)
294 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
295 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
296 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
297 "0608" // OBJECT IDENTIFIER length 8 (param)
298 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
299 // } end SEQUENCE (AlgorithmIdentifier)
300 "046d" // OCTET STRING length 0x6d (privateKey) holding...
301 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
302 "020101" // INTEGER length 1 value 1 (version)
303 "0420" // OCTET STRING length 0x20 (privateKey)
304 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
305 "941eed09366bc03299986481f3a4d859"
306 "a144" // TAG [1] len 0x44 (publicKey) {
307 "03420004bf85d7720d07c25461683bc6"
308 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
309 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
310 "bcc41c6eb00083cf3376d11fd44949e0"
311 "b2183bfe"
312 // } end SEQUENCE (ECPrivateKey)
313 // } end SEQUENCE (PrivateKeyInfo)
314);
Selene Huang31ab4042020-04-29 04:22:39 -0700315
David Drysdaled2cc8c22021-04-15 13:29:45 +0100316string ec_521_key = hex2str(
317 // RFC 5208 s5
318 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
319 "020100" // INTEGER length 1 value 0 (version)
320 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
321 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
322 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
323 "0605" // OBJECT IDENTIFIER length 5 (param)
324 "2B81040023" // 1.3.132.0.35 (secp521r1)
325 // } end SEQUENCE (AlgorithmIdentifier)
326 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
327 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
328 "020101" // INTEGER length 1 value 1 (version)
329 "0442" // OCTET STRING length 0x42 (privateKey)
330 "0011458C586DB5DAA92AFAB03F4FE46A"
331 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
332 "9D18D7D08B5BCFA0E53C75B064AD51C4"
333 "49BAE0258D54B94B1E885DED08ED4FB2"
334 "5CE9"
335 "A18189" // TAG [1] len 0x89 (publicKey) {
336 "03818600040149EC11C6DF0FA122C6A9"
337 "AFD9754A4FA9513A627CA329E349535A"
338 "5629875A8ADFBE27DCB932C051986377"
339 "108D054C28C6F39B6F2C9AF81802F9F3"
340 "26B842FF2E5F3C00AB7635CFB36157FC"
341 "0882D574A10D839C1A0C049DC5E0D775"
342 "E2EE50671A208431BB45E78E70BEFE93"
343 "0DB34818EE4D5C26259F5C6B8E28A652"
344 "950F9F88D7B4B2C9D9"
345 // } end SEQUENCE (ECPrivateKey)
346 // } end SEQUENCE (PrivateKeyInfo)
347);
Selene Huang31ab4042020-04-29 04:22:39 -0700348
David Drysdaled2cc8c22021-04-15 13:29:45 +0100349string ec_256_key_rfc5915 = hex2str(
350 // RFC 5208 s5
351 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
352 "020100" // INTEGER length 1 value 0 (version)
353 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
354 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
355 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
356 "0608" // OBJECT IDENTIFIER length 8 (param)
357 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
358 // } end SEQUENCE (AlgorithmIdentifier)
359 "0479" // OCTET STRING length 0x79 (privateKey) holding...
360 // RFC 5915 s3
361 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
362 "020101" // INTEGER length 1 value 1 (version)
363 "0420" // OCTET STRING length 0x42 (privateKey)
364 "782370a8c8ce5537baadd04dcff079c8"
365 "158cfa9c67b818b38e8d21c9fa750c1d"
366 "a00a" // TAG [0] length 0xa (parameters)
367 "0608" // OBJECT IDENTIFIER length 8
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end TAG [0]
370 "a144" // TAG [1] length 0x44 (publicKey) {
371 "0342" // BIT STRING length 0x42
372 "00" // no pad bits
373 "04e2cc561ee701da0ad0ef0d176bb0c9"
374 "19d42e79c393fdc1bd6c4010d85cf2cf"
375 "8e68c905464666f98dad4f01573ba810"
376 "78b3428570a439ba3229fbc026c55068"
377 "2f"
378 // } end SEQUENCE (ECPrivateKey)
379 // } end SEQUENCE (PrivateKeyInfo)
380);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
David Drysdaled2cc8c22021-04-15 13:29:45 +0100382string ec_256_key_sec1 = hex2str(
383 // RFC 5208 s5
384 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
385 "020100" // INTEGER length 1 value 0 (version)
386 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
387 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
388 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
389 "0608" // OBJECT IDENTIFIER length 8 (param)
390 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
391 // } end SEQUENCE (AlgorithmIdentifier)
392 "046d" // OCTET STRING length 0x6d (privateKey) holding...
393 // SEC1-v2 C.4
394 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
395 "020101" // INTEGER length 1 value 0x01 (version)
396 "0420" // OCTET STRING length 0x20 (privateKey)
397 "782370a8c8ce5537baadd04dcff079c8"
398 "158cfa9c67b818b38e8d21c9fa750c1d"
399 "a144" // TAG [1] length 0x44 (publicKey) {
400 "0342" // BIT STRING length 0x42
401 "00" // no pad bits
402 "04e2cc561ee701da0ad0ef0d176bb0c9"
403 "19d42e79c393fdc1bd6c4010d85cf2cf"
404 "8e68c905464666f98dad4f01573ba810"
405 "78b3428570a439ba3229fbc026c55068"
406 "2f"
407 // } end TAG [1] (publicKey)
408 // } end SEQUENCE (PrivateKeyInfo)
409);
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411struct RSA_Delete {
412 void operator()(RSA* p) { RSA_free(p); }
413};
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415std::string make_string(const uint8_t* data, size_t length) {
416 return std::string(reinterpret_cast<const char*>(data), length);
417}
418
419template <size_t N>
420std::string make_string(const uint8_t (&a)[N]) {
421 return make_string(a, N);
422}
423
424class AidlBuf : public vector<uint8_t> {
425 typedef vector<uint8_t> super;
426
427 public:
428 AidlBuf() {}
429 AidlBuf(const super& other) : super(other) {}
430 AidlBuf(super&& other) : super(std::move(other)) {}
431 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
432
433 AidlBuf& operator=(const super& other) {
434 super::operator=(other);
435 return *this;
436 }
437
438 AidlBuf& operator=(super&& other) {
439 super::operator=(std::move(other));
440 return *this;
441 }
442
443 AidlBuf& operator=(const string& other) {
444 resize(other.size());
445 for (size_t i = 0; i < other.size(); ++i) {
446 (*this)[i] = static_cast<uint8_t>(other[i]);
447 }
448 return *this;
449 }
450
451 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
452};
453
David Drysdale4dc01072021-04-01 12:17:35 +0100454string device_suffix(const string& name) {
455 size_t pos = name.find('/');
456 if (pos == string::npos) {
457 return name;
458 }
459 return name.substr(pos + 1);
460}
461
462bool matching_rp_instance(const string& km_name,
463 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
464 string km_suffix = device_suffix(km_name);
465
466 vector<string> rp_names =
467 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
468 for (const string& rp_name : rp_names) {
469 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
470 // KeyMint instance, assume they match.
471 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
472 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
473 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
474 return true;
475 }
476 }
477 return false;
478}
479
Selene Huang31ab4042020-04-29 04:22:39 -0700480} // namespace
481
482class NewKeyGenerationTest : public KeyMintAidlTestBase {
483 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700484 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000485 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700486 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700487
Selene Huang31ab4042020-04-29 04:22:39 -0700488 // Check that some unexpected tags/values are NOT present.
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
490 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 }
492
493 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
494 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
497
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000499 }
500
501 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
502 // TODO(swillden): Distinguish which params should be in which auth list.
503 AuthorizationSet auths;
504 for (auto& entry : keyCharacteristics) {
505 auths.push_back(AuthorizationSet(entry.authorizations));
506 }
507 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
508
509 // Verify that App data, ROT and auth timeout are NOT included.
510 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
511 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700512 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
513
David Drysdaled2cc8c22021-04-15 13:29:45 +0100514 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
515 // never adds it.
516 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
517
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700519 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000520 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700521 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700522 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000523 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700524 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000525
David Drysdalebb3d85e2021-04-13 11:15:51 +0100526 if (check_patchLevels) {
527 // Should include vendor and boot patchlevels.
528 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
529 EXPECT_TRUE(vendor_pl);
530 EXPECT_EQ(*vendor_pl, vendor_patch_level());
531 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
532 EXPECT_TRUE(boot_pl);
533 }
534
David Drysdale7de9feb2021-03-05 14:56:19 +0000535 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700536 }
537};
538
539/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000540 * NewKeyGenerationTest.Aes
541 *
542 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
543 * have correct characteristics.
544 */
545TEST_P(NewKeyGenerationTest, Aes) {
546 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
547 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
548 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
549 SCOPED_TRACE(testing::Message()
550 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
551 vector<uint8_t> key_blob;
552 vector<KeyCharacteristics> key_characteristics;
553 auto builder = AuthorizationSetBuilder()
554 .AesEncryptionKey(key_size)
555 .BlockMode(block_mode)
556 .Padding(padding_mode)
557 .SetDefaultValidity();
558 if (block_mode == BlockMode::GCM) {
559 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
560 }
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
562
563 EXPECT_GT(key_blob.size(), 0U);
564 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100565 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000566
567 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
568
569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
571 << "Key size " << key_size << "missing";
572
573 CheckedDeleteKey(&key_blob);
574 }
575 }
576 }
577}
578
579/*
580 * NewKeyGenerationTest.AesInvalidSize
581 *
582 * Verifies that specifying an invalid key size for AES key generation returns
583 * UNSUPPORTED_KEY_SIZE.
584 */
585TEST_P(NewKeyGenerationTest, AesInvalidSize) {
586 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
587 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
588 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
589 SCOPED_TRACE(testing::Message()
590 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
591 vector<uint8_t> key_blob;
592 vector<KeyCharacteristics> key_characteristics;
593 auto builder = AuthorizationSetBuilder()
594 .AesEncryptionKey(key_size)
595 .BlockMode(block_mode)
596 .Padding(padding_mode)
597 .SetDefaultValidity();
598 if (block_mode == BlockMode::GCM) {
599 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
600 }
601 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
602 GenerateKey(builder, &key_blob, &key_characteristics));
603 }
604 }
605 }
606
607 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
608 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611 // No key size specified
612 auto builder = AuthorizationSetBuilder()
613 .Authorization(TAG_ALGORITHM, Algorithm::AES)
614 .BlockMode(block_mode)
615 .Padding(padding_mode)
616 .SetDefaultValidity();
617 if (block_mode == BlockMode::GCM) {
618 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
619 }
620 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
621 GenerateKey(builder, &key_blob, &key_characteristics));
622 }
623 }
624}
625
626/*
627 * NewKeyGenerationTest.AesInvalidPadding
628 *
629 * Verifies that specifying an invalid padding on AES keys gives a failure
630 * somewhere along the way.
631 */
632TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
633 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
634 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
635 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
636 SCOPED_TRACE(testing::Message()
637 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000638 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 .AesEncryptionKey(key_size)
641 .BlockMode(block_mode)
642 .Padding(padding_mode)
643 .SetDefaultValidity();
644 if (block_mode == BlockMode::GCM) {
645 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
646 }
647
Tommy Chiu3950b452021-05-03 22:01:46 +0800648 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 if (result == ErrorCode::OK) {
650 // Key creation was OK but has generated a key that cannot be used.
651 auto params =
652 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800653 if (block_mode == BlockMode::GCM) {
654 params.Authorization(TAG_MAC_LENGTH, 128);
655 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 auto result = Begin(KeyPurpose::ENCRYPT, params);
657 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100658 result == ErrorCode::INVALID_KEY_BLOB)
659 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000660 } else {
661 // The KeyMint implementation detected that the generated key
662 // is unusable.
663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
664 }
665 }
666 }
667 }
668}
669
670/*
671 * NewKeyGenerationTest.AesGcmMissingMinMac
672 *
673 * Verifies that specifying an invalid key size for AES key generation returns
674 * UNSUPPORTED_KEY_SIZE.
675 */
676TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
677 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
678 BlockMode block_mode = BlockMode::GCM;
679 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
680 SCOPED_TRACE(testing::Message()
681 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
682 vector<uint8_t> key_blob;
683 vector<KeyCharacteristics> key_characteristics;
684 // No MIN_MAC_LENGTH provided.
685 auto builder = AuthorizationSetBuilder()
686 .AesEncryptionKey(key_size)
687 .BlockMode(block_mode)
688 .Padding(padding_mode)
689 .SetDefaultValidity();
690 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
691 GenerateKey(builder, &key_blob, &key_characteristics));
692 }
693 }
694}
695
696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100697 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
698 *
699 * Verifies that specifying an invalid min MAC size for AES key generation returns
700 * UNSUPPORTED_MIN_MAC_LENGTH.
701 */
702TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
703 for (size_t min_mac_len : {88, 136}) {
704 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
705 BlockMode block_mode = BlockMode::GCM;
706 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
707 SCOPED_TRACE(testing::Message()
708 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
709 vector<uint8_t> key_blob;
710 vector<KeyCharacteristics> key_characteristics;
711 auto builder = AuthorizationSetBuilder()
712 .AesEncryptionKey(key_size)
713 .BlockMode(block_mode)
714 .Padding(padding_mode)
715 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
716 .SetDefaultValidity();
717 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
718 GenerateKey(builder, &key_blob, &key_characteristics));
719 }
720 }
721 }
722}
723
724/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000725 * NewKeyGenerationTest.TripleDes
726 *
727 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
728 * have correct characteristics.
729 */
730TEST_P(NewKeyGenerationTest, TripleDes) {
731 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
732 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
733 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
734 SCOPED_TRACE(testing::Message()
735 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
736 vector<uint8_t> key_blob;
737 vector<KeyCharacteristics> key_characteristics;
738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
739 .TripleDesEncryptionKey(key_size)
740 .BlockMode(block_mode)
741 .Padding(padding_mode)
742 .Authorization(TAG_NO_AUTH_REQUIRED)
743 .SetDefaultValidity(),
744 &key_blob, &key_characteristics));
745
746 EXPECT_GT(key_blob.size(), 0U);
747 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100748 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000749
750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
751
752 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
753 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
754 << "Key size " << key_size << "missing";
755
756 CheckedDeleteKey(&key_blob);
757 }
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.TripleDesWithAttestation
764 *
765 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
766 * have correct characteristics.
767 *
768 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
769 * put in a certificate) but which isn't an error.
770 */
771TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
772 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
773 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
774 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
775 SCOPED_TRACE(testing::Message()
776 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
777
778 auto challenge = "hello";
779 auto app_id = "foo";
780
781 vector<uint8_t> key_blob;
782 vector<KeyCharacteristics> key_characteristics;
783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
784 .TripleDesEncryptionKey(key_size)
785 .BlockMode(block_mode)
786 .Padding(padding_mode)
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AttestationChallenge(challenge)
789 .AttestationApplicationId(app_id)
790 .SetDefaultValidity(),
791 &key_blob, &key_characteristics));
792
793 EXPECT_GT(key_blob.size(), 0U);
794 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100795 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000796
797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
798
799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
800 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
801 << "Key size " << key_size << "missing";
802
803 CheckedDeleteKey(&key_blob);
804 }
805 }
806 }
807}
808
809/*
810 * NewKeyGenerationTest.TripleDesInvalidSize
811 *
812 * Verifies that specifying an invalid key size for 3-DES key generation returns
813 * UNSUPPORTED_KEY_SIZE.
814 */
815TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
816 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
817 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
818 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
819 SCOPED_TRACE(testing::Message()
820 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
821 vector<uint8_t> key_blob;
822 vector<KeyCharacteristics> key_characteristics;
823 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
824 GenerateKey(AuthorizationSetBuilder()
825 .TripleDesEncryptionKey(key_size)
826 .BlockMode(block_mode)
827 .Padding(padding_mode)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .SetDefaultValidity(),
830 &key_blob, &key_characteristics));
831 }
832 }
833 }
834
835 // Omitting the key size fails.
836 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
837 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
838 SCOPED_TRACE(testing::Message()
839 << "3DES-default-" << block_mode << "-" << padding_mode);
840 vector<uint8_t> key_blob;
841 vector<KeyCharacteristics> key_characteristics;
842 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
843 GenerateKey(AuthorizationSetBuilder()
844 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
845 .BlockMode(block_mode)
846 .Padding(padding_mode)
847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity(),
849 &key_blob, &key_characteristics));
850 }
851 }
852}
853
854/*
Selene Huang31ab4042020-04-29 04:22:39 -0700855 * NewKeyGenerationTest.Rsa
856 *
857 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
858 * have correct characteristics.
859 */
860TEST_P(NewKeyGenerationTest, Rsa) {
861 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
862 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700863 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
865 .RsaSigningKey(key_size, 65537)
866 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700869 &key_blob, &key_characteristics));
870
871 ASSERT_GT(key_blob.size(), 0U);
872 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100873 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700874
Shawn Willden7f424372021-01-10 18:06:50 -0700875 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
877 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
878 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
879 << "Key size " << key_size << "missing";
880 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
881
882 CheckedDeleteKey(&key_blob);
883 }
884}
885
886/*
Qi Wud22ec842020-11-26 13:27:53 +0800887 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100889 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
890 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891 */
892TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700893 auto challenge = "hello";
894 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700895
Selene Huang6e46f142021-04-20 19:20:11 -0700896 auto subject = "cert subj 2";
897 vector<uint8_t> subject_der(make_name_from_str(subject));
898
899 uint64_t serial_int = 66;
900 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
901
Selene Huang4f64c222021-04-13 19:54:36 -0700902 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700905 ASSERT_EQ(ErrorCode::OK,
906 GenerateKey(AuthorizationSetBuilder()
907 .RsaSigningKey(key_size, 65537)
908 .Digest(Digest::NONE)
909 .Padding(PaddingMode::NONE)
910 .AttestationChallenge(challenge)
911 .AttestationApplicationId(app_id)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
914 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
915 .SetDefaultValidity(),
916 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700917
918 ASSERT_GT(key_blob.size(), 0U);
919 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100920 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700921
922 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
923
924 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
925 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
926 << "Key size " << key_size << "missing";
927 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
928
Selene Huang6e46f142021-04-20 19:20:11 -0700929 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700930 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931 ASSERT_GT(cert_chain_.size(), 0);
932
933 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
934 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
935 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
936 sw_enforced, hw_enforced, SecLevel(),
937 cert_chain_[0].encodedCertificate));
938
939 CheckedDeleteKey(&key_blob);
940 }
941}
942
943/*
David Drysdale4dc01072021-04-01 12:17:35 +0100944 * NewKeyGenerationTest.RsaWithRpkAttestation
945 *
946 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
947 * that has been generated using an associate IRemotelyProvisionedComponent.
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 Drysdale96ad2032021-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 Drysdale96ad2032021-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 Drysdale96ad2032021-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 Drysdale96ad2032021-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 Drysdale96ad2032021-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 Drysdale308916b2021-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 Drysdale308916b2021-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 Drysdale96ad2032021-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 Drysdale308916b2021-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 Drysdale308916b2021-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 Drysdale308916b2021-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 Drysdale96ad2032021-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 Drysdale308916b2021-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 Drysdale92464372021-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 Drysdale308916b2021-06-08 15:46:11 +01001457 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-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 }
Seth Moore3dbdaa92021-07-12 14:18:28 -07001490 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1491 // Tag not required to be supported by all KeyMint implementations.
David Drysdale92464372021-05-14 16:46:59 +01001492 continue;
1493 }
1494 ASSERT_EQ(result, ErrorCode::OK);
1495 ASSERT_GT(key_blob.size(), 0U);
1496
1497 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1498 ASSERT_GT(cert_chain_.size(), 0);
1499 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1500
1501 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1502 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Moore3dbdaa92021-07-12 14:18:28 -07001503 // Some tags are optional, so don't require them to be in the enforcements.
1504 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale92464372021-05-14 16:46:59 +01001505 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1506 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1507 }
1508
1509 // Verifying the attestation record will check for the specific tag because
1510 // it's included in the authorizations.
1511 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1512 SecLevel(), cert_chain_[0].encodedCertificate));
1513
1514 CheckedDeleteKey(&key_blob);
1515 }
1516
1517 // Device attestation IDs should be rejected for normal attestation requests; these fields
1518 // are only used for device unique attestation.
1519 auto invalid_tags = AuthorizationSetBuilder()
1520 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1521 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1522 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1523 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1524 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1525 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1526 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1527 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1528 for (const KeyParameter& tag : invalid_tags) {
1529 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1530 vector<uint8_t> key_blob;
1531 vector<KeyCharacteristics> key_characteristics;
1532 AuthorizationSetBuilder builder =
1533 AuthorizationSetBuilder()
1534 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001535 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001536 .Digest(Digest::NONE)
1537 .AttestationChallenge(challenge)
1538 .AttestationApplicationId(app_id)
1539 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1540 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1541 .SetDefaultValidity();
1542 builder.push_back(tag);
1543 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1544 GenerateKey(builder, &key_blob, &key_characteristics));
1545 }
1546}
1547
1548/*
1549 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1550 *
1551 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1552 */
1553TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1554 auto challenge = "hello";
1555 auto attest_app_id = "foo";
1556 auto subject = "cert subj 2";
1557 vector<uint8_t> subject_der(make_name_from_str(subject));
1558 uint64_t serial_int = 0x1010;
1559 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1560
1561 // Earlier versions of the attestation extension schema included a slot:
1562 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1563 // This should never have been included, and should never be filled in.
1564 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1565 // to confirm that this field never makes it into the attestation extension.
1566 vector<uint8_t> key_blob;
1567 vector<KeyCharacteristics> key_characteristics;
1568 auto result = GenerateKey(AuthorizationSetBuilder()
1569 .Authorization(TAG_NO_AUTH_REQUIRED)
1570 .EcdsaSigningKey(EcCurve::P_256)
1571 .Digest(Digest::NONE)
1572 .AttestationChallenge(challenge)
1573 .AttestationApplicationId(attest_app_id)
1574 .Authorization(TAG_APPLICATION_ID, "client_id")
1575 .Authorization(TAG_APPLICATION_DATA, "appdata")
1576 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1577 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1578 .SetDefaultValidity(),
1579 &key_blob, &key_characteristics);
1580 ASSERT_EQ(result, ErrorCode::OK);
1581 ASSERT_GT(key_blob.size(), 0U);
1582
1583 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1584 ASSERT_GT(cert_chain_.size(), 0);
1585 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1586
1587 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1588 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1589 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1590 SecLevel(), cert_chain_[0].encodedCertificate));
1591
1592 // Check that the app id is not in the cert.
1593 string app_id = "clientid";
1594 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1595 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1596 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1597 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1598 cert_chain_[0].encodedCertificate.end());
1599
1600 CheckedDeleteKey(&key_blob);
1601}
1602
1603/*
Selene Huang4f64c222021-04-13 19:54:36 -07001604 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1605 *
1606 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1607 * the key will generate a self signed attestation.
1608 */
1609TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001610 auto subject = "cert subj 2";
1611 vector<uint8_t> subject_der(make_name_from_str(subject));
1612
1613 uint64_t serial_int = 0x123456FFF1234;
1614 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1615
David Drysdale308916b2021-06-08 15:46:11 +01001616 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001617 vector<uint8_t> key_blob;
1618 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001619 ASSERT_EQ(ErrorCode::OK,
1620 GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001621 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001622 .Digest(Digest::NONE)
1623 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1624 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1625 .SetDefaultValidity(),
1626 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001627 ASSERT_GT(key_blob.size(), 0U);
1628 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001629 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001630
1631 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1632
1633 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001634 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001635
1636 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001637 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001638 ASSERT_EQ(cert_chain_.size(), 1);
1639
1640 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1641 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1642
1643 CheckedDeleteKey(&key_blob);
1644 }
1645}
1646
1647/*
1648 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1649 *
1650 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1651 * app id must also be provided or else it will fail.
1652 */
1653TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1654 auto challenge = "hello";
1655 vector<uint8_t> key_blob;
1656 vector<KeyCharacteristics> key_characteristics;
1657
1658 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1659 GenerateKey(AuthorizationSetBuilder()
1660 .EcdsaSigningKey(EcCurve::P_256)
1661 .Digest(Digest::NONE)
1662 .AttestationChallenge(challenge)
1663 .SetDefaultValidity(),
1664 &key_blob, &key_characteristics));
1665}
1666
1667/*
1668 * NewKeyGenerationTest.EcdsaIgnoreAppId
1669 *
1670 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1671 * any appid will be ignored, and keymint will generate a self sign certificate.
1672 */
1673TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1674 auto app_id = "foo";
1675
David Drysdale308916b2021-06-08 15:46:11 +01001676 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001677 vector<uint8_t> key_blob;
1678 vector<KeyCharacteristics> key_characteristics;
1679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001680 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001681 .Digest(Digest::NONE)
1682 .AttestationApplicationId(app_id)
1683 .SetDefaultValidity(),
1684 &key_blob, &key_characteristics));
1685
1686 ASSERT_GT(key_blob.size(), 0U);
1687 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001688 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001689
1690 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1691
1692 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001693 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001694
1695 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1696 ASSERT_EQ(cert_chain_.size(), 1);
1697
1698 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1699 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1700
1701 CheckedDeleteKey(&key_blob);
1702 }
1703}
1704
1705/*
1706 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1707 *
1708 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1709 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1710 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1711 * to specify how many following bytes will be used to encode the length.
1712 */
1713TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1714 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001715 std::vector<uint32_t> app_id_lengths{143, 258};
1716
1717 for (uint32_t length : app_id_lengths) {
1718 const string app_id(length, 'a');
1719 vector<uint8_t> key_blob;
1720 vector<KeyCharacteristics> key_characteristics;
1721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1722 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001723 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001724 .Digest(Digest::NONE)
1725 .AttestationChallenge(challenge)
1726 .AttestationApplicationId(app_id)
1727 .SetDefaultValidity(),
1728 &key_blob, &key_characteristics));
1729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001731 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001732
1733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001737
1738 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1739 ASSERT_GT(cert_chain_.size(), 0);
1740
1741 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1742 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1743 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1744 sw_enforced, hw_enforced, SecLevel(),
1745 cert_chain_[0].encodedCertificate));
1746
1747 CheckedDeleteKey(&key_blob);
1748 }
1749}
1750
1751/*
Qi Wud22ec842020-11-26 13:27:53 +08001752 * NewKeyGenerationTest.LimitedUsageEcdsa
1753 *
1754 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1755 * resulting keys have correct characteristics.
1756 */
1757TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001758 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001759 vector<uint8_t> key_blob;
1760 vector<KeyCharacteristics> key_characteristics;
1761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001762 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001763 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001764 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1765 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001766 &key_blob, &key_characteristics));
1767
1768 ASSERT_GT(key_blob.size(), 0U);
1769 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001770 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001771
1772 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1773
1774 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001775 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001776
1777 // Check the usage count limit tag appears in the authorizations.
1778 AuthorizationSet auths;
1779 for (auto& entry : key_characteristics) {
1780 auths.push_back(AuthorizationSet(entry.authorizations));
1781 }
1782 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1783 << "key usage count limit " << 1U << " missing";
1784
1785 CheckedDeleteKey(&key_blob);
1786 }
1787}
1788
1789/*
Selene Huang31ab4042020-04-29 04:22:39 -07001790 * NewKeyGenerationTest.EcdsaDefaultSize
1791 *
David Drysdale308916b2021-06-08 15:46:11 +01001792 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001793 * UNSUPPORTED_KEY_SIZE.
1794 */
1795TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1796 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1797 GenerateKey(AuthorizationSetBuilder()
1798 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1799 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001800 .Digest(Digest::NONE)
1801 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001802}
1803
1804/*
1805 * NewKeyGenerationTest.EcdsaInvalidSize
1806 *
1807 * Verifies that specifying an invalid key size for EC key generation returns
1808 * UNSUPPORTED_KEY_SIZE.
1809 */
1810TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdale308916b2021-06-08 15:46:11 +01001811 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001812 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001813 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001814 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001815 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001816 .Digest(Digest::NONE)
1817 .SetDefaultValidity(),
1818 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001819 }
1820
David Drysdale308916b2021-06-08 15:46:11 +01001821 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1822 GenerateKey(AuthorizationSetBuilder()
1823 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1824 .Authorization(TAG_KEY_SIZE, 190)
1825 .SigningKey()
1826 .Digest(Digest::NONE)
1827 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001828}
1829
1830/*
1831 * NewKeyGenerationTest.EcdsaMismatchKeySize
1832 *
1833 * Verifies that specifying mismatched key size and curve for EC key generation returns
1834 * INVALID_ARGUMENT.
1835 */
1836TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1837 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1838
David Drysdale308916b2021-06-08 15:46:11 +01001839 auto result = GenerateKey(AuthorizationSetBuilder()
1840 .Authorization(TAG_KEY_SIZE, 224)
1841 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1842 .Digest(Digest::NONE)
1843 .SetDefaultValidity());
1844 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT ||
1845 result == ErrorCode::UNSUPPORTED_ALGORITHM);
Selene Huang31ab4042020-04-29 04:22:39 -07001846}
1847
1848/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001849 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001850 *
1851 * Verifies that keymint does not support any curve designated as unsupported.
1852 */
1853TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1854 Digest digest;
1855 if (SecLevel() == SecurityLevel::STRONGBOX) {
1856 digest = Digest::SHA_2_256;
1857 } else {
1858 digest = Digest::SHA_2_512;
1859 }
1860 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001861 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1862 .EcdsaSigningKey(curve)
1863 .Digest(digest)
1864 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001865 << "Failed to generate key on curve: " << curve;
1866 CheckedDeleteKey();
1867 }
1868}
1869
1870/*
1871 * NewKeyGenerationTest.Hmac
1872 *
1873 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1874 * characteristics.
1875 */
1876TEST_P(NewKeyGenerationTest, Hmac) {
1877 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1878 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001879 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001880 constexpr size_t key_size = 128;
1881 ASSERT_EQ(ErrorCode::OK,
1882 GenerateKey(
1883 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1884 TAG_MIN_MAC_LENGTH, 128),
1885 &key_blob, &key_characteristics));
1886
1887 ASSERT_GT(key_blob.size(), 0U);
1888 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001889 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001890
Shawn Willden7f424372021-01-10 18:06:50 -07001891 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1892 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1893 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1894 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001895
1896 CheckedDeleteKey(&key_blob);
1897 }
1898}
1899
1900/*
Selene Huang4f64c222021-04-13 19:54:36 -07001901 * NewKeyGenerationTest.HmacNoAttestation
1902 *
1903 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1904 * and app id are provided.
1905 */
1906TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1907 auto challenge = "hello";
1908 auto app_id = "foo";
1909
1910 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1911 vector<uint8_t> key_blob;
1912 vector<KeyCharacteristics> key_characteristics;
1913 constexpr size_t key_size = 128;
1914 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1915 .HmacKey(key_size)
1916 .Digest(digest)
1917 .AttestationChallenge(challenge)
1918 .AttestationApplicationId(app_id)
1919 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1920 &key_blob, &key_characteristics));
1921
1922 ASSERT_GT(key_blob.size(), 0U);
1923 ASSERT_EQ(cert_chain_.size(), 0);
1924 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001925 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001926
1927 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1928 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1929 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1930 << "Key size " << key_size << "missing";
1931
1932 CheckedDeleteKey(&key_blob);
1933 }
1934}
1935
1936/*
Qi Wud22ec842020-11-26 13:27:53 +08001937 * NewKeyGenerationTest.LimitedUsageHmac
1938 *
1939 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1940 * resulting keys have correct characteristics.
1941 */
1942TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1943 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1944 vector<uint8_t> key_blob;
1945 vector<KeyCharacteristics> key_characteristics;
1946 constexpr size_t key_size = 128;
1947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1948 .HmacKey(key_size)
1949 .Digest(digest)
1950 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1951 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1952 &key_blob, &key_characteristics));
1953
1954 ASSERT_GT(key_blob.size(), 0U);
1955 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001956 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001957
1958 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1959 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1960 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1961 << "Key size " << key_size << "missing";
1962
1963 // Check the usage count limit tag appears in the authorizations.
1964 AuthorizationSet auths;
1965 for (auto& entry : key_characteristics) {
1966 auths.push_back(AuthorizationSet(entry.authorizations));
1967 }
1968 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1969 << "key usage count limit " << 1U << " missing";
1970
1971 CheckedDeleteKey(&key_blob);
1972 }
1973}
1974
1975/*
Selene Huang31ab4042020-04-29 04:22:39 -07001976 * NewKeyGenerationTest.HmacCheckKeySizes
1977 *
1978 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1979 */
1980TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1981 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1982 if (key_size < 64 || key_size % 8 != 0) {
1983 // To keep this test from being very slow, we only test a random fraction of
1984 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1985 // them, we expect to run ~40 of them in each run.
1986 if (key_size % 8 == 0 || random() % 10 == 0) {
1987 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1988 GenerateKey(AuthorizationSetBuilder()
1989 .HmacKey(key_size)
1990 .Digest(Digest::SHA_2_256)
1991 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1992 << "HMAC key size " << key_size << " invalid";
1993 }
1994 } else {
1995 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1996 .HmacKey(key_size)
1997 .Digest(Digest::SHA_2_256)
1998 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1999 << "Failed to generate HMAC key of size " << key_size;
2000 CheckedDeleteKey();
2001 }
2002 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002003 if (SecLevel() == SecurityLevel::STRONGBOX) {
2004 // STRONGBOX devices must not support keys larger than 512 bits.
2005 size_t key_size = 520;
2006 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2007 GenerateKey(AuthorizationSetBuilder()
2008 .HmacKey(key_size)
2009 .Digest(Digest::SHA_2_256)
2010 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2011 << "HMAC key size " << key_size << " unexpectedly valid";
2012 }
Selene Huang31ab4042020-04-29 04:22:39 -07002013}
2014
2015/*
2016 * NewKeyGenerationTest.HmacCheckMinMacLengths
2017 *
2018 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2019 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2020 * specific MAC length that failed, so reproducing a failed run will be easy.
2021 */
2022TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2023 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2024 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2025 // To keep this test from being very long, we only test a random fraction of
2026 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2027 // we expect to run ~17 of them in each run.
2028 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2029 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2030 GenerateKey(AuthorizationSetBuilder()
2031 .HmacKey(128)
2032 .Digest(Digest::SHA_2_256)
2033 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2034 << "HMAC min mac length " << min_mac_length << " invalid.";
2035 }
2036 } else {
2037 EXPECT_EQ(ErrorCode::OK,
2038 GenerateKey(AuthorizationSetBuilder()
2039 .HmacKey(128)
2040 .Digest(Digest::SHA_2_256)
2041 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2042 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2043 CheckedDeleteKey();
2044 }
2045 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002046
2047 // Minimum MAC length must be no more than 512 bits.
2048 size_t min_mac_length = 520;
2049 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2050 GenerateKey(AuthorizationSetBuilder()
2051 .HmacKey(128)
2052 .Digest(Digest::SHA_2_256)
2053 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2054 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002055}
2056
2057/*
2058 * NewKeyGenerationTest.HmacMultipleDigests
2059 *
2060 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2061 */
2062TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2063 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2064
2065 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2066 GenerateKey(AuthorizationSetBuilder()
2067 .HmacKey(128)
2068 .Digest(Digest::SHA1)
2069 .Digest(Digest::SHA_2_256)
2070 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2071}
2072
2073/*
2074 * NewKeyGenerationTest.HmacDigestNone
2075 *
2076 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2077 */
2078TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2079 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2080 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2081 128)));
2082
2083 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2084 GenerateKey(AuthorizationSetBuilder()
2085 .HmacKey(128)
2086 .Digest(Digest::NONE)
2087 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2088}
2089
Selene Huang4f64c222021-04-13 19:54:36 -07002090/*
2091 * NewKeyGenerationTest.AesNoAttestation
2092 *
2093 * Verifies that attestation parameters to AES keys are ignored and generateKey
2094 * will succeed.
2095 */
2096TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2097 auto challenge = "hello";
2098 auto app_id = "foo";
2099
2100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2101 .Authorization(TAG_NO_AUTH_REQUIRED)
2102 .AesEncryptionKey(128)
2103 .EcbMode()
2104 .Padding(PaddingMode::PKCS7)
2105 .AttestationChallenge(challenge)
2106 .AttestationApplicationId(app_id)));
2107
2108 ASSERT_EQ(cert_chain_.size(), 0);
2109}
2110
2111/*
2112 * NewKeyGenerationTest.TripleDesNoAttestation
2113 *
2114 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2115 * will be successful. No attestation should be generated.
2116 */
2117TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2118 auto challenge = "hello";
2119 auto app_id = "foo";
2120
2121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2122 .TripleDesEncryptionKey(168)
2123 .BlockMode(BlockMode::ECB)
2124 .Authorization(TAG_NO_AUTH_REQUIRED)
2125 .Padding(PaddingMode::NONE)
2126 .AttestationChallenge(challenge)
2127 .AttestationApplicationId(app_id)));
2128 ASSERT_EQ(cert_chain_.size(), 0);
2129}
2130
Selene Huang31ab4042020-04-29 04:22:39 -07002131INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2132
2133typedef KeyMintAidlTestBase SigningOperationsTest;
2134
2135/*
2136 * SigningOperationsTest.RsaSuccess
2137 *
2138 * Verifies that raw RSA signature operations succeed.
2139 */
2140TEST_P(SigningOperationsTest, RsaSuccess) {
2141 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2142 .RsaSigningKey(2048, 65537)
2143 .Digest(Digest::NONE)
2144 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002145 .Authorization(TAG_NO_AUTH_REQUIRED)
2146 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002147 string message = "12345678901234567890123456789012";
2148 string signature = SignMessage(
2149 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdalefe42aa32021-05-06 08:10:58 +01002150 LocalVerifyMessage(message, signature,
2151 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2152}
2153
2154/*
2155 * SigningOperationsTest.RsaAllPaddingsAndDigests
2156 *
2157 * Verifies RSA signature/verification for all padding modes and digests.
2158 */
2159TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2160 auto authorizations = AuthorizationSetBuilder()
2161 .Authorization(TAG_NO_AUTH_REQUIRED)
2162 .RsaSigningKey(2048, 65537)
2163 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2164 .Padding(PaddingMode::NONE)
2165 .Padding(PaddingMode::RSA_PSS)
2166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2167 .SetDefaultValidity();
2168
2169 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2170
2171 string message(128, 'a');
2172 string corrupt_message(message);
2173 ++corrupt_message[corrupt_message.size() / 2];
2174
2175 for (auto padding :
2176 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2177 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2178 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2179 // Digesting only makes sense with padding.
2180 continue;
2181 }
2182
2183 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2184 // PSS requires digesting.
2185 continue;
2186 }
2187
2188 string signature =
2189 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2190 LocalVerifyMessage(message, signature,
2191 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2192 }
2193 }
Selene Huang31ab4042020-04-29 04:22:39 -07002194}
2195
2196/*
2197 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2198 *
Shawn Willden7f424372021-01-10 18:06:50 -07002199 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002200 */
2201TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2202 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2203 .Authorization(TAG_NO_AUTH_REQUIRED)
2204 .RsaSigningKey(2048, 65537)
2205 .Digest(Digest::NONE)
2206 .Padding(PaddingMode::NONE)
2207 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002208 .Authorization(TAG_APPLICATION_DATA, "appdata")
2209 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002210
2211 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2212
Selene Huang31ab4042020-04-29 04:22:39 -07002213 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2214 Begin(KeyPurpose::SIGN,
2215 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2216 AbortIfNeeded();
2217 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2218 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2219 .Digest(Digest::NONE)
2220 .Padding(PaddingMode::NONE)
2221 .Authorization(TAG_APPLICATION_ID, "clientid")));
2222 AbortIfNeeded();
2223 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2224 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2225 .Digest(Digest::NONE)
2226 .Padding(PaddingMode::NONE)
2227 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2228 AbortIfNeeded();
2229 EXPECT_EQ(ErrorCode::OK,
2230 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2231 .Digest(Digest::NONE)
2232 .Padding(PaddingMode::NONE)
2233 .Authorization(TAG_APPLICATION_DATA, "appdata")
2234 .Authorization(TAG_APPLICATION_ID, "clientid")));
2235 AbortIfNeeded();
2236}
2237
2238/*
2239 * SigningOperationsTest.RsaPssSha256Success
2240 *
2241 * Verifies that RSA-PSS signature operations succeed.
2242 */
2243TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2244 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2245 .RsaSigningKey(2048, 65537)
2246 .Digest(Digest::SHA_2_256)
2247 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002248 .Authorization(TAG_NO_AUTH_REQUIRED)
2249 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002250 // Use large message, which won't work without digesting.
2251 string message(1024, 'a');
2252 string signature = SignMessage(
2253 message,
2254 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2255}
2256
2257/*
2258 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2259 *
2260 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2261 * supports only unpadded operations.
2262 */
2263TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2264 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2265 .RsaSigningKey(2048, 65537)
2266 .Digest(Digest::NONE)
2267 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002268 .Padding(PaddingMode::NONE)
2269 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002270 string message = "12345678901234567890123456789012";
2271 string signature;
2272
2273 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2274 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2275 .Digest(Digest::NONE)
2276 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2277}
2278
2279/*
2280 * SigningOperationsTest.NoUserConfirmation
2281 *
2282 * Verifies that keymint rejects signing operations for keys with
2283 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2284 * presented.
2285 */
2286TEST_P(SigningOperationsTest, NoUserConfirmation) {
2287 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2289 .RsaSigningKey(1024, 65537)
2290 .Digest(Digest::NONE)
2291 .Padding(PaddingMode::NONE)
2292 .Authorization(TAG_NO_AUTH_REQUIRED)
2293 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2294 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002295
2296 const string message = "12345678901234567890123456789012";
2297 EXPECT_EQ(ErrorCode::OK,
2298 Begin(KeyPurpose::SIGN,
2299 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2300 string signature;
2301 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2302}
2303
2304/*
2305 * SigningOperationsTest.RsaPkcs1Sha256Success
2306 *
2307 * Verifies that digested RSA-PKCS1 signature operations succeed.
2308 */
2309TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2311 .RsaSigningKey(2048, 65537)
2312 .Digest(Digest::SHA_2_256)
2313 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002314 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2315 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002316 string message(1024, 'a');
2317 string signature = SignMessage(message, AuthorizationSetBuilder()
2318 .Digest(Digest::SHA_2_256)
2319 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2320}
2321
2322/*
2323 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2324 *
2325 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2326 */
2327TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2328 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2329 .RsaSigningKey(2048, 65537)
2330 .Digest(Digest::NONE)
2331 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002332 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2333 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002334 string message(53, 'a');
2335 string signature = SignMessage(message, AuthorizationSetBuilder()
2336 .Digest(Digest::NONE)
2337 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2338}
2339
2340/*
2341 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2342 *
2343 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2344 * given a too-long message.
2345 */
2346TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2347 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2348 .RsaSigningKey(2048, 65537)
2349 .Digest(Digest::NONE)
2350 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002351 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2352 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002353 string message(257, 'a');
2354
2355 EXPECT_EQ(ErrorCode::OK,
2356 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2357 .Digest(Digest::NONE)
2358 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2359 string signature;
2360 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2361}
2362
2363/*
2364 * SigningOperationsTest.RsaPssSha512TooSmallKey
2365 *
2366 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2367 * used with a key that is too small for the message.
2368 *
2369 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2370 * keymint specification requires that salt_size == digest_size, so the message will be
2371 * digest_size * 2 +
2372 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2373 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2374 * for a 1024-bit key.
2375 */
2376TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2377 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2379 .RsaSigningKey(1024, 65537)
2380 .Digest(Digest::SHA_2_512)
2381 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002382 .Padding(PaddingMode::RSA_PSS)
2383 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002384 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2385 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2386 .Digest(Digest::SHA_2_512)
2387 .Padding(PaddingMode::RSA_PSS)));
2388}
2389
2390/*
2391 * SigningOperationsTest.RsaNoPaddingTooLong
2392 *
2393 * Verifies that raw RSA signature operations fail with the correct error code when
2394 * given a too-long message.
2395 */
2396TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2398 .RsaSigningKey(2048, 65537)
2399 .Digest(Digest::NONE)
2400 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002401 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2402 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002403 // One byte too long
2404 string message(2048 / 8 + 1, 'a');
2405 ASSERT_EQ(ErrorCode::OK,
2406 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2407 .Digest(Digest::NONE)
2408 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2409 string result;
2410 ErrorCode finish_error_code = Finish(message, &result);
2411 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2412 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2413
2414 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2415 message = string(128 * 1024, 'a');
2416 ASSERT_EQ(ErrorCode::OK,
2417 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2418 .Digest(Digest::NONE)
2419 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2420 finish_error_code = Finish(message, &result);
2421 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2422 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2423}
2424
2425/*
2426 * SigningOperationsTest.RsaAbort
2427 *
2428 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2429 * test, but the behavior should be algorithm and purpose-independent.
2430 */
2431TEST_P(SigningOperationsTest, RsaAbort) {
2432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2433 .RsaSigningKey(2048, 65537)
2434 .Digest(Digest::NONE)
2435 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002436 .Padding(PaddingMode::NONE)
2437 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002438
2439 ASSERT_EQ(ErrorCode::OK,
2440 Begin(KeyPurpose::SIGN,
2441 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2442 EXPECT_EQ(ErrorCode::OK, Abort());
2443
2444 // Another abort should fail
2445 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2446
2447 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002448 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002449}
2450
2451/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002452 * SigningOperationsTest.RsaNonUniqueParams
2453 *
2454 * Verifies that an operation with multiple padding modes is rejected.
2455 */
2456TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2457 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2458 .RsaSigningKey(2048, 65537)
2459 .Digest(Digest::NONE)
2460 .Digest(Digest::SHA1)
2461 .Authorization(TAG_NO_AUTH_REQUIRED)
2462 .Padding(PaddingMode::NONE)
2463 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2464 .SetDefaultValidity()));
2465
2466 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2467 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2468 .Digest(Digest::NONE)
2469 .Padding(PaddingMode::NONE)
2470 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2471
Tommy Chiu3b56cbc2021-05-11 18:36:50 +08002472 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2473 .Digest(Digest::NONE)
2474 .Digest(Digest::SHA1)
2475 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2476 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002477
2478 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2479 Begin(KeyPurpose::SIGN,
2480 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2481}
2482
2483/*
Selene Huang31ab4042020-04-29 04:22:39 -07002484 * SigningOperationsTest.RsaUnsupportedPadding
2485 *
2486 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2487 * with a padding mode inappropriate for RSA.
2488 */
2489TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2491 .RsaSigningKey(2048, 65537)
2492 .Authorization(TAG_NO_AUTH_REQUIRED)
2493 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002494 .Padding(PaddingMode::PKCS7)
2495 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002496 ASSERT_EQ(
2497 ErrorCode::UNSUPPORTED_PADDING_MODE,
2498 Begin(KeyPurpose::SIGN,
2499 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002500 CheckedDeleteKey();
2501
2502 ASSERT_EQ(ErrorCode::OK,
2503 GenerateKey(
2504 AuthorizationSetBuilder()
2505 .RsaSigningKey(2048, 65537)
2506 .Authorization(TAG_NO_AUTH_REQUIRED)
2507 .Digest(Digest::SHA_2_256 /* supported digest */)
2508 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2509 .SetDefaultValidity()));
2510 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2511 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2512 .Digest(Digest::SHA_2_256)
2513 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002514}
2515
2516/*
2517 * SigningOperationsTest.RsaPssNoDigest
2518 *
2519 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2520 */
2521TEST_P(SigningOperationsTest, RsaNoDigest) {
2522 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2523 .RsaSigningKey(2048, 65537)
2524 .Authorization(TAG_NO_AUTH_REQUIRED)
2525 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002526 .Padding(PaddingMode::RSA_PSS)
2527 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002528 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2529 Begin(KeyPurpose::SIGN,
2530 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2531
2532 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2533 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2534}
2535
2536/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002537 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002538 *
2539 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2540 * supported in some cases (as validated in other tests), but a mode must be specified.
2541 */
2542TEST_P(SigningOperationsTest, RsaNoPadding) {
2543 // Padding must be specified
2544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2545 .RsaKey(2048, 65537)
2546 .Authorization(TAG_NO_AUTH_REQUIRED)
2547 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002548 .Digest(Digest::NONE)
2549 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002550 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2551 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2552}
2553
2554/*
2555 * SigningOperationsTest.RsaShortMessage
2556 *
2557 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2558 */
2559TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2561 .Authorization(TAG_NO_AUTH_REQUIRED)
2562 .RsaSigningKey(2048, 65537)
2563 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002564 .Padding(PaddingMode::NONE)
2565 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002566
2567 // Barely shorter
2568 string message(2048 / 8 - 1, 'a');
2569 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2570
2571 // Much shorter
2572 message = "a";
2573 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2574}
2575
2576/*
2577 * SigningOperationsTest.RsaSignWithEncryptionKey
2578 *
2579 * Verifies that RSA encryption keys cannot be used to sign.
2580 */
2581TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2583 .Authorization(TAG_NO_AUTH_REQUIRED)
2584 .RsaEncryptionKey(2048, 65537)
2585 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002586 .Padding(PaddingMode::NONE)
2587 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002588 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2589 Begin(KeyPurpose::SIGN,
2590 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2591}
2592
2593/*
2594 * SigningOperationsTest.RsaSignTooLargeMessage
2595 *
2596 * Verifies that attempting a raw signature of a message which is the same length as the key,
2597 * but numerically larger than the public modulus, fails with the correct error.
2598 */
2599TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2600 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2601 .Authorization(TAG_NO_AUTH_REQUIRED)
2602 .RsaSigningKey(2048, 65537)
2603 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002604 .Padding(PaddingMode::NONE)
2605 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002606
2607 // Largest possible message will always be larger than the public modulus.
2608 string message(2048 / 8, static_cast<char>(0xff));
2609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2610 .Authorization(TAG_NO_AUTH_REQUIRED)
2611 .Digest(Digest::NONE)
2612 .Padding(PaddingMode::NONE)));
2613 string signature;
2614 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2615}
2616
2617/*
David Drysdalefe42aa32021-05-06 08:10:58 +01002618 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2619 *
2620 * Verifies ECDSA signature/verification for all digests and curves.
2621 */
2622TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2623 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2624
2625 string message = "1234567890";
2626 string corrupt_message = "2234567890";
2627 for (auto curve : ValidCurves()) {
2628 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2629 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2630 .Authorization(TAG_NO_AUTH_REQUIRED)
2631 .EcdsaSigningKey(curve)
2632 .Digest(digests)
2633 .SetDefaultValidity());
2634 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2635 if (error != ErrorCode::OK) {
2636 continue;
2637 }
2638
2639 for (auto digest : digests) {
2640 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2641 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2642 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2643 }
2644
2645 auto rc = DeleteKey();
2646 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2647 }
2648}
2649
2650/*
Selene Huang31ab4042020-04-29 04:22:39 -07002651 * SigningOperationsTest.EcdsaAllCurves
2652 *
2653 * Verifies that ECDSA operations succeed with all possible curves.
2654 */
2655TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2656 for (auto curve : ValidCurves()) {
2657 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2658 .Authorization(TAG_NO_AUTH_REQUIRED)
2659 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002660 .Digest(Digest::SHA_2_256)
2661 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002662 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2663 if (error != ErrorCode::OK) continue;
2664
2665 string message(1024, 'a');
2666 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2667 CheckedDeleteKey();
2668 }
2669}
2670
2671/*
2672 * SigningOperationsTest.EcdsaNoDigestHugeData
2673 *
2674 * Verifies that ECDSA operations support very large messages, even without digesting. This
2675 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2676 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2677 * the framework.
2678 */
2679TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2681 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002682 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002683 .Digest(Digest::NONE)
2684 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002685 string message(1 * 1024, 'a');
2686 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2687}
2688
2689/*
2690 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2691 *
2692 * Verifies that using an EC key requires the correct app ID/data.
2693 */
2694TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2696 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002697 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002698 .Digest(Digest::NONE)
2699 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002700 .Authorization(TAG_APPLICATION_DATA, "appdata")
2701 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002702
2703 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2704
Selene Huang31ab4042020-04-29 04:22:39 -07002705 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2706 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2707 AbortIfNeeded();
2708 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2709 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2710 .Digest(Digest::NONE)
2711 .Authorization(TAG_APPLICATION_ID, "clientid")));
2712 AbortIfNeeded();
2713 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2714 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2715 .Digest(Digest::NONE)
2716 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2717 AbortIfNeeded();
2718 EXPECT_EQ(ErrorCode::OK,
2719 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2720 .Digest(Digest::NONE)
2721 .Authorization(TAG_APPLICATION_DATA, "appdata")
2722 .Authorization(TAG_APPLICATION_ID, "clientid")));
2723 AbortIfNeeded();
2724}
2725
2726/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002727 * SigningOperationsTest.EcdsaIncompatibleDigest
2728 *
2729 * Verifies that using an EC key requires compatible digest.
2730 */
2731TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002734 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002735 .Digest(Digest::NONE)
2736 .Digest(Digest::SHA1)
2737 .SetDefaultValidity()));
2738 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2739 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2740 AbortIfNeeded();
2741}
2742
2743/*
Selene Huang31ab4042020-04-29 04:22:39 -07002744 * SigningOperationsTest.AesEcbSign
2745 *
2746 * Verifies that attempts to use AES keys to sign fail in the correct way.
2747 */
2748TEST_P(SigningOperationsTest, AesEcbSign) {
2749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2750 .Authorization(TAG_NO_AUTH_REQUIRED)
2751 .SigningKey()
2752 .AesEncryptionKey(128)
2753 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2754
2755 AuthorizationSet out_params;
2756 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2757 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2758 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2759 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2760}
2761
2762/*
2763 * SigningOperationsTest.HmacAllDigests
2764 *
2765 * Verifies that HMAC works with all digests.
2766 */
2767TEST_P(SigningOperationsTest, HmacAllDigests) {
2768 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2770 .Authorization(TAG_NO_AUTH_REQUIRED)
2771 .HmacKey(128)
2772 .Digest(digest)
2773 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2774 << "Failed to create HMAC key with digest " << digest;
2775 string message = "12345678901234567890123456789012";
2776 string signature = MacMessage(message, digest, 160);
2777 EXPECT_EQ(160U / 8U, signature.size())
2778 << "Failed to sign with HMAC key with digest " << digest;
2779 CheckedDeleteKey();
2780 }
2781}
2782
2783/*
2784 * SigningOperationsTest.HmacSha256TooLargeMacLength
2785 *
2786 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2787 * digest size.
2788 */
2789TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2790 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2791 .Authorization(TAG_NO_AUTH_REQUIRED)
2792 .HmacKey(128)
2793 .Digest(Digest::SHA_2_256)
2794 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2795 AuthorizationSet output_params;
2796 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2797 AuthorizationSetBuilder()
2798 .Digest(Digest::SHA_2_256)
2799 .Authorization(TAG_MAC_LENGTH, 264),
2800 &output_params));
2801}
2802
2803/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002804 * SigningOperationsTest.HmacSha256InvalidMacLength
2805 *
2806 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2807 * not a multiple of 8.
2808 */
2809TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2811 .Authorization(TAG_NO_AUTH_REQUIRED)
2812 .HmacKey(128)
2813 .Digest(Digest::SHA_2_256)
2814 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2815 AuthorizationSet output_params;
2816 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2817 AuthorizationSetBuilder()
2818 .Digest(Digest::SHA_2_256)
2819 .Authorization(TAG_MAC_LENGTH, 161),
2820 &output_params));
2821}
2822
2823/*
Selene Huang31ab4042020-04-29 04:22:39 -07002824 * SigningOperationsTest.HmacSha256TooSmallMacLength
2825 *
2826 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2827 * specified minimum MAC length.
2828 */
2829TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2830 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2831 .Authorization(TAG_NO_AUTH_REQUIRED)
2832 .HmacKey(128)
2833 .Digest(Digest::SHA_2_256)
2834 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2835 AuthorizationSet output_params;
2836 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2837 AuthorizationSetBuilder()
2838 .Digest(Digest::SHA_2_256)
2839 .Authorization(TAG_MAC_LENGTH, 120),
2840 &output_params));
2841}
2842
2843/*
2844 * SigningOperationsTest.HmacRfc4231TestCase3
2845 *
2846 * Validates against the test vectors from RFC 4231 test case 3.
2847 */
2848TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2849 string key(20, 0xaa);
2850 string message(50, 0xdd);
2851 uint8_t sha_224_expected[] = {
2852 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2853 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2854 };
2855 uint8_t sha_256_expected[] = {
2856 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2857 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2858 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2859 };
2860 uint8_t sha_384_expected[] = {
2861 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2862 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2863 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2864 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2865 };
2866 uint8_t sha_512_expected[] = {
2867 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2868 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2869 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2870 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2871 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2872 };
2873
2874 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2875 if (SecLevel() != SecurityLevel::STRONGBOX) {
2876 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2877 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2878 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2879 }
2880}
2881
2882/*
2883 * SigningOperationsTest.HmacRfc4231TestCase5
2884 *
2885 * Validates against the test vectors from RFC 4231 test case 5.
2886 */
2887TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2888 string key(20, 0x0c);
2889 string message = "Test With Truncation";
2890
2891 uint8_t sha_224_expected[] = {
2892 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2893 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2894 };
2895 uint8_t sha_256_expected[] = {
2896 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2897 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2898 };
2899 uint8_t sha_384_expected[] = {
2900 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2901 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2902 };
2903 uint8_t sha_512_expected[] = {
2904 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2905 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2906 };
2907
2908 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2909 if (SecLevel() != SecurityLevel::STRONGBOX) {
2910 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2911 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2912 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2913 }
2914}
2915
2916INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2917
2918typedef KeyMintAidlTestBase VerificationOperationsTest;
2919
2920/*
Selene Huang31ab4042020-04-29 04:22:39 -07002921 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2922 *
2923 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2924 */
2925TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2926 string key_material = "HelloThisIsAKey";
2927
2928 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002929 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002930 EXPECT_EQ(ErrorCode::OK,
2931 ImportKey(AuthorizationSetBuilder()
2932 .Authorization(TAG_NO_AUTH_REQUIRED)
2933 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2934 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2935 .Digest(Digest::SHA_2_256)
2936 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2937 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2938 EXPECT_EQ(ErrorCode::OK,
2939 ImportKey(AuthorizationSetBuilder()
2940 .Authorization(TAG_NO_AUTH_REQUIRED)
2941 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2942 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2943 .Digest(Digest::SHA_2_256)
2944 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2945 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2946
2947 string message = "This is a message.";
2948 string signature = SignMessage(
2949 signing_key, message,
2950 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2951
2952 // Signing key should not work.
2953 AuthorizationSet out_params;
2954 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2955 Begin(KeyPurpose::VERIFY, signing_key,
2956 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2957
2958 // Verification key should work.
2959 VerifyMessage(verification_key, message, signature,
2960 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2961
2962 CheckedDeleteKey(&signing_key);
2963 CheckedDeleteKey(&verification_key);
2964}
2965
2966INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2967
2968typedef KeyMintAidlTestBase ExportKeyTest;
2969
2970/*
2971 * ExportKeyTest.RsaUnsupportedKeyFormat
2972 *
2973 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2974 */
2975// TODO(seleneh) add ExportKey to GenerateKey
2976// check result
2977
2978class ImportKeyTest : public KeyMintAidlTestBase {
2979 public:
2980 template <TagType tag_type, Tag tag, typename ValueT>
2981 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2982 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002983 for (auto& entry : key_characteristics_) {
2984 if (entry.securityLevel == SecLevel()) {
2985 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2986 << "Tag " << tag << " with value " << expected
2987 << " not found at security level" << entry.securityLevel;
2988 } else {
2989 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2990 << "Tag " << tag << " found at security level " << entry.securityLevel;
2991 }
Selene Huang31ab4042020-04-29 04:22:39 -07002992 }
2993 }
2994
2995 void CheckOrigin() {
2996 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002997 // Origin isn't a crypto param, but it always lives with them.
2998 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002999 }
3000};
3001
3002/*
3003 * ImportKeyTest.RsaSuccess
3004 *
3005 * Verifies that importing and using an RSA key pair works correctly.
3006 */
3007TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003008 uint32_t key_size;
3009 string key;
3010
3011 if (SecLevel() == SecurityLevel::STRONGBOX) {
3012 key_size = 2048;
3013 key = rsa_2048_key;
3014 } else {
3015 key_size = 1024;
3016 key = rsa_key;
3017 }
3018
Selene Huang31ab4042020-04-29 04:22:39 -07003019 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3020 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003021 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003022 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003023 .Padding(PaddingMode::RSA_PSS)
3024 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003025 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003026
3027 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003028 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003029 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3030 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3031 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3032 CheckOrigin();
3033
3034 string message(1024 / 8, 'a');
3035 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3036 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003037 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003038}
3039
3040/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003041 * ImportKeyTest.RsaSuccessWithoutParams
3042 *
3043 * Verifies that importing and using an RSA key pair without specifying parameters
3044 * works correctly.
3045 */
3046TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3047 uint32_t key_size;
3048 string key;
3049
3050 if (SecLevel() == SecurityLevel::STRONGBOX) {
3051 key_size = 2048;
3052 key = rsa_2048_key;
3053 } else {
3054 key_size = 1024;
3055 key = rsa_key;
3056 }
3057
3058 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3059 .Authorization(TAG_NO_AUTH_REQUIRED)
3060 .SigningKey()
3061 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3062 .Digest(Digest::SHA_2_256)
3063 .Padding(PaddingMode::RSA_PSS)
3064 .SetDefaultValidity(),
3065 KeyFormat::PKCS8, key));
3066
3067 // Key size and public exponent are determined from the imported key material.
3068 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3069 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3070
3071 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3072 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3073 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3074 CheckOrigin();
3075
3076 string message(1024 / 8, 'a');
3077 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3078 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003079 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003080}
3081
3082/*
Selene Huang31ab4042020-04-29 04:22:39 -07003083 * ImportKeyTest.RsaKeySizeMismatch
3084 *
3085 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3086 * correct way.
3087 */
3088TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3089 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3090 ImportKey(AuthorizationSetBuilder()
3091 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3092 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003093 .Padding(PaddingMode::NONE)
3094 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003095 KeyFormat::PKCS8, rsa_key));
3096}
3097
3098/*
3099 * ImportKeyTest.RsaPublicExponentMismatch
3100 *
3101 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3102 * fails in the correct way.
3103 */
3104TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3105 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3106 ImportKey(AuthorizationSetBuilder()
3107 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3108 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003109 .Padding(PaddingMode::NONE)
3110 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003111 KeyFormat::PKCS8, rsa_key));
3112}
3113
3114/*
3115 * ImportKeyTest.EcdsaSuccess
3116 *
3117 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3118 */
3119TEST_P(ImportKeyTest, EcdsaSuccess) {
3120 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3121 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003122 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003123 .Digest(Digest::SHA_2_256)
3124 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003125 KeyFormat::PKCS8, ec_256_key));
3126
3127 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003128 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3129 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3130
3131 CheckOrigin();
3132
3133 string message(32, 'a');
3134 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3135 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003136 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003137}
3138
3139/*
3140 * ImportKeyTest.EcdsaP256RFC5915Success
3141 *
3142 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3143 * correctly.
3144 */
3145TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3146 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3147 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003148 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003149 .Digest(Digest::SHA_2_256)
3150 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003151 KeyFormat::PKCS8, ec_256_key_rfc5915));
3152
3153 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003154 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3155 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3156
3157 CheckOrigin();
3158
3159 string message(32, 'a');
3160 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3161 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003162 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003163}
3164
3165/*
3166 * ImportKeyTest.EcdsaP256SEC1Success
3167 *
3168 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3169 */
3170TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3171 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3172 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003173 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003174 .Digest(Digest::SHA_2_256)
3175 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003176 KeyFormat::PKCS8, ec_256_key_sec1));
3177
3178 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003179 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3180 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3181
3182 CheckOrigin();
3183
3184 string message(32, 'a');
3185 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3186 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003187 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003188}
3189
3190/*
3191 * ImportKeyTest.Ecdsa521Success
3192 *
3193 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3194 */
3195TEST_P(ImportKeyTest, Ecdsa521Success) {
3196 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3197 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3198 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003199 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003200 .Digest(Digest::SHA_2_256)
3201 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003202 KeyFormat::PKCS8, ec_521_key));
3203
3204 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003205 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3206 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3207 CheckOrigin();
3208
3209 string message(32, 'a');
3210 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3211 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003212 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003213}
3214
3215/*
Selene Huang31ab4042020-04-29 04:22:39 -07003216 * ImportKeyTest.EcdsaCurveMismatch
3217 *
3218 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3219 * the correct way.
3220 */
3221TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3222 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3223 ImportKey(AuthorizationSetBuilder()
3224 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003225 .Digest(Digest::NONE)
3226 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003227 KeyFormat::PKCS8, ec_256_key));
3228}
3229
3230/*
3231 * ImportKeyTest.AesSuccess
3232 *
3233 * Verifies that importing and using an AES key works.
3234 */
3235TEST_P(ImportKeyTest, AesSuccess) {
3236 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3237 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3238 .Authorization(TAG_NO_AUTH_REQUIRED)
3239 .AesEncryptionKey(key.size() * 8)
3240 .EcbMode()
3241 .Padding(PaddingMode::PKCS7),
3242 KeyFormat::RAW, key));
3243
3244 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3245 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3246 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3247 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3248 CheckOrigin();
3249
3250 string message = "Hello World!";
3251 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3252 string ciphertext = EncryptMessage(message, params);
3253 string plaintext = DecryptMessage(ciphertext, params);
3254 EXPECT_EQ(message, plaintext);
3255}
3256
3257/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003258 * ImportKeyTest.AesFailure
3259 *
3260 * Verifies that importing an invalid AES key fails.
3261 */
3262TEST_P(ImportKeyTest, AesFailure) {
3263 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3264 uint32_t bitlen = key.size() * 8;
3265 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003266 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003267 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003268 .Authorization(TAG_NO_AUTH_REQUIRED)
3269 .AesEncryptionKey(key_size)
3270 .EcbMode()
3271 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003272 KeyFormat::RAW, key);
3273 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003274 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3275 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003276 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003277
3278 // Explicit key size matches that of the provided key, but it's not a valid size.
3279 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3280 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3281 ImportKey(AuthorizationSetBuilder()
3282 .Authorization(TAG_NO_AUTH_REQUIRED)
3283 .AesEncryptionKey(long_key.size() * 8)
3284 .EcbMode()
3285 .Padding(PaddingMode::PKCS7),
3286 KeyFormat::RAW, long_key));
3287 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3288 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3289 ImportKey(AuthorizationSetBuilder()
3290 .Authorization(TAG_NO_AUTH_REQUIRED)
3291 .AesEncryptionKey(short_key.size() * 8)
3292 .EcbMode()
3293 .Padding(PaddingMode::PKCS7),
3294 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003295}
3296
3297/*
3298 * ImportKeyTest.TripleDesSuccess
3299 *
3300 * Verifies that importing and using a 3DES key works.
3301 */
3302TEST_P(ImportKeyTest, TripleDesSuccess) {
3303 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3304 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3305 .Authorization(TAG_NO_AUTH_REQUIRED)
3306 .TripleDesEncryptionKey(168)
3307 .EcbMode()
3308 .Padding(PaddingMode::PKCS7),
3309 KeyFormat::RAW, key));
3310
3311 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3312 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3313 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3314 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3315 CheckOrigin();
3316
3317 string message = "Hello World!";
3318 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3319 string ciphertext = EncryptMessage(message, params);
3320 string plaintext = DecryptMessage(ciphertext, params);
3321 EXPECT_EQ(message, plaintext);
3322}
3323
3324/*
3325 * ImportKeyTest.TripleDesFailure
3326 *
3327 * Verifies that importing an invalid 3DES key fails.
3328 */
3329TEST_P(ImportKeyTest, TripleDesFailure) {
3330 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003331 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003332 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003333 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003334 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003335 .Authorization(TAG_NO_AUTH_REQUIRED)
3336 .TripleDesEncryptionKey(key_size)
3337 .EcbMode()
3338 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003339 KeyFormat::RAW, key);
3340 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003341 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3342 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003343 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003344 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003345 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003346 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3347 ImportKey(AuthorizationSetBuilder()
3348 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003349 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003350 .EcbMode()
3351 .Padding(PaddingMode::PKCS7),
3352 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003353 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003354 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3355 ImportKey(AuthorizationSetBuilder()
3356 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003357 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003358 .EcbMode()
3359 .Padding(PaddingMode::PKCS7),
3360 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003361}
3362
3363/*
3364 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003365 *
3366 * Verifies that importing and using an HMAC key works.
3367 */
3368TEST_P(ImportKeyTest, HmacKeySuccess) {
3369 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3370 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3371 .Authorization(TAG_NO_AUTH_REQUIRED)
3372 .HmacKey(key.size() * 8)
3373 .Digest(Digest::SHA_2_256)
3374 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3375 KeyFormat::RAW, key));
3376
3377 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3378 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3379 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3380 CheckOrigin();
3381
3382 string message = "Hello World!";
3383 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3384 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3385}
3386
3387INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3388
3389auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003390 // IKeyMintDevice.aidl
3391 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3392 "020100" // INTEGER length 1 value 0x00 (version)
3393 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3394 "934bf94e2aa28a3f83c9f79297250262"
3395 "fbe3276b5a1c91159bbfa3ef8957aac8"
3396 "4b59b30b455a79c2973480823d8b3863"
3397 "c3deef4a8e243590268d80e18751a0e1"
3398 "30f67ce6a1ace9f79b95e097474febc9"
3399 "81195b1d13a69086c0863f66a7b7fdb4"
3400 "8792227b1ac5e2489febdf087ab54864"
3401 "83033a6f001ca5d1ec1e27f5c30f4cec"
3402 "2642074a39ae68aee552e196627a8e3d"
3403 "867e67a8c01b11e75f13cca0a97ab668"
3404 "b50cda07a8ecb7cd8e3dd7009c963653"
3405 "4f6f239cffe1fc8daa466f78b676c711"
3406 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3407 "99b801597d5220e307eaa5bee507fb94"
3408 "d1fa69f9e519b2de315bac92c36f2ea1"
3409 "fa1df4478c0ddedeae8c70e0233cd098"
3410 "040c" // OCTET STRING length 0x0c (initializationVector)
3411 "d796b02c370f1fa4cc0124f1"
3412 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3413 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3414 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3415 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3416 "3106" // SET length 0x06
3417 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3418 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3419 // } end SET
3420 // } end [1]
3421 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3422 "020120" // INTEGER length 1 value 0x20 (AES)
3423 // } end [2]
3424 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3425 "02020100" // INTEGER length 2 value 0x100
3426 // } end [3]
3427 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3428 "3103" // SET length 0x03 {
3429 "020101" // INTEGER length 1 value 0x01 (ECB)
3430 // } end SET
3431 // } end [4]
3432 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3433 "3103" // SET length 0x03 {
3434 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3435 // } end SET
3436 // } end [5]
3437 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3438 // (noAuthRequired)
3439 "0500" // NULL
3440 // } end [503]
3441 // } end SEQUENCE (AuthorizationList)
3442 // } end SEQUENCE (KeyDescription)
3443 "0420" // OCTET STRING length 0x20 (encryptedKey)
3444 "ccd540855f833a5e1480bfd2d36faf3a"
3445 "eee15df5beabe2691bc82dde2a7aa910"
3446 "0410" // OCTET STRING length 0x10 (tag)
3447 "64c9f689c60ff6223ab6e6999e0eb6e5"
3448 // } SEQUENCE (SecureKeyWrapper)
3449);
Selene Huang31ab4042020-04-29 04:22:39 -07003450
3451auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003452 // IKeyMintDevice.aidl
3453 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3454 "020100" // INTEGER length 1 value 0x00 (version)
3455 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3456 "aad93ed5924f283b4bb5526fbe7a1412"
3457 "f9d9749ec30db9062b29e574a8546f33"
3458 "c88732452f5b8e6a391ee76c39ed1712"
3459 "c61d8df6213dec1cffbc17a8c6d04c7b"
3460 "30893d8daa9b2015213e219468215532"
3461 "07f8f9931c4caba23ed3bee28b36947e"
3462 "47f10e0a5c3dc51c988a628daad3e5e1"
3463 "f4005e79c2d5a96c284b4b8d7e4948f3"
3464 "31e5b85dd5a236f85579f3ea1d1b8484"
3465 "87470bdb0ab4f81a12bee42c99fe0df4"
3466 "bee3759453e69ad1d68a809ce06b949f"
3467 "7694a990429b2fe81e066ff43e56a216"
3468 "02db70757922a4bcc23ab89f1e35da77"
3469 "586775f423e519c2ea394caf48a28d0c"
3470 "8020f1dcf6b3a68ec246f615ae96dae9"
3471 "a079b1f6eb959033c1af5c125fd94168"
3472 "040c" // OCTET STRING length 0x0c (initializationVector)
3473 "6d9721d08589581ab49204a3"
3474 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3475 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3476 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3477 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3478 "3106" // SET length 0x06
3479 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3480 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3481 // } end SET
3482 // } end [1]
3483 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3484 "020120" // INTEGER length 1 value 0x20 (AES)
3485 // } end [2]
3486 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3487 "02020100" // INTEGER length 2 value 0x100
3488 // } end [3]
3489 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3490 "3103" // SET length 0x03 {
3491 "020101" // INTEGER length 1 value 0x01 (ECB)
3492 // } end SET
3493 // } end [4]
3494 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3495 "3103" // SET length 0x03 {
3496 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3497 // } end SET
3498 // } end [5]
3499 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3500 // (noAuthRequired)
3501 "0500" // NULL
3502 // } end [503]
3503 // } end SEQUENCE (AuthorizationList)
3504 // } end SEQUENCE (KeyDescription)
3505 "0420" // OCTET STRING length 0x20 (encryptedKey)
3506 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3507 "c20d1f99a9a024a76f35c8e2cab9b68d"
3508 "0410" // OCTET STRING length 0x10 (tag)
3509 "2560c70109ae67c030f00b98b512a670"
3510 // } SEQUENCE (SecureKeyWrapper)
3511);
Selene Huang31ab4042020-04-29 04:22:39 -07003512
3513auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003514 // RFC 5208 s5
3515 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3516 "020100" // INTEGER length 1 value 0x00 (version)
3517 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3518 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3519 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3520 "0500" // NULL (parameters)
3521 // } SEQUENCE (AlgorithmIdentifier)
3522 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3523 // RFC 8017 A.1.2
3524 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3525 "020100" // INTEGER length 1 value 0x00 (version)
3526 "02820101" // INTEGER length 0x0101 (modulus) value...
3527 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3528 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3529 "7b06e673a837313d56b1c725150a3fef" // 0x30
3530 "86acbddc41bb759c2854eae32d35841e" // 0x40
3531 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3532 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3533 "312d7bd5921ffaea1347c157406fef71" // 0x70
3534 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3535 "f4645c11f5c1374c3886427411c44979" // 0x90
3536 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3537 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3538 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3539 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3540 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3541 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3542 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3543 "55" // 0x101
3544 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3545 "02820100" // INTEGER length 0x100 (privateExponent) value...
3546 "431447b6251908112b1ee76f99f3711a" // 0x10
3547 "52b6630960046c2de70de188d833f8b8" // 0x20
3548 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3549 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3550 "e710b630a03adc683b5d2c43080e52be" // 0x50
3551 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3552 "822bccff087d63c940ba8a45f670feb2" // 0x70
3553 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3554 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3555 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3556 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3557 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3558 "52659d5a5ba05b663737a8696281865b" // 0xd0
3559 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3560 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3561 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3562 "028181" // INTEGER length 0x81 (prime1) value...
3563 "00de392e18d682c829266cc3454e1d61" // 0x10
3564 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3565 "ff841be5bac82a164c5970007047b8c5" // 0x30
3566 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3567 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3568 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3569 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3570 "9e91346130748a6e3c124f9149d71c74" // 0x80
3571 "35"
3572 "028181" // INTEGER length 0x81 (prime2) value...
3573 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3574 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3575 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3576 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3577 "9ed39a2d934c880440aed8832f984316" // 0x50
3578 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3579 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3580 "b880677c068e1be936e81288815252a8" // 0x80
3581 "a1"
3582 "028180" // INTEGER length 0x80 (exponent1) value...
3583 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3584 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3585 "5a063212a4f105a3764743e53281988a" // 0x30
3586 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3587 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3588 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3589 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3590 "4719d6e2b9439823719cd08bcd031781" // 0x80
3591 "028181" // INTEGER length 0x81 (exponent2) value...
3592 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3593 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3594 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3595 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3596 "1254186af30b22c10582a8a43e34fe94" // 0x50
3597 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3598 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3599 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3600 "61"
3601 "028181" // INTEGER length 0x81 (coefficient) value...
3602 "00c931617c77829dfb1270502be9195c" // 0x10
3603 "8f2830885f57dba869536811e6864236" // 0x20
3604 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3605 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3606 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3607 "959356210723287b0affcc9f727044d4" // 0x60
3608 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3609 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3610 "22"
3611 // } SEQUENCE
3612 // } SEQUENCE ()
3613);
Selene Huang31ab4042020-04-29 04:22:39 -07003614
3615string zero_masking_key =
3616 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3617string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3618
3619class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3620
3621TEST_P(ImportWrappedKeyTest, Success) {
3622 auto wrapping_key_desc = AuthorizationSetBuilder()
3623 .RsaEncryptionKey(2048, 65537)
3624 .Digest(Digest::SHA_2_256)
3625 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003626 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3627 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003628
3629 ASSERT_EQ(ErrorCode::OK,
3630 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3631 AuthorizationSetBuilder()
3632 .Digest(Digest::SHA_2_256)
3633 .Padding(PaddingMode::RSA_OAEP)));
3634
3635 string message = "Hello World!";
3636 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3637 string ciphertext = EncryptMessage(message, params);
3638 string plaintext = DecryptMessage(ciphertext, params);
3639 EXPECT_EQ(message, plaintext);
3640}
3641
David Drysdaled2cc8c22021-04-15 13:29:45 +01003642/*
3643 * ImportWrappedKeyTest.SuccessSidsIgnored
3644 *
3645 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3646 * include Tag:USER_SECURE_ID.
3647 */
3648TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3649 auto wrapping_key_desc = AuthorizationSetBuilder()
3650 .RsaEncryptionKey(2048, 65537)
3651 .Digest(Digest::SHA_2_256)
3652 .Padding(PaddingMode::RSA_OAEP)
3653 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3654 .SetDefaultValidity();
3655
3656 int64_t password_sid = 42;
3657 int64_t biometric_sid = 24;
3658 ASSERT_EQ(ErrorCode::OK,
3659 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3660 AuthorizationSetBuilder()
3661 .Digest(Digest::SHA_2_256)
3662 .Padding(PaddingMode::RSA_OAEP),
3663 password_sid, biometric_sid));
3664
3665 string message = "Hello World!";
3666 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3667 string ciphertext = EncryptMessage(message, params);
3668 string plaintext = DecryptMessage(ciphertext, params);
3669 EXPECT_EQ(message, plaintext);
3670}
3671
Selene Huang31ab4042020-04-29 04:22:39 -07003672TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3673 auto wrapping_key_desc = AuthorizationSetBuilder()
3674 .RsaEncryptionKey(2048, 65537)
3675 .Digest(Digest::SHA_2_256)
3676 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003677 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3678 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003679
3680 ASSERT_EQ(ErrorCode::OK,
3681 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3682 AuthorizationSetBuilder()
3683 .Digest(Digest::SHA_2_256)
3684 .Padding(PaddingMode::RSA_OAEP)));
3685}
3686
3687TEST_P(ImportWrappedKeyTest, WrongMask) {
3688 auto wrapping_key_desc = AuthorizationSetBuilder()
3689 .RsaEncryptionKey(2048, 65537)
3690 .Digest(Digest::SHA_2_256)
3691 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003692 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3693 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003694
3695 ASSERT_EQ(
3696 ErrorCode::VERIFICATION_FAILED,
3697 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3698 AuthorizationSetBuilder()
3699 .Digest(Digest::SHA_2_256)
3700 .Padding(PaddingMode::RSA_OAEP)));
3701}
3702
3703TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3704 auto wrapping_key_desc = AuthorizationSetBuilder()
3705 .RsaEncryptionKey(2048, 65537)
3706 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003707 .Padding(PaddingMode::RSA_OAEP)
3708 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003709
3710 ASSERT_EQ(
3711 ErrorCode::INCOMPATIBLE_PURPOSE,
3712 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3713 AuthorizationSetBuilder()
3714 .Digest(Digest::SHA_2_256)
3715 .Padding(PaddingMode::RSA_OAEP)));
3716}
3717
David Drysdaled2cc8c22021-04-15 13:29:45 +01003718TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3719 auto wrapping_key_desc = AuthorizationSetBuilder()
3720 .RsaEncryptionKey(2048, 65537)
3721 .Digest(Digest::SHA_2_256)
3722 .Padding(PaddingMode::RSA_PSS)
3723 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3724 .SetDefaultValidity();
3725
3726 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3727 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3728 AuthorizationSetBuilder()
3729 .Digest(Digest::SHA_2_256)
3730 .Padding(PaddingMode::RSA_OAEP)));
3731}
3732
3733TEST_P(ImportWrappedKeyTest, WrongDigest) {
3734 auto wrapping_key_desc = AuthorizationSetBuilder()
3735 .RsaEncryptionKey(2048, 65537)
3736 .Digest(Digest::SHA_2_512)
3737 .Padding(PaddingMode::RSA_OAEP)
3738 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3739 .SetDefaultValidity();
3740
3741 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3742 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3743 AuthorizationSetBuilder()
3744 .Digest(Digest::SHA_2_256)
3745 .Padding(PaddingMode::RSA_OAEP)));
3746}
3747
Selene Huang31ab4042020-04-29 04:22:39 -07003748INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3749
3750typedef KeyMintAidlTestBase EncryptionOperationsTest;
3751
3752/*
3753 * EncryptionOperationsTest.RsaNoPaddingSuccess
3754 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003755 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003756 */
3757TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003758 for (uint64_t exponent : {3, 65537}) {
3759 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3760 .Authorization(TAG_NO_AUTH_REQUIRED)
3761 .RsaEncryptionKey(2048, exponent)
3762 .Padding(PaddingMode::NONE)
3763 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003764
David Drysdaled2cc8c22021-04-15 13:29:45 +01003765 string message = string(2048 / 8, 'a');
3766 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003767 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003768 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003769
David Drysdale2b6c3512021-05-12 13:52:03 +01003770 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003771 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003772
David Drysdaled2cc8c22021-04-15 13:29:45 +01003773 // Unpadded RSA is deterministic
3774 EXPECT_EQ(ciphertext1, ciphertext2);
3775
3776 CheckedDeleteKey();
3777 }
Selene Huang31ab4042020-04-29 04:22:39 -07003778}
3779
3780/*
3781 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3782 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003783 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003784 */
3785TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3787 .Authorization(TAG_NO_AUTH_REQUIRED)
3788 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003789 .Padding(PaddingMode::NONE)
3790 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003791
3792 string message = "1";
3793 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3794
David Drysdale2b6c3512021-05-12 13:52:03 +01003795 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003796 EXPECT_EQ(2048U / 8, ciphertext.size());
3797
3798 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3799 string plaintext = DecryptMessage(ciphertext, params);
3800
3801 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003802}
3803
3804/*
Selene Huang31ab4042020-04-29 04:22:39 -07003805 * EncryptionOperationsTest.RsaOaepSuccess
3806 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003807 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003808 */
3809TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3810 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3811
3812 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale2b6c3512021-05-12 13:52:03 +01003813 ASSERT_EQ(ErrorCode::OK,
3814 GenerateKey(AuthorizationSetBuilder()
3815 .Authorization(TAG_NO_AUTH_REQUIRED)
3816 .RsaEncryptionKey(key_size, 65537)
3817 .Padding(PaddingMode::RSA_OAEP)
3818 .Digest(digests)
3819 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3820 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003821
3822 string message = "Hello";
3823
3824 for (auto digest : digests) {
David Drysdale2b6c3512021-05-12 13:52:03 +01003825 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3826
3827 auto params = AuthorizationSetBuilder()
3828 .Digest(digest)
3829 .Padding(PaddingMode::RSA_OAEP)
3830 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3831 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003832 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3833 EXPECT_EQ(key_size / 8, ciphertext1.size());
3834
David Drysdale2b6c3512021-05-12 13:52:03 +01003835 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003836 EXPECT_EQ(key_size / 8, ciphertext2.size());
3837
3838 // OAEP randomizes padding so every result should be different (with astronomically high
3839 // probability).
3840 EXPECT_NE(ciphertext1, ciphertext2);
3841
3842 string plaintext1 = DecryptMessage(ciphertext1, params);
3843 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3844 string plaintext2 = DecryptMessage(ciphertext2, params);
3845 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3846
3847 // Decrypting corrupted ciphertext should fail.
3848 size_t offset_to_corrupt = random() % ciphertext1.size();
3849 char corrupt_byte;
3850 do {
3851 corrupt_byte = static_cast<char>(random() % 256);
3852 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3853 ciphertext1[offset_to_corrupt] = corrupt_byte;
3854
3855 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3856 string result;
3857 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3858 EXPECT_EQ(0U, result.size());
3859 }
3860}
3861
3862/*
3863 * EncryptionOperationsTest.RsaOaepInvalidDigest
3864 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003865 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003866 * without a digest.
3867 */
3868TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3869 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3870 .Authorization(TAG_NO_AUTH_REQUIRED)
3871 .RsaEncryptionKey(2048, 65537)
3872 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003873 .Digest(Digest::NONE)
3874 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003875
3876 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003877 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003878}
3879
3880/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003881 * EncryptionOperationsTest.RsaOaepInvalidPadding
3882 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003883 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003884 * with a padding value that is only suitable for signing/verifying.
3885 */
3886TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3888 .Authorization(TAG_NO_AUTH_REQUIRED)
3889 .RsaEncryptionKey(2048, 65537)
3890 .Padding(PaddingMode::RSA_PSS)
3891 .Digest(Digest::NONE)
3892 .SetDefaultValidity()));
3893
3894 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003895 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003896}
3897
3898/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003899 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003900 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003901 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003902 * with a different digest than was used to encrypt.
3903 */
3904TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3905 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3906
3907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3908 .Authorization(TAG_NO_AUTH_REQUIRED)
3909 .RsaEncryptionKey(1024, 65537)
3910 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003911 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3912 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003913 string message = "Hello World!";
David Drysdale2b6c3512021-05-12 13:52:03 +01003914 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003915 message,
3916 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3917
3918 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3919 .Digest(Digest::SHA_2_256)
3920 .Padding(PaddingMode::RSA_OAEP)));
3921 string result;
3922 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3923 EXPECT_EQ(0U, result.size());
3924}
3925
3926/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003927 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3928 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003929 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003930 * digests.
3931 */
3932TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3933 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3934
3935 size_t key_size = 2048; // Need largish key for SHA-512 test.
3936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3937 .OaepMGFDigest(digests)
3938 .Authorization(TAG_NO_AUTH_REQUIRED)
3939 .RsaEncryptionKey(key_size, 65537)
3940 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003941 .Digest(Digest::SHA_2_256)
3942 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003943
3944 string message = "Hello";
3945
3946 for (auto digest : digests) {
3947 auto params = AuthorizationSetBuilder()
3948 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3949 .Digest(Digest::SHA_2_256)
3950 .Padding(PaddingMode::RSA_OAEP);
David Drysdale2b6c3512021-05-12 13:52:03 +01003951 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003952 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3953 EXPECT_EQ(key_size / 8, ciphertext1.size());
3954
David Drysdale2b6c3512021-05-12 13:52:03 +01003955 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003956 EXPECT_EQ(key_size / 8, ciphertext2.size());
3957
3958 // OAEP randomizes padding so every result should be different (with astronomically high
3959 // probability).
3960 EXPECT_NE(ciphertext1, ciphertext2);
3961
3962 string plaintext1 = DecryptMessage(ciphertext1, params);
3963 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3964 string plaintext2 = DecryptMessage(ciphertext2, params);
3965 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3966
3967 // Decrypting corrupted ciphertext should fail.
3968 size_t offset_to_corrupt = random() % ciphertext1.size();
3969 char corrupt_byte;
3970 do {
3971 corrupt_byte = static_cast<char>(random() % 256);
3972 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3973 ciphertext1[offset_to_corrupt] = corrupt_byte;
3974
3975 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3976 string result;
3977 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3978 EXPECT_EQ(0U, result.size());
3979 }
3980}
3981
3982/*
3983 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3984 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003985 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003986 * with incompatible MGF digest.
3987 */
3988TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3989 ASSERT_EQ(ErrorCode::OK,
3990 GenerateKey(AuthorizationSetBuilder()
3991 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3992 .Authorization(TAG_NO_AUTH_REQUIRED)
3993 .RsaEncryptionKey(2048, 65537)
3994 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003995 .Digest(Digest::SHA_2_256)
3996 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003997 string message = "Hello World!";
3998
3999 auto params = AuthorizationSetBuilder()
4000 .Padding(PaddingMode::RSA_OAEP)
4001 .Digest(Digest::SHA_2_256)
4002 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale2b6c3512021-05-12 13:52:03 +01004003 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004004}
4005
4006/*
4007 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4008 *
4009 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4010 * with unsupported MGF digest.
4011 */
4012TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4013 ASSERT_EQ(ErrorCode::OK,
4014 GenerateKey(AuthorizationSetBuilder()
4015 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4016 .Authorization(TAG_NO_AUTH_REQUIRED)
4017 .RsaEncryptionKey(2048, 65537)
4018 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004019 .Digest(Digest::SHA_2_256)
4020 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004021 string message = "Hello World!";
4022
4023 auto params = AuthorizationSetBuilder()
4024 .Padding(PaddingMode::RSA_OAEP)
4025 .Digest(Digest::SHA_2_256)
4026 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01004027 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004028}
4029
4030/*
Selene Huang31ab4042020-04-29 04:22:39 -07004031 * EncryptionOperationsTest.RsaPkcs1Success
4032 *
4033 * Verifies that RSA PKCS encryption/decrypts works.
4034 */
4035TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4037 .Authorization(TAG_NO_AUTH_REQUIRED)
4038 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004039 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4040 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004041
4042 string message = "Hello World!";
4043 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale2b6c3512021-05-12 13:52:03 +01004044 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004045 EXPECT_EQ(2048U / 8, ciphertext1.size());
4046
David Drysdale2b6c3512021-05-12 13:52:03 +01004047 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004048 EXPECT_EQ(2048U / 8, ciphertext2.size());
4049
4050 // PKCS1 v1.5 randomizes padding so every result should be different.
4051 EXPECT_NE(ciphertext1, ciphertext2);
4052
4053 string plaintext = DecryptMessage(ciphertext1, params);
4054 EXPECT_EQ(message, plaintext);
4055
4056 // Decrypting corrupted ciphertext should fail.
4057 size_t offset_to_corrupt = random() % ciphertext1.size();
4058 char corrupt_byte;
4059 do {
4060 corrupt_byte = static_cast<char>(random() % 256);
4061 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4062 ciphertext1[offset_to_corrupt] = corrupt_byte;
4063
4064 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4065 string result;
4066 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4067 EXPECT_EQ(0U, result.size());
4068}
4069
4070/*
Selene Huang31ab4042020-04-29 04:22:39 -07004071 * EncryptionOperationsTest.EcdsaEncrypt
4072 *
4073 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4074 */
4075TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4076 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4077 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01004078 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004079 .Digest(Digest::NONE)
4080 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004081 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4082 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4083 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4084}
4085
4086/*
4087 * EncryptionOperationsTest.HmacEncrypt
4088 *
4089 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4090 */
4091TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4093 .Authorization(TAG_NO_AUTH_REQUIRED)
4094 .HmacKey(128)
4095 .Digest(Digest::SHA_2_256)
4096 .Padding(PaddingMode::NONE)
4097 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4098 auto params = AuthorizationSetBuilder()
4099 .Digest(Digest::SHA_2_256)
4100 .Padding(PaddingMode::NONE)
4101 .Authorization(TAG_MAC_LENGTH, 128);
4102 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4103 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4104}
4105
4106/*
4107 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4108 *
4109 * Verifies that AES ECB mode works.
4110 */
4111TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4112 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4113 .Authorization(TAG_NO_AUTH_REQUIRED)
4114 .AesEncryptionKey(128)
4115 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4116 .Padding(PaddingMode::NONE)));
4117
4118 ASSERT_GT(key_blob_.size(), 0U);
4119 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4120
4121 // Two-block message.
4122 string message = "12345678901234567890123456789012";
4123 string ciphertext1 = EncryptMessage(message, params);
4124 EXPECT_EQ(message.size(), ciphertext1.size());
4125
4126 string ciphertext2 = EncryptMessage(string(message), params);
4127 EXPECT_EQ(message.size(), ciphertext2.size());
4128
4129 // ECB is deterministic.
4130 EXPECT_EQ(ciphertext1, ciphertext2);
4131
4132 string plaintext = DecryptMessage(ciphertext1, params);
4133 EXPECT_EQ(message, plaintext);
4134}
4135
4136/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004137 * EncryptionOperationsTest.AesEcbUnknownTag
4138 *
4139 * Verifies that AES ECB operations ignore unknown tags.
4140 */
4141TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4142 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4143 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4144 KeyParameter unknown_param;
4145 unknown_param.tag = unknown_tag;
4146
4147 vector<KeyCharacteristics> key_characteristics;
4148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4149 .Authorization(TAG_NO_AUTH_REQUIRED)
4150 .AesEncryptionKey(128)
4151 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4152 .Padding(PaddingMode::NONE)
4153 .Authorization(unknown_param),
4154 &key_blob_, &key_characteristics));
4155 ASSERT_GT(key_blob_.size(), 0U);
4156
4157 // Unknown tags should not be returned in key characteristics.
4158 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4159 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4160 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4161 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4162
4163 // Encrypt without mentioning the unknown parameter.
4164 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4165 string message = "12345678901234567890123456789012";
4166 string ciphertext = EncryptMessage(message, params);
4167 EXPECT_EQ(message.size(), ciphertext.size());
4168
4169 // Decrypt including the unknown parameter.
4170 auto decrypt_params = AuthorizationSetBuilder()
4171 .BlockMode(BlockMode::ECB)
4172 .Padding(PaddingMode::NONE)
4173 .Authorization(unknown_param);
4174 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4175 EXPECT_EQ(message, plaintext);
4176}
4177
4178/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004179 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004180 *
4181 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4182 */
4183TEST_P(EncryptionOperationsTest, AesWrongMode) {
4184 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4185 .Authorization(TAG_NO_AUTH_REQUIRED)
4186 .AesEncryptionKey(128)
4187 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4188 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004189 ASSERT_GT(key_blob_.size(), 0U);
4190
Selene Huang31ab4042020-04-29 04:22:39 -07004191 EXPECT_EQ(
4192 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4193 Begin(KeyPurpose::ENCRYPT,
4194 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4195}
4196
4197/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004198 * EncryptionOperationsTest.AesWrongPadding
4199 *
4200 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4201 */
4202TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4204 .Authorization(TAG_NO_AUTH_REQUIRED)
4205 .AesEncryptionKey(128)
4206 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4207 .Padding(PaddingMode::NONE)));
4208 ASSERT_GT(key_blob_.size(), 0U);
4209
4210 EXPECT_EQ(
4211 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4212 Begin(KeyPurpose::ENCRYPT,
4213 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4214}
4215
4216/*
4217 * EncryptionOperationsTest.AesInvalidParams
4218 *
4219 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4220 */
4221TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4223 .Authorization(TAG_NO_AUTH_REQUIRED)
4224 .AesEncryptionKey(128)
4225 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4226 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4227 .Padding(PaddingMode::NONE)
4228 .Padding(PaddingMode::PKCS7)));
4229 ASSERT_GT(key_blob_.size(), 0U);
4230
4231 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4232 .BlockMode(BlockMode::CBC)
4233 .BlockMode(BlockMode::ECB)
4234 .Padding(PaddingMode::NONE));
4235 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4236 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4237
4238 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4239 .BlockMode(BlockMode::ECB)
4240 .Padding(PaddingMode::NONE)
4241 .Padding(PaddingMode::PKCS7));
4242 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4243 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4244}
4245
4246/*
Selene Huang31ab4042020-04-29 04:22:39 -07004247 * EncryptionOperationsTest.AesWrongPurpose
4248 *
4249 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4250 * specified.
4251 */
4252TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4253 auto err = GenerateKey(AuthorizationSetBuilder()
4254 .Authorization(TAG_NO_AUTH_REQUIRED)
4255 .AesKey(128)
4256 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4257 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4258 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4259 .Padding(PaddingMode::NONE));
4260 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4261 ASSERT_GT(key_blob_.size(), 0U);
4262
4263 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4264 .BlockMode(BlockMode::GCM)
4265 .Padding(PaddingMode::NONE)
4266 .Authorization(TAG_MAC_LENGTH, 128));
4267 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4268
4269 CheckedDeleteKey();
4270
4271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4272 .Authorization(TAG_NO_AUTH_REQUIRED)
4273 .AesKey(128)
4274 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4275 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4276 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4277 .Padding(PaddingMode::NONE)));
4278
4279 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4280 .BlockMode(BlockMode::GCM)
4281 .Padding(PaddingMode::NONE)
4282 .Authorization(TAG_MAC_LENGTH, 128));
4283 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4284}
4285
4286/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004287 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004288 *
4289 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4290 * multiple of the block size and no padding is specified.
4291 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004292TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4293 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4295 .Authorization(TAG_NO_AUTH_REQUIRED)
4296 .AesEncryptionKey(128)
4297 .Authorization(TAG_BLOCK_MODE, blockMode)
4298 .Padding(PaddingMode::NONE)));
4299 // Message is slightly shorter than two blocks.
4300 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004301
David Drysdaled2cc8c22021-04-15 13:29:45 +01004302 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4303 AuthorizationSet out_params;
4304 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4305 string ciphertext;
4306 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4307 EXPECT_EQ(0U, ciphertext.size());
4308
4309 CheckedDeleteKey();
4310 }
Selene Huang31ab4042020-04-29 04:22:39 -07004311}
4312
4313/*
4314 * EncryptionOperationsTest.AesEcbPkcs7Padding
4315 *
4316 * Verifies that AES PKCS7 padding works for any message length.
4317 */
4318TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4319 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4320 .Authorization(TAG_NO_AUTH_REQUIRED)
4321 .AesEncryptionKey(128)
4322 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4323 .Padding(PaddingMode::PKCS7)));
4324
4325 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4326
4327 // Try various message lengths; all should work.
4328 for (size_t i = 0; i < 32; ++i) {
4329 string message(i, 'a');
4330 string ciphertext = EncryptMessage(message, params);
4331 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4332 string plaintext = DecryptMessage(ciphertext, params);
4333 EXPECT_EQ(message, plaintext);
4334 }
4335}
4336
4337/*
4338 * EncryptionOperationsTest.AesEcbWrongPadding
4339 *
4340 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4341 * specified.
4342 */
4343TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4344 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4345 .Authorization(TAG_NO_AUTH_REQUIRED)
4346 .AesEncryptionKey(128)
4347 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4348 .Padding(PaddingMode::NONE)));
4349
4350 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4351
4352 // Try various message lengths; all should fail
4353 for (size_t i = 0; i < 32; ++i) {
4354 string message(i, 'a');
4355 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4356 }
4357}
4358
4359/*
4360 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4361 *
4362 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4363 */
4364TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4366 .Authorization(TAG_NO_AUTH_REQUIRED)
4367 .AesEncryptionKey(128)
4368 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4369 .Padding(PaddingMode::PKCS7)));
4370
4371 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4372
4373 string message = "a";
4374 string ciphertext = EncryptMessage(message, params);
4375 EXPECT_EQ(16U, ciphertext.size());
4376 EXPECT_NE(ciphertext, message);
4377 ++ciphertext[ciphertext.size() / 2];
4378
4379 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4380 string plaintext;
4381 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4382}
4383
4384vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4385 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004386 EXPECT_TRUE(iv);
4387 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004388}
4389
4390/*
4391 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4392 *
4393 * Verifies that AES CTR mode works.
4394 */
4395TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4397 .Authorization(TAG_NO_AUTH_REQUIRED)
4398 .AesEncryptionKey(128)
4399 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4400 .Padding(PaddingMode::NONE)));
4401
4402 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4403
4404 string message = "123";
4405 AuthorizationSet out_params;
4406 string ciphertext1 = EncryptMessage(message, params, &out_params);
4407 vector<uint8_t> iv1 = CopyIv(out_params);
4408 EXPECT_EQ(16U, iv1.size());
4409
4410 EXPECT_EQ(message.size(), ciphertext1.size());
4411
4412 out_params.Clear();
4413 string ciphertext2 = EncryptMessage(message, params, &out_params);
4414 vector<uint8_t> iv2 = CopyIv(out_params);
4415 EXPECT_EQ(16U, iv2.size());
4416
4417 // IVs should be random, so ciphertexts should differ.
4418 EXPECT_NE(ciphertext1, ciphertext2);
4419
4420 auto params_iv1 =
4421 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4422 auto params_iv2 =
4423 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4424
4425 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4426 EXPECT_EQ(message, plaintext);
4427 plaintext = DecryptMessage(ciphertext2, params_iv2);
4428 EXPECT_EQ(message, plaintext);
4429
4430 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4431 plaintext = DecryptMessage(ciphertext1, params_iv2);
4432 EXPECT_NE(message, plaintext);
4433 plaintext = DecryptMessage(ciphertext2, params_iv1);
4434 EXPECT_NE(message, plaintext);
4435}
4436
4437/*
4438 * EncryptionOperationsTest.AesIncremental
4439 *
4440 * Verifies that AES works, all modes, when provided data in various size increments.
4441 */
4442TEST_P(EncryptionOperationsTest, AesIncremental) {
4443 auto block_modes = {
4444 BlockMode::ECB,
4445 BlockMode::CBC,
4446 BlockMode::CTR,
4447 BlockMode::GCM,
4448 };
4449
4450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4451 .Authorization(TAG_NO_AUTH_REQUIRED)
4452 .AesEncryptionKey(128)
4453 .BlockMode(block_modes)
4454 .Padding(PaddingMode::NONE)
4455 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4456
4457 for (int increment = 1; increment <= 240; ++increment) {
4458 for (auto block_mode : block_modes) {
4459 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004460 auto params =
4461 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4462 if (block_mode == BlockMode::GCM) {
4463 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4464 }
Selene Huang31ab4042020-04-29 04:22:39 -07004465
4466 AuthorizationSet output_params;
4467 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4468
4469 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004470 string to_send;
4471 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004472 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004473 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004474 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4475 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004476
4477 switch (block_mode) {
4478 case BlockMode::GCM:
4479 EXPECT_EQ(message.size() + 16, ciphertext.size());
4480 break;
4481 case BlockMode::CTR:
4482 EXPECT_EQ(message.size(), ciphertext.size());
4483 break;
4484 case BlockMode::CBC:
4485 case BlockMode::ECB:
4486 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4487 break;
4488 }
4489
4490 auto iv = output_params.GetTagValue(TAG_NONCE);
4491 switch (block_mode) {
4492 case BlockMode::CBC:
4493 case BlockMode::GCM:
4494 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004495 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4496 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4497 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004498 break;
4499
4500 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004501 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004502 break;
4503 }
4504
4505 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4506 << "Decrypt begin() failed for block mode " << block_mode;
4507
4508 string plaintext;
4509 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004510 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004511 }
4512 ErrorCode error = Finish(to_send, &plaintext);
4513 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4514 << " and increment " << increment;
4515 if (error == ErrorCode::OK) {
4516 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4517 << block_mode << " and increment " << increment;
4518 }
4519 }
4520 }
4521}
4522
4523struct AesCtrSp80038aTestVector {
4524 const char* key;
4525 const char* nonce;
4526 const char* plaintext;
4527 const char* ciphertext;
4528};
4529
4530// These test vectors are taken from
4531// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4532static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4533 // AES-128
4534 {
4535 "2b7e151628aed2a6abf7158809cf4f3c",
4536 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4537 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4538 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4539 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4540 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4541 },
4542 // AES-192
4543 {
4544 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4545 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4546 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4547 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4548 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4549 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4550 },
4551 // AES-256
4552 {
4553 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4554 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4555 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4556 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4557 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4558 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4559 },
4560};
4561
4562/*
4563 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4564 *
4565 * Verifies AES CTR implementation against SP800-38A test vectors.
4566 */
4567TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4568 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4569 for (size_t i = 0; i < 3; i++) {
4570 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4571 const string key = hex2str(test.key);
4572 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4573 InvalidSizes.end())
4574 continue;
4575 const string nonce = hex2str(test.nonce);
4576 const string plaintext = hex2str(test.plaintext);
4577 const string ciphertext = hex2str(test.ciphertext);
4578 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4579 }
4580}
4581
4582/*
4583 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4584 *
4585 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4586 */
4587TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4589 .Authorization(TAG_NO_AUTH_REQUIRED)
4590 .AesEncryptionKey(128)
4591 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4592 .Padding(PaddingMode::PKCS7)));
4593 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4594 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4595}
4596
4597/*
4598 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4599 *
4600 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4601 */
4602TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4604 .Authorization(TAG_NO_AUTH_REQUIRED)
4605 .AesEncryptionKey(128)
4606 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4607 .Authorization(TAG_CALLER_NONCE)
4608 .Padding(PaddingMode::NONE)));
4609
4610 auto params = AuthorizationSetBuilder()
4611 .BlockMode(BlockMode::CTR)
4612 .Padding(PaddingMode::NONE)
4613 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4614 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4615
4616 params = AuthorizationSetBuilder()
4617 .BlockMode(BlockMode::CTR)
4618 .Padding(PaddingMode::NONE)
4619 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4620 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4621
4622 params = AuthorizationSetBuilder()
4623 .BlockMode(BlockMode::CTR)
4624 .Padding(PaddingMode::NONE)
4625 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4626 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4627}
4628
4629/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004630 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004631 *
4632 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4633 */
4634TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4636 .Authorization(TAG_NO_AUTH_REQUIRED)
4637 .AesEncryptionKey(128)
4638 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4639 .Padding(PaddingMode::NONE)));
4640 // Two-block message.
4641 string message = "12345678901234567890123456789012";
4642 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4643 AuthorizationSet out_params;
4644 string ciphertext1 = EncryptMessage(message, params, &out_params);
4645 vector<uint8_t> iv1 = CopyIv(out_params);
4646 EXPECT_EQ(message.size(), ciphertext1.size());
4647
4648 out_params.Clear();
4649
4650 string ciphertext2 = EncryptMessage(message, params, &out_params);
4651 vector<uint8_t> iv2 = CopyIv(out_params);
4652 EXPECT_EQ(message.size(), ciphertext2.size());
4653
4654 // IVs should be random, so ciphertexts should differ.
4655 EXPECT_NE(ciphertext1, ciphertext2);
4656
4657 params.push_back(TAG_NONCE, iv1);
4658 string plaintext = DecryptMessage(ciphertext1, params);
4659 EXPECT_EQ(message, plaintext);
4660}
4661
4662/*
4663 * EncryptionOperationsTest.AesCallerNonce
4664 *
4665 * Verifies that AES caller-provided nonces work correctly.
4666 */
4667TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4668 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4669 .Authorization(TAG_NO_AUTH_REQUIRED)
4670 .AesEncryptionKey(128)
4671 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4672 .Authorization(TAG_CALLER_NONCE)
4673 .Padding(PaddingMode::NONE)));
4674
4675 string message = "12345678901234567890123456789012";
4676
4677 // Don't specify nonce, should get a random one.
4678 AuthorizationSetBuilder params =
4679 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4680 AuthorizationSet out_params;
4681 string ciphertext = EncryptMessage(message, params, &out_params);
4682 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004683 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004684
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004685 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004686 string plaintext = DecryptMessage(ciphertext, params);
4687 EXPECT_EQ(message, plaintext);
4688
4689 // Now specify a nonce, should also work.
4690 params = AuthorizationSetBuilder()
4691 .BlockMode(BlockMode::CBC)
4692 .Padding(PaddingMode::NONE)
4693 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4694 out_params.Clear();
4695 ciphertext = EncryptMessage(message, params, &out_params);
4696
4697 // Decrypt with correct nonce.
4698 plaintext = DecryptMessage(ciphertext, params);
4699 EXPECT_EQ(message, plaintext);
4700
4701 // Try with wrong nonce.
4702 params = AuthorizationSetBuilder()
4703 .BlockMode(BlockMode::CBC)
4704 .Padding(PaddingMode::NONE)
4705 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4706 plaintext = DecryptMessage(ciphertext, params);
4707 EXPECT_NE(message, plaintext);
4708}
4709
4710/*
4711 * EncryptionOperationsTest.AesCallerNonceProhibited
4712 *
4713 * Verifies that caller-provided nonces are not permitted when not specified in the key
4714 * authorizations.
4715 */
4716TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4717 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4718 .Authorization(TAG_NO_AUTH_REQUIRED)
4719 .AesEncryptionKey(128)
4720 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4721 .Padding(PaddingMode::NONE)));
4722
4723 string message = "12345678901234567890123456789012";
4724
4725 // Don't specify nonce, should get a random one.
4726 AuthorizationSetBuilder params =
4727 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4728 AuthorizationSet out_params;
4729 string ciphertext = EncryptMessage(message, params, &out_params);
4730 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004731 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004732
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004733 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004734 string plaintext = DecryptMessage(ciphertext, params);
4735 EXPECT_EQ(message, plaintext);
4736
4737 // Now specify a nonce, should fail
4738 params = AuthorizationSetBuilder()
4739 .BlockMode(BlockMode::CBC)
4740 .Padding(PaddingMode::NONE)
4741 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4742 out_params.Clear();
4743 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4744}
4745
4746/*
4747 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4748 *
4749 * Verifies that AES GCM mode works.
4750 */
4751TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4753 .Authorization(TAG_NO_AUTH_REQUIRED)
4754 .AesEncryptionKey(128)
4755 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4756 .Padding(PaddingMode::NONE)
4757 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4758
4759 string aad = "foobar";
4760 string message = "123456789012345678901234567890123456";
4761
4762 auto begin_params = AuthorizationSetBuilder()
4763 .BlockMode(BlockMode::GCM)
4764 .Padding(PaddingMode::NONE)
4765 .Authorization(TAG_MAC_LENGTH, 128);
4766
Selene Huang31ab4042020-04-29 04:22:39 -07004767 // Encrypt
4768 AuthorizationSet begin_out_params;
4769 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4770 << "Begin encrypt";
4771 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004772 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4773 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004774 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4775
4776 // Grab nonce
4777 begin_params.push_back(begin_out_params);
4778
4779 // Decrypt.
4780 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004781 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004782 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004783 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004784 EXPECT_EQ(message.length(), plaintext.length());
4785 EXPECT_EQ(message, plaintext);
4786}
4787
4788/*
4789 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4790 *
4791 * Verifies that AES GCM mode works, even when there's a long delay
4792 * between operations.
4793 */
4794TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4795 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4796 .Authorization(TAG_NO_AUTH_REQUIRED)
4797 .AesEncryptionKey(128)
4798 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4799 .Padding(PaddingMode::NONE)
4800 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4801
4802 string aad = "foobar";
4803 string message = "123456789012345678901234567890123456";
4804
4805 auto begin_params = AuthorizationSetBuilder()
4806 .BlockMode(BlockMode::GCM)
4807 .Padding(PaddingMode::NONE)
4808 .Authorization(TAG_MAC_LENGTH, 128);
4809
Selene Huang31ab4042020-04-29 04:22:39 -07004810 // Encrypt
4811 AuthorizationSet begin_out_params;
4812 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4813 << "Begin encrypt";
4814 string ciphertext;
4815 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004816 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004817 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004818 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004819
4820 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4821
4822 // Grab nonce
4823 begin_params.push_back(begin_out_params);
4824
4825 // Decrypt.
4826 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4827 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004828 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004829 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004830 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004831 sleep(5);
4832 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4833 EXPECT_EQ(message.length(), plaintext.length());
4834 EXPECT_EQ(message, plaintext);
4835}
4836
4837/*
4838 * EncryptionOperationsTest.AesGcmDifferentNonces
4839 *
4840 * Verifies that encrypting the same data with different nonces produces different outputs.
4841 */
4842TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4844 .Authorization(TAG_NO_AUTH_REQUIRED)
4845 .AesEncryptionKey(128)
4846 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4847 .Padding(PaddingMode::NONE)
4848 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4849 .Authorization(TAG_CALLER_NONCE)));
4850
4851 string aad = "foobar";
4852 string message = "123456789012345678901234567890123456";
4853 string nonce1 = "000000000000";
4854 string nonce2 = "111111111111";
4855 string nonce3 = "222222222222";
4856
4857 string ciphertext1 =
4858 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4859 string ciphertext2 =
4860 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4861 string ciphertext3 =
4862 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4863
4864 ASSERT_NE(ciphertext1, ciphertext2);
4865 ASSERT_NE(ciphertext1, ciphertext3);
4866 ASSERT_NE(ciphertext2, ciphertext3);
4867}
4868
4869/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004870 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4871 *
4872 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4873 */
4874TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4875 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4876 .Authorization(TAG_NO_AUTH_REQUIRED)
4877 .AesEncryptionKey(128)
4878 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4879 .Padding(PaddingMode::NONE)
4880 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4881
4882 string aad = "foobar";
4883 string message = "123456789012345678901234567890123456";
4884
4885 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4886 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4887 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4888
4889 ASSERT_NE(ciphertext1, ciphertext2);
4890 ASSERT_NE(ciphertext1, ciphertext3);
4891 ASSERT_NE(ciphertext2, ciphertext3);
4892}
4893
4894/*
Selene Huang31ab4042020-04-29 04:22:39 -07004895 * EncryptionOperationsTest.AesGcmTooShortTag
4896 *
4897 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4898 */
4899TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4901 .Authorization(TAG_NO_AUTH_REQUIRED)
4902 .AesEncryptionKey(128)
4903 .BlockMode(BlockMode::GCM)
4904 .Padding(PaddingMode::NONE)
4905 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4906 string message = "123456789012345678901234567890123456";
4907 auto params = AuthorizationSetBuilder()
4908 .BlockMode(BlockMode::GCM)
4909 .Padding(PaddingMode::NONE)
4910 .Authorization(TAG_MAC_LENGTH, 96);
4911
4912 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4913}
4914
4915/*
4916 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4917 *
4918 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4919 */
4920TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4922 .Authorization(TAG_NO_AUTH_REQUIRED)
4923 .AesEncryptionKey(128)
4924 .BlockMode(BlockMode::GCM)
4925 .Padding(PaddingMode::NONE)
4926 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4927 string aad = "foobar";
4928 string message = "123456789012345678901234567890123456";
4929 auto params = AuthorizationSetBuilder()
4930 .BlockMode(BlockMode::GCM)
4931 .Padding(PaddingMode::NONE)
4932 .Authorization(TAG_MAC_LENGTH, 128);
4933
Selene Huang31ab4042020-04-29 04:22:39 -07004934 // Encrypt
4935 AuthorizationSet begin_out_params;
4936 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4937 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004938 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004939
4940 AuthorizationSet finish_out_params;
4941 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004942 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4943 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004944
4945 params = AuthorizationSetBuilder()
4946 .Authorizations(begin_out_params)
4947 .BlockMode(BlockMode::GCM)
4948 .Padding(PaddingMode::NONE)
4949 .Authorization(TAG_MAC_LENGTH, 96);
4950
4951 // Decrypt.
4952 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4953}
4954
4955/*
4956 * EncryptionOperationsTest.AesGcmCorruptKey
4957 *
4958 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4959 */
4960TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4961 const uint8_t nonce_bytes[] = {
4962 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4963 };
4964 string nonce = make_string(nonce_bytes);
4965 const uint8_t ciphertext_bytes[] = {
4966 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4967 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4968 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4969 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4970 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4971 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4972 };
4973 string ciphertext = make_string(ciphertext_bytes);
4974
4975 auto params = AuthorizationSetBuilder()
4976 .BlockMode(BlockMode::GCM)
4977 .Padding(PaddingMode::NONE)
4978 .Authorization(TAG_MAC_LENGTH, 128)
4979 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4980
4981 auto import_params = AuthorizationSetBuilder()
4982 .Authorization(TAG_NO_AUTH_REQUIRED)
4983 .AesEncryptionKey(128)
4984 .BlockMode(BlockMode::GCM)
4985 .Padding(PaddingMode::NONE)
4986 .Authorization(TAG_CALLER_NONCE)
4987 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4988
4989 // Import correct key and decrypt
4990 const uint8_t key_bytes[] = {
4991 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4992 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4993 };
4994 string key = make_string(key_bytes);
4995 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4996 string plaintext = DecryptMessage(ciphertext, params);
4997 CheckedDeleteKey();
4998
4999 // Corrupt key and attempt to decrypt
5000 key[0] = 0;
5001 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5002 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5003 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5004 CheckedDeleteKey();
5005}
5006
5007/*
5008 * EncryptionOperationsTest.AesGcmAadNoData
5009 *
5010 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5011 * encrypt.
5012 */
5013TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5015 .Authorization(TAG_NO_AUTH_REQUIRED)
5016 .AesEncryptionKey(128)
5017 .BlockMode(BlockMode::GCM)
5018 .Padding(PaddingMode::NONE)
5019 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5020
5021 string aad = "1234567890123456";
5022 auto params = AuthorizationSetBuilder()
5023 .BlockMode(BlockMode::GCM)
5024 .Padding(PaddingMode::NONE)
5025 .Authorization(TAG_MAC_LENGTH, 128);
5026
Selene Huang31ab4042020-04-29 04:22:39 -07005027 // Encrypt
5028 AuthorizationSet begin_out_params;
5029 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5030 string ciphertext;
5031 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005032 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5033 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005034 EXPECT_TRUE(finish_out_params.empty());
5035
5036 // Grab nonce
5037 params.push_back(begin_out_params);
5038
5039 // Decrypt.
5040 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005041 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005042 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005043 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005044
5045 EXPECT_TRUE(finish_out_params.empty());
5046
5047 EXPECT_EQ("", plaintext);
5048}
5049
5050/*
5051 * EncryptionOperationsTest.AesGcmMultiPartAad
5052 *
5053 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5054 * chunks.
5055 */
5056TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5057 const size_t tag_bits = 128;
5058 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5059 .Authorization(TAG_NO_AUTH_REQUIRED)
5060 .AesEncryptionKey(128)
5061 .BlockMode(BlockMode::GCM)
5062 .Padding(PaddingMode::NONE)
5063 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5064
5065 string message = "123456789012345678901234567890123456";
5066 auto begin_params = AuthorizationSetBuilder()
5067 .BlockMode(BlockMode::GCM)
5068 .Padding(PaddingMode::NONE)
5069 .Authorization(TAG_MAC_LENGTH, tag_bits);
5070 AuthorizationSet begin_out_params;
5071
Selene Huang31ab4042020-04-29 04:22:39 -07005072 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5073
5074 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005075 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5076 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005077 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005078 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5079 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005080
Selene Huang31ab4042020-04-29 04:22:39 -07005081 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005082 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005083
5084 // Grab nonce.
5085 begin_params.push_back(begin_out_params);
5086
5087 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005088 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005089 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005090 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005091 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005092 EXPECT_EQ(message, plaintext);
5093}
5094
5095/*
5096 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5097 *
5098 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5099 */
5100TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5102 .Authorization(TAG_NO_AUTH_REQUIRED)
5103 .AesEncryptionKey(128)
5104 .BlockMode(BlockMode::GCM)
5105 .Padding(PaddingMode::NONE)
5106 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5107
5108 string message = "123456789012345678901234567890123456";
5109 auto begin_params = AuthorizationSetBuilder()
5110 .BlockMode(BlockMode::GCM)
5111 .Padding(PaddingMode::NONE)
5112 .Authorization(TAG_MAC_LENGTH, 128);
5113 AuthorizationSet begin_out_params;
5114
Selene Huang31ab4042020-04-29 04:22:39 -07005115 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5116
Shawn Willden92d79c02021-02-19 07:31:55 -07005117 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005118 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005119 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5120 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005121
David Drysdaled2cc8c22021-04-15 13:29:45 +01005122 // The failure should have already cancelled the operation.
5123 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5124
Shawn Willden92d79c02021-02-19 07:31:55 -07005125 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005126}
5127
5128/*
5129 * EncryptionOperationsTest.AesGcmBadAad
5130 *
5131 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5132 */
5133TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5134 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5135 .Authorization(TAG_NO_AUTH_REQUIRED)
5136 .AesEncryptionKey(128)
5137 .BlockMode(BlockMode::GCM)
5138 .Padding(PaddingMode::NONE)
5139 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5140
5141 string message = "12345678901234567890123456789012";
5142 auto begin_params = AuthorizationSetBuilder()
5143 .BlockMode(BlockMode::GCM)
5144 .Padding(PaddingMode::NONE)
5145 .Authorization(TAG_MAC_LENGTH, 128);
5146
Selene Huang31ab4042020-04-29 04:22:39 -07005147 // Encrypt
5148 AuthorizationSet begin_out_params;
5149 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005150 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005151 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005152 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005153
5154 // Grab nonce
5155 begin_params.push_back(begin_out_params);
5156
Selene Huang31ab4042020-04-29 04:22:39 -07005157 // Decrypt.
5158 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005159 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005160 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005161 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005162}
5163
5164/*
5165 * EncryptionOperationsTest.AesGcmWrongNonce
5166 *
5167 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5168 */
5169TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5171 .Authorization(TAG_NO_AUTH_REQUIRED)
5172 .AesEncryptionKey(128)
5173 .BlockMode(BlockMode::GCM)
5174 .Padding(PaddingMode::NONE)
5175 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5176
5177 string message = "12345678901234567890123456789012";
5178 auto begin_params = AuthorizationSetBuilder()
5179 .BlockMode(BlockMode::GCM)
5180 .Padding(PaddingMode::NONE)
5181 .Authorization(TAG_MAC_LENGTH, 128);
5182
Selene Huang31ab4042020-04-29 04:22:39 -07005183 // Encrypt
5184 AuthorizationSet begin_out_params;
5185 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005186 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005187 string ciphertext;
5188 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005189 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005190
5191 // Wrong nonce
5192 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5193
5194 // Decrypt.
5195 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005196 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005197 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005198 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005199
5200 // With wrong nonce, should have gotten garbage plaintext (or none).
5201 EXPECT_NE(message, plaintext);
5202}
5203
5204/*
5205 * EncryptionOperationsTest.AesGcmCorruptTag
5206 *
5207 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5208 */
5209TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5211 .Authorization(TAG_NO_AUTH_REQUIRED)
5212 .AesEncryptionKey(128)
5213 .BlockMode(BlockMode::GCM)
5214 .Padding(PaddingMode::NONE)
5215 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5216
5217 string aad = "1234567890123456";
5218 string message = "123456789012345678901234567890123456";
5219
5220 auto params = AuthorizationSetBuilder()
5221 .BlockMode(BlockMode::GCM)
5222 .Padding(PaddingMode::NONE)
5223 .Authorization(TAG_MAC_LENGTH, 128);
5224
Selene Huang31ab4042020-04-29 04:22:39 -07005225 // Encrypt
5226 AuthorizationSet begin_out_params;
5227 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005228 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005229 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005230 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005231
5232 // Corrupt tag
5233 ++(*ciphertext.rbegin());
5234
5235 // Grab nonce
5236 params.push_back(begin_out_params);
5237
5238 // Decrypt.
5239 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005240 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005241 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005242 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005243}
5244
5245/*
5246 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5247 *
5248 * Verifies that 3DES is basically functional.
5249 */
5250TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5251 auto auths = AuthorizationSetBuilder()
5252 .TripleDesEncryptionKey(168)
5253 .BlockMode(BlockMode::ECB)
5254 .Authorization(TAG_NO_AUTH_REQUIRED)
5255 .Padding(PaddingMode::NONE);
5256
5257 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5258 // Two-block message.
5259 string message = "1234567890123456";
5260 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5261 string ciphertext1 = EncryptMessage(message, inParams);
5262 EXPECT_EQ(message.size(), ciphertext1.size());
5263
5264 string ciphertext2 = EncryptMessage(string(message), inParams);
5265 EXPECT_EQ(message.size(), ciphertext2.size());
5266
5267 // ECB is deterministic.
5268 EXPECT_EQ(ciphertext1, ciphertext2);
5269
5270 string plaintext = DecryptMessage(ciphertext1, inParams);
5271 EXPECT_EQ(message, plaintext);
5272}
5273
5274/*
5275 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5276 *
5277 * Verifies that CBC keys reject ECB usage.
5278 */
5279TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5281 .TripleDesEncryptionKey(168)
5282 .BlockMode(BlockMode::CBC)
5283 .Authorization(TAG_NO_AUTH_REQUIRED)
5284 .Padding(PaddingMode::NONE)));
5285
5286 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5287 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5288}
5289
5290/*
5291 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5292 *
5293 * Tests ECB mode with PKCS#7 padding, various message sizes.
5294 */
5295TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5297 .TripleDesEncryptionKey(168)
5298 .BlockMode(BlockMode::ECB)
5299 .Authorization(TAG_NO_AUTH_REQUIRED)
5300 .Padding(PaddingMode::PKCS7)));
5301
5302 for (size_t i = 0; i < 32; ++i) {
5303 string message(i, 'a');
5304 auto inParams =
5305 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5306 string ciphertext = EncryptMessage(message, inParams);
5307 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5308 string plaintext = DecryptMessage(ciphertext, inParams);
5309 EXPECT_EQ(message, plaintext);
5310 }
5311}
5312
5313/*
5314 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5315 *
5316 * Verifies that keys configured for no padding reject PKCS7 padding
5317 */
5318TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5319 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5320 .TripleDesEncryptionKey(168)
5321 .BlockMode(BlockMode::ECB)
5322 .Authorization(TAG_NO_AUTH_REQUIRED)
5323 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005324 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5325 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005326}
5327
5328/*
5329 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5330 *
5331 * Verifies that corrupted padding is detected.
5332 */
5333TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5335 .TripleDesEncryptionKey(168)
5336 .BlockMode(BlockMode::ECB)
5337 .Authorization(TAG_NO_AUTH_REQUIRED)
5338 .Padding(PaddingMode::PKCS7)));
5339
5340 string message = "a";
5341 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5342 EXPECT_EQ(8U, ciphertext.size());
5343 EXPECT_NE(ciphertext, message);
5344 ++ciphertext[ciphertext.size() / 2];
5345
5346 AuthorizationSetBuilder begin_params;
5347 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5348 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5349 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5350 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005351 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005352 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5353}
5354
5355struct TripleDesTestVector {
5356 const char* name;
5357 const KeyPurpose purpose;
5358 const BlockMode block_mode;
5359 const PaddingMode padding_mode;
5360 const char* key;
5361 const char* iv;
5362 const char* input;
5363 const char* output;
5364};
5365
5366// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5367// of the NIST vectors are multiples of the block size.
5368static const TripleDesTestVector kTripleDesTestVectors[] = {
5369 {
5370 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5371 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5372 "", // IV
5373 "329d86bdf1bc5af4", // input
5374 "d946c2756d78633f", // output
5375 },
5376 {
5377 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5378 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5379 "", // IV
5380 "6b1540781b01ce1997adae102dbf3c5b", // input
5381 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5382 },
5383 {
5384 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5385 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5386 "", // IV
5387 "6daad94ce08acfe7", // input
5388 "660e7d32dcc90e79", // output
5389 },
5390 {
5391 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5392 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5393 "", // IV
5394 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5395 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5396 },
5397 {
5398 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5399 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5400 "43f791134c5647ba", // IV
5401 "dcc153cef81d6f24", // input
5402 "92538bd8af18d3ba", // output
5403 },
5404 {
5405 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5406 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5407 "c2e999cb6249023c", // IV
5408 "c689aee38a301bb316da75db36f110b5", // input
5409 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5410 },
5411 {
5412 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5413 PaddingMode::PKCS7,
5414 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5415 "c2e999cb6249023c", // IV
5416 "c689aee38a301bb316da75db36f110b500", // input
5417 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5418 },
5419 {
5420 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5421 PaddingMode::PKCS7,
5422 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5423 "c2e999cb6249023c", // IV
5424 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5425 "c689aee38a301bb316da75db36f110b500", // output
5426 },
5427 {
5428 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5429 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5430 "41746c7e442d3681", // IV
5431 "c53a7b0ec40600fe", // input
5432 "d4f00eb455de1034", // output
5433 },
5434 {
5435 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5436 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5437 "3982bc02c3727d45", // IV
5438 "6006f10adef52991fcc777a1238bbb65", // input
5439 "edae09288e9e3bc05746d872b48e3b29", // output
5440 },
5441};
5442
5443/*
5444 * EncryptionOperationsTest.TripleDesTestVector
5445 *
5446 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5447 */
5448TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5449 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5450 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5451 SCOPED_TRACE(test->name);
5452 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5453 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5454 hex2str(test->output));
5455 }
5456}
5457
5458/*
5459 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5460 *
5461 * Validates CBC mode functionality.
5462 */
5463TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5464 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5465 .TripleDesEncryptionKey(168)
5466 .BlockMode(BlockMode::CBC)
5467 .Authorization(TAG_NO_AUTH_REQUIRED)
5468 .Padding(PaddingMode::NONE)));
5469
5470 ASSERT_GT(key_blob_.size(), 0U);
5471
5472 // Two-block message.
5473 string message = "1234567890123456";
5474 vector<uint8_t> iv1;
5475 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5476 EXPECT_EQ(message.size(), ciphertext1.size());
5477
5478 vector<uint8_t> iv2;
5479 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5480 EXPECT_EQ(message.size(), ciphertext2.size());
5481
5482 // IVs should be random, so ciphertexts should differ.
5483 EXPECT_NE(iv1, iv2);
5484 EXPECT_NE(ciphertext1, ciphertext2);
5485
5486 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5487 EXPECT_EQ(message, plaintext);
5488}
5489
5490/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005491 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5492 *
5493 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5494 */
5495TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5497 .TripleDesEncryptionKey(168)
5498 .BlockMode(BlockMode::CBC)
5499 .Authorization(TAG_NO_AUTH_REQUIRED)
5500 .Authorization(TAG_CALLER_NONCE)
5501 .Padding(PaddingMode::NONE)));
5502 auto params = AuthorizationSetBuilder()
5503 .BlockMode(BlockMode::CBC)
5504 .Padding(PaddingMode::NONE)
5505 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5506 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5507}
5508
5509/*
Selene Huang31ab4042020-04-29 04:22:39 -07005510 * EncryptionOperationsTest.TripleDesCallerIv
5511 *
5512 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5513 */
5514TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5516 .TripleDesEncryptionKey(168)
5517 .BlockMode(BlockMode::CBC)
5518 .Authorization(TAG_NO_AUTH_REQUIRED)
5519 .Authorization(TAG_CALLER_NONCE)
5520 .Padding(PaddingMode::NONE)));
5521 string message = "1234567890123456";
5522 vector<uint8_t> iv;
5523 // Don't specify IV, should get a random one.
5524 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5525 EXPECT_EQ(message.size(), ciphertext1.size());
5526 EXPECT_EQ(8U, iv.size());
5527
5528 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5529 EXPECT_EQ(message, plaintext);
5530
5531 // Now specify an IV, should also work.
5532 iv = AidlBuf("abcdefgh");
5533 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5534
5535 // Decrypt with correct IV.
5536 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5537 EXPECT_EQ(message, plaintext);
5538
5539 // Now try with wrong IV.
5540 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5541 EXPECT_NE(message, plaintext);
5542}
5543
5544/*
5545 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5546 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005547 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005548 */
5549TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5551 .TripleDesEncryptionKey(168)
5552 .BlockMode(BlockMode::CBC)
5553 .Authorization(TAG_NO_AUTH_REQUIRED)
5554 .Padding(PaddingMode::NONE)));
5555
5556 string message = "12345678901234567890123456789012";
5557 vector<uint8_t> iv;
5558 // Don't specify nonce, should get a random one.
5559 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5560 EXPECT_EQ(message.size(), ciphertext1.size());
5561 EXPECT_EQ(8U, iv.size());
5562
5563 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5564 EXPECT_EQ(message, plaintext);
5565
5566 // Now specify a nonce, should fail.
5567 auto input_params = AuthorizationSetBuilder()
5568 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5569 .BlockMode(BlockMode::CBC)
5570 .Padding(PaddingMode::NONE);
5571 AuthorizationSet output_params;
5572 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5573 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5574}
5575
5576/*
5577 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5578 *
5579 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5580 */
5581TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5583 .TripleDesEncryptionKey(168)
5584 .BlockMode(BlockMode::ECB)
5585 .Authorization(TAG_NO_AUTH_REQUIRED)
5586 .Padding(PaddingMode::NONE)));
5587 // Two-block message.
5588 string message = "1234567890123456";
5589 auto begin_params =
5590 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5591 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5592}
5593
5594/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005595 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005596 *
5597 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5598 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005599TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5600 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5601 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5602 .TripleDesEncryptionKey(168)
5603 .BlockMode(blockMode)
5604 .Authorization(TAG_NO_AUTH_REQUIRED)
5605 .Padding(PaddingMode::NONE)));
5606 // Message is slightly shorter than two blocks.
5607 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005608
David Drysdaled2cc8c22021-04-15 13:29:45 +01005609 auto begin_params =
5610 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5611 AuthorizationSet output_params;
5612 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5613 string ciphertext;
5614 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5615
5616 CheckedDeleteKey();
5617 }
Selene Huang31ab4042020-04-29 04:22:39 -07005618}
5619
5620/*
5621 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5622 *
5623 * Verifies that PKCS7 padding works correctly in CBC mode.
5624 */
5625TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5626 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5627 .TripleDesEncryptionKey(168)
5628 .BlockMode(BlockMode::CBC)
5629 .Authorization(TAG_NO_AUTH_REQUIRED)
5630 .Padding(PaddingMode::PKCS7)));
5631
5632 // Try various message lengths; all should work.
5633 for (size_t i = 0; i < 32; ++i) {
5634 string message(i, 'a');
5635 vector<uint8_t> iv;
5636 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5637 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5638 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5639 EXPECT_EQ(message, plaintext);
5640 }
5641}
5642
5643/*
5644 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5645 *
5646 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5647 */
5648TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5650 .TripleDesEncryptionKey(168)
5651 .BlockMode(BlockMode::CBC)
5652 .Authorization(TAG_NO_AUTH_REQUIRED)
5653 .Padding(PaddingMode::NONE)));
5654
5655 // Try various message lengths; all should fail.
5656 for (size_t i = 0; i < 32; ++i) {
5657 auto begin_params =
5658 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5659 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5660 }
5661}
5662
5663/*
5664 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5665 *
5666 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5667 */
5668TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5670 .TripleDesEncryptionKey(168)
5671 .BlockMode(BlockMode::CBC)
5672 .Authorization(TAG_NO_AUTH_REQUIRED)
5673 .Padding(PaddingMode::PKCS7)));
5674
5675 string message = "a";
5676 vector<uint8_t> iv;
5677 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5678 EXPECT_EQ(8U, ciphertext.size());
5679 EXPECT_NE(ciphertext, message);
5680 ++ciphertext[ciphertext.size() / 2];
5681
5682 auto begin_params = AuthorizationSetBuilder()
5683 .BlockMode(BlockMode::CBC)
5684 .Padding(PaddingMode::PKCS7)
5685 .Authorization(TAG_NONCE, iv);
5686 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5687 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005688 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005689 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5690}
5691
5692/*
5693 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5694 *
5695 * Verifies that 3DES CBC works with many different input sizes.
5696 */
5697TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .TripleDesEncryptionKey(168)
5700 .BlockMode(BlockMode::CBC)
5701 .Authorization(TAG_NO_AUTH_REQUIRED)
5702 .Padding(PaddingMode::NONE)));
5703
5704 int increment = 7;
5705 string message(240, 'a');
5706 AuthorizationSet input_params =
5707 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5708 AuthorizationSet output_params;
5709 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5710
5711 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005712 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005713 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005714 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5715 EXPECT_EQ(message.size(), ciphertext.size());
5716
5717 // Move TAG_NONCE into input_params
5718 input_params = output_params;
5719 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5720 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5721 output_params.Clear();
5722
5723 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5724 string plaintext;
5725 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005726 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005727 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5728 EXPECT_EQ(ciphertext.size(), plaintext.size());
5729 EXPECT_EQ(message, plaintext);
5730}
5731
5732INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5733
5734typedef KeyMintAidlTestBase MaxOperationsTest;
5735
5736/*
5737 * MaxOperationsTest.TestLimitAes
5738 *
5739 * Verifies that the max uses per boot tag works correctly with AES keys.
5740 */
5741TEST_P(MaxOperationsTest, TestLimitAes) {
5742 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5743
5744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5745 .Authorization(TAG_NO_AUTH_REQUIRED)
5746 .AesEncryptionKey(128)
5747 .EcbMode()
5748 .Padding(PaddingMode::NONE)
5749 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5750
5751 string message = "1234567890123456";
5752
5753 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5754
5755 EncryptMessage(message, params);
5756 EncryptMessage(message, params);
5757 EncryptMessage(message, params);
5758
5759 // Fourth time should fail.
5760 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5761}
5762
5763/*
Qi Wud22ec842020-11-26 13:27:53 +08005764 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005765 *
5766 * Verifies that the max uses per boot tag works correctly with RSA keys.
5767 */
5768TEST_P(MaxOperationsTest, TestLimitRsa) {
5769 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5770
5771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5772 .Authorization(TAG_NO_AUTH_REQUIRED)
5773 .RsaSigningKey(1024, 65537)
5774 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005775 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5776 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005777
5778 string message = "1234567890123456";
5779
5780 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5781
5782 SignMessage(message, params);
5783 SignMessage(message, params);
5784 SignMessage(message, params);
5785
5786 // Fourth time should fail.
5787 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5788}
5789
5790INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5791
Qi Wud22ec842020-11-26 13:27:53 +08005792typedef KeyMintAidlTestBase UsageCountLimitTest;
5793
5794/*
Qi Wubeefae42021-01-28 23:16:37 +08005795 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005796 *
Qi Wubeefae42021-01-28 23:16:37 +08005797 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005798 */
Qi Wubeefae42021-01-28 23:16:37 +08005799TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005800 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5801
5802 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5803 .Authorization(TAG_NO_AUTH_REQUIRED)
5804 .AesEncryptionKey(128)
5805 .EcbMode()
5806 .Padding(PaddingMode::NONE)
5807 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5808
5809 // Check the usage count limit tag appears in the authorizations.
5810 AuthorizationSet auths;
5811 for (auto& entry : key_characteristics_) {
5812 auths.push_back(AuthorizationSet(entry.authorizations));
5813 }
5814 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5815 << "key usage count limit " << 1U << " missing";
5816
5817 string message = "1234567890123456";
5818 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5819
Qi Wubeefae42021-01-28 23:16:37 +08005820 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5821 AuthorizationSet keystore_auths =
5822 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5823
Qi Wud22ec842020-11-26 13:27:53 +08005824 // First usage of AES key should work.
5825 EncryptMessage(message, params);
5826
Qi Wud22ec842020-11-26 13:27:53 +08005827 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5828 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5829 // must be invalidated from secure storage (such as RPMB partition).
5830 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5831 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005832 // Usage count limit tag is enforced by keystore, keymint does nothing.
5833 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005834 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5835 }
5836}
5837
5838/*
Qi Wubeefae42021-01-28 23:16:37 +08005839 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005840 *
Qi Wubeefae42021-01-28 23:16:37 +08005841 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005842 */
Qi Wubeefae42021-01-28 23:16:37 +08005843TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5844 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5845
5846 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5847 .Authorization(TAG_NO_AUTH_REQUIRED)
5848 .AesEncryptionKey(128)
5849 .EcbMode()
5850 .Padding(PaddingMode::NONE)
5851 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5852
5853 // Check the usage count limit tag appears in the authorizations.
5854 AuthorizationSet auths;
5855 for (auto& entry : key_characteristics_) {
5856 auths.push_back(AuthorizationSet(entry.authorizations));
5857 }
5858 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5859 << "key usage count limit " << 3U << " missing";
5860
5861 string message = "1234567890123456";
5862 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5863
5864 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5865 AuthorizationSet keystore_auths =
5866 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5867
5868 EncryptMessage(message, params);
5869 EncryptMessage(message, params);
5870 EncryptMessage(message, params);
5871
5872 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5873 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5874 // must be invalidated from secure storage (such as RPMB partition).
5875 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5876 } else {
5877 // Usage count limit tag is enforced by keystore, keymint does nothing.
5878 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5879 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5880 }
5881}
5882
5883/*
5884 * UsageCountLimitTest.TestSingleUseRsa
5885 *
5886 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5887 */
5888TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005889 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5890
5891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5892 .Authorization(TAG_NO_AUTH_REQUIRED)
5893 .RsaSigningKey(1024, 65537)
5894 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005895 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5896 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005897
5898 // Check the usage count limit tag appears in the authorizations.
5899 AuthorizationSet auths;
5900 for (auto& entry : key_characteristics_) {
5901 auths.push_back(AuthorizationSet(entry.authorizations));
5902 }
5903 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5904 << "key usage count limit " << 1U << " missing";
5905
5906 string message = "1234567890123456";
5907 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5908
Qi Wubeefae42021-01-28 23:16:37 +08005909 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5910 AuthorizationSet keystore_auths =
5911 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5912
Qi Wud22ec842020-11-26 13:27:53 +08005913 // First usage of RSA key should work.
5914 SignMessage(message, params);
5915
Qi Wud22ec842020-11-26 13:27:53 +08005916 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5917 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5918 // must be invalidated from secure storage (such as RPMB partition).
5919 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5920 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005921 // Usage count limit tag is enforced by keystore, keymint does nothing.
5922 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5923 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5924 }
5925}
5926
5927/*
5928 * UsageCountLimitTest.TestLimitUseRsa
5929 *
5930 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5931 */
5932TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5933 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5934
5935 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5936 .Authorization(TAG_NO_AUTH_REQUIRED)
5937 .RsaSigningKey(1024, 65537)
5938 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005939 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5940 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005941
5942 // Check the usage count limit tag appears in the authorizations.
5943 AuthorizationSet auths;
5944 for (auto& entry : key_characteristics_) {
5945 auths.push_back(AuthorizationSet(entry.authorizations));
5946 }
5947 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5948 << "key usage count limit " << 3U << " missing";
5949
5950 string message = "1234567890123456";
5951 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5952
5953 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5954 AuthorizationSet keystore_auths =
5955 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5956
5957 SignMessage(message, params);
5958 SignMessage(message, params);
5959 SignMessage(message, params);
5960
5961 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5962 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5963 // must be invalidated from secure storage (such as RPMB partition).
5964 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5965 } else {
5966 // Usage count limit tag is enforced by keystore, keymint does nothing.
5967 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005968 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5969 }
5970}
5971
Qi Wu8e727f72021-02-11 02:49:33 +08005972/*
5973 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5974 *
5975 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5976 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5977 * in hardware.
5978 */
5979TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5980 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5981
5982 auto error = GenerateKey(AuthorizationSetBuilder()
5983 .RsaSigningKey(2048, 65537)
5984 .Digest(Digest::NONE)
5985 .Padding(PaddingMode::NONE)
5986 .Authorization(TAG_NO_AUTH_REQUIRED)
5987 .Authorization(TAG_ROLLBACK_RESISTANCE)
5988 .SetDefaultValidity());
5989 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5990
5991 if (error == ErrorCode::OK) {
5992 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5993 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5994 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5995 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5996
5997 // The KeyMint should also enforce single use key in hardware when it supports rollback
5998 // resistance.
5999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6000 .Authorization(TAG_NO_AUTH_REQUIRED)
6001 .RsaSigningKey(1024, 65537)
6002 .NoDigestOrPadding()
6003 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6004 .SetDefaultValidity()));
6005
6006 // Check the usage count limit tag appears in the hardware authorizations.
6007 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6008 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6009 << "key usage count limit " << 1U << " missing";
6010
6011 string message = "1234567890123456";
6012 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6013
6014 // First usage of RSA key should work.
6015 SignMessage(message, params);
6016
6017 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6018 // must be invalidated from secure storage (such as RPMB partition).
6019 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6020 }
6021}
6022
Qi Wud22ec842020-11-26 13:27:53 +08006023INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6024
David Drysdale7de9feb2021-03-05 14:56:19 +00006025typedef KeyMintAidlTestBase GetHardwareInfoTest;
6026
6027TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6028 // Retrieving hardware info should give the same result each time.
6029 KeyMintHardwareInfo info;
6030 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6031 KeyMintHardwareInfo info2;
6032 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6033 EXPECT_EQ(info, info2);
6034}
6035
6036INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6037
Selene Huang31ab4042020-04-29 04:22:39 -07006038typedef KeyMintAidlTestBase AddEntropyTest;
6039
6040/*
6041 * AddEntropyTest.AddEntropy
6042 *
6043 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6044 * is actually added.
6045 */
6046TEST_P(AddEntropyTest, AddEntropy) {
6047 string data = "foo";
6048 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6049}
6050
6051/*
6052 * AddEntropyTest.AddEmptyEntropy
6053 *
6054 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6055 */
6056TEST_P(AddEntropyTest, AddEmptyEntropy) {
6057 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6058}
6059
6060/*
6061 * AddEntropyTest.AddLargeEntropy
6062 *
6063 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6064 */
6065TEST_P(AddEntropyTest, AddLargeEntropy) {
6066 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6067}
6068
David Drysdalebb3d85e2021-04-13 11:15:51 +01006069/*
6070 * AddEntropyTest.AddTooLargeEntropy
6071 *
6072 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6073 */
6074TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6075 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6076 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6077}
6078
Selene Huang31ab4042020-04-29 04:22:39 -07006079INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6080
Selene Huang31ab4042020-04-29 04:22:39 -07006081typedef KeyMintAidlTestBase KeyDeletionTest;
6082
6083/**
6084 * KeyDeletionTest.DeleteKey
6085 *
6086 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6087 * valid key blob.
6088 */
6089TEST_P(KeyDeletionTest, DeleteKey) {
6090 auto error = GenerateKey(AuthorizationSetBuilder()
6091 .RsaSigningKey(2048, 65537)
6092 .Digest(Digest::NONE)
6093 .Padding(PaddingMode::NONE)
6094 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006095 .Authorization(TAG_ROLLBACK_RESISTANCE)
6096 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006097 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6098
6099 // Delete must work if rollback protection is implemented
6100 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006101 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006102 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6103
6104 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6105
6106 string message = "12345678901234567890123456789012";
6107 AuthorizationSet begin_out_params;
6108 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6109 Begin(KeyPurpose::SIGN, key_blob_,
6110 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6111 &begin_out_params));
6112 AbortIfNeeded();
6113 key_blob_ = AidlBuf();
6114 }
6115}
6116
6117/**
6118 * KeyDeletionTest.DeleteInvalidKey
6119 *
6120 * This test checks that the HAL excepts invalid key blobs..
6121 */
6122TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6123 // Generate key just to check if rollback protection is implemented
6124 auto error = GenerateKey(AuthorizationSetBuilder()
6125 .RsaSigningKey(2048, 65537)
6126 .Digest(Digest::NONE)
6127 .Padding(PaddingMode::NONE)
6128 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006129 .Authorization(TAG_ROLLBACK_RESISTANCE)
6130 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006131 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6132
6133 // Delete must work if rollback protection is implemented
6134 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006135 AuthorizationSet enforced(SecLevelAuthorizations());
6136 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006137
6138 // Delete the key we don't care about the result at this point.
6139 DeleteKey();
6140
6141 // Now create an invalid key blob and delete it.
6142 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6143
6144 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6145 }
6146}
6147
6148/**
6149 * KeyDeletionTest.DeleteAllKeys
6150 *
6151 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6152 *
6153 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6154 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6155 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6156 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6157 * credentials stored in Keystore/Keymint.
6158 */
6159TEST_P(KeyDeletionTest, DeleteAllKeys) {
6160 if (!arm_deleteAllKeys) return;
6161 auto error = GenerateKey(AuthorizationSetBuilder()
6162 .RsaSigningKey(2048, 65537)
6163 .Digest(Digest::NONE)
6164 .Padding(PaddingMode::NONE)
6165 .Authorization(TAG_NO_AUTH_REQUIRED)
6166 .Authorization(TAG_ROLLBACK_RESISTANCE));
6167 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6168
6169 // Delete must work if rollback protection is implemented
6170 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006171 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006172 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6173
6174 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6175
6176 string message = "12345678901234567890123456789012";
6177 AuthorizationSet begin_out_params;
6178
6179 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6180 Begin(KeyPurpose::SIGN, key_blob_,
6181 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6182 &begin_out_params));
6183 AbortIfNeeded();
6184 key_blob_ = AidlBuf();
6185 }
6186}
6187
6188INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6189
David Drysdaled2cc8c22021-04-15 13:29:45 +01006190typedef KeyMintAidlTestBase KeyUpgradeTest;
6191
6192/**
6193 * KeyUpgradeTest.UpgradeInvalidKey
6194 *
6195 * This test checks that the HAL excepts invalid key blobs..
6196 */
6197TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6198 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6199
6200 std::vector<uint8_t> new_blob;
6201 Status result = keymint_->upgradeKey(key_blob,
6202 AuthorizationSetBuilder()
6203 .Authorization(TAG_APPLICATION_ID, "clientid")
6204 .Authorization(TAG_APPLICATION_DATA, "appdata")
6205 .vector_data(),
6206 &new_blob);
6207 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6208}
6209
6210INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6211
Selene Huang31ab4042020-04-29 04:22:39 -07006212using UpgradeKeyTest = KeyMintAidlTestBase;
6213
6214/*
6215 * UpgradeKeyTest.UpgradeKey
6216 *
6217 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6218 */
6219TEST_P(UpgradeKeyTest, UpgradeKey) {
6220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6221 .AesEncryptionKey(128)
6222 .Padding(PaddingMode::NONE)
6223 .Authorization(TAG_NO_AUTH_REQUIRED)));
6224
6225 auto result = UpgradeKey(key_blob_);
6226
6227 // Key doesn't need upgrading. Should get okay, but no new key blob.
6228 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6229}
6230
6231INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6232
6233using ClearOperationsTest = KeyMintAidlTestBase;
6234
6235/*
6236 * ClearSlotsTest.TooManyOperations
6237 *
6238 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6239 * operations are started without being finished or aborted. Also verifies
6240 * that aborting the operations clears the operations.
6241 *
6242 */
6243TEST_P(ClearOperationsTest, TooManyOperations) {
6244 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6245 .Authorization(TAG_NO_AUTH_REQUIRED)
6246 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006247 .Padding(PaddingMode::NONE)
6248 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006249
6250 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6251 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006252 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006253 AuthorizationSet out_params;
6254 ErrorCode result;
6255 size_t i;
6256
6257 for (i = 0; i < max_operations; i++) {
6258 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6259 if (ErrorCode::OK != result) {
6260 break;
6261 }
6262 }
6263 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6264 // Try again just in case there's a weird overflow bug
6265 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6266 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6267 for (size_t j = 0; j < i; j++) {
6268 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6269 << "Aboort failed for i = " << j << std::endl;
6270 }
6271 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6272 AbortIfNeeded();
6273}
6274
6275INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6276
6277typedef KeyMintAidlTestBase TransportLimitTest;
6278
6279/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006280 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006281 *
6282 * Verifies that passing input data to finish succeeds as expected.
6283 */
6284TEST_P(TransportLimitTest, LargeFinishInput) {
6285 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6286 .Authorization(TAG_NO_AUTH_REQUIRED)
6287 .AesEncryptionKey(128)
6288 .BlockMode(BlockMode::ECB)
6289 .Padding(PaddingMode::NONE)));
6290
6291 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6292 auto cipher_params =
6293 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6294
6295 AuthorizationSet out_params;
6296 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6297
6298 string plain_message = std::string(1 << msg_size, 'x');
6299 string encrypted_message;
6300 auto rc = Finish(plain_message, &encrypted_message);
6301
6302 EXPECT_EQ(ErrorCode::OK, rc);
6303 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6304 << "Encrypt finish returned OK, but did not consume all of the given input";
6305 cipher_params.push_back(out_params);
6306
6307 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6308
6309 string decrypted_message;
6310 rc = Finish(encrypted_message, &decrypted_message);
6311 EXPECT_EQ(ErrorCode::OK, rc);
6312 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6313 << "Decrypt finish returned OK, did not consume all of the given input";
6314 }
6315}
6316
6317INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6318
David Zeuthene0c40892021-01-08 12:54:11 -05006319typedef KeyMintAidlTestBase KeyAgreementTest;
6320
6321int CurveToOpenSslCurveName(EcCurve curve) {
6322 switch (curve) {
6323 case EcCurve::P_224:
6324 return NID_secp224r1;
6325 case EcCurve::P_256:
6326 return NID_X9_62_prime256v1;
6327 case EcCurve::P_384:
6328 return NID_secp384r1;
6329 case EcCurve::P_521:
6330 return NID_secp521r1;
6331 }
6332}
6333
6334/*
6335 * KeyAgreementTest.Ecdh
6336 *
6337 * Verifies that ECDH works for all curves
6338 */
6339TEST_P(KeyAgreementTest, Ecdh) {
6340 // Because it's possible to use this API with keys on different curves, we
6341 // check all N^2 combinations where N is the number of supported
6342 // curves.
6343 //
6344 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6345 // lot more curves we can be smart about things and just pick |otherCurve| so
6346 // it's not |curve| and that way we end up with only 2*N runs
6347 //
6348 for (auto curve : ValidCurves()) {
6349 for (auto localCurve : ValidCurves()) {
6350 // Generate EC key locally (with access to private key material)
6351 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6352 int curveName = CurveToOpenSslCurveName(localCurve);
6353 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6354 ASSERT_NE(group, nullptr);
6355 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6356 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6357 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6358 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6359
6360 // Get encoded form of the public part of the locally generated key...
6361 unsigned char* p = nullptr;
6362 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6363 ASSERT_GT(encodedPublicKeySize, 0);
6364 vector<uint8_t> encodedPublicKey(
6365 reinterpret_cast<const uint8_t*>(p),
6366 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6367 OPENSSL_free(p);
6368
6369 // Generate EC key in KeyMint (only access to public key material)
6370 vector<uint8_t> challenge = {0x41, 0x42};
6371 EXPECT_EQ(
6372 ErrorCode::OK,
6373 GenerateKey(AuthorizationSetBuilder()
6374 .Authorization(TAG_NO_AUTH_REQUIRED)
6375 .Authorization(TAG_EC_CURVE, curve)
6376 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6377 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6378 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006379 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6380 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006381 << "Failed to generate key";
6382 ASSERT_GT(cert_chain_.size(), 0);
6383 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6384 ASSERT_NE(kmKeyCert, nullptr);
6385 // Check that keyAgreement (bit 4) is set in KeyUsage
6386 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6387 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6388 ASSERT_NE(kmPkey, nullptr);
6389 if (dump_Attestations) {
6390 for (size_t n = 0; n < cert_chain_.size(); n++) {
6391 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6392 }
6393 }
6394
6395 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6396 if (curve != localCurve) {
6397 // If the keys are using different curves KeyMint should fail with
6398 // ErrorCode:INVALID_ARGUMENT. Check that.
6399 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6400 string ZabFromKeyMintStr;
6401 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6402 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6403 &ZabFromKeyMintStr));
6404
6405 } else {
6406 // Otherwise if the keys are using the same curve, it should work.
6407 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6408 string ZabFromKeyMintStr;
6409 EXPECT_EQ(ErrorCode::OK,
6410 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6411 &ZabFromKeyMintStr));
6412 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6413
6414 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6415 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6416 ASSERT_NE(ctx, nullptr);
6417 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6418 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6419 size_t ZabFromTestLen = 0;
6420 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6421 vector<uint8_t> ZabFromTest;
6422 ZabFromTest.resize(ZabFromTestLen);
6423 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6424
6425 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6426 }
6427
6428 CheckedDeleteKey();
6429 }
6430 }
6431}
6432
6433INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6434
David Drysdaled2cc8c22021-04-15 13:29:45 +01006435using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6436
6437// This is a problematic test, as it can render the device under test permanently unusable.
6438// Re-enable and run at your own risk.
6439TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6440 auto result = DestroyAttestationIds();
6441 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6442}
6443
6444INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6445
Shawn Willdend659c7c2021-02-19 14:51:51 -07006446using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006447
David Drysdale216d9922021-05-18 11:43:31 +01006448/*
6449 * EarlyBootKeyTest.CreateEarlyBootKeys
6450 *
6451 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6452 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006453TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdale216d9922021-05-18 11:43:31 +01006454 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006455 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6456 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6457
David Drysdaleeaab0f22021-05-27 12:00:53 +01006458 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6459 ASSERT_GT(keyData.blob.size(), 0U);
6460 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6461 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6462 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006463 CheckedDeleteKey(&aesKeyData.blob);
6464 CheckedDeleteKey(&hmacKeyData.blob);
6465 CheckedDeleteKey(&rsaKeyData.blob);
6466 CheckedDeleteKey(&ecdsaKeyData.blob);
6467}
6468
David Drysdale216d9922021-05-18 11:43:31 +01006469/*
David Drysdaleeaab0f22021-05-27 12:00:53 +01006470 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6471 *
6472 * Verifies that creating an early boot key with attestation succeeds.
6473 */
6474TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6475 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6476 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6477 builder->AttestationChallenge("challenge");
6478 builder->AttestationApplicationId("app_id");
6479 });
6480
6481 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6482 ASSERT_GT(keyData.blob.size(), 0U);
6483 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6484 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6485 }
6486 CheckedDeleteKey(&aesKeyData.blob);
6487 CheckedDeleteKey(&hmacKeyData.blob);
6488 CheckedDeleteKey(&rsaKeyData.blob);
6489 CheckedDeleteKey(&ecdsaKeyData.blob);
6490}
6491
6492/*
6493 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdale216d9922021-05-18 11:43:31 +01006494 *
6495 * Verifies that using early boot keys at a later stage fails.
6496 */
6497TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6499 .Authorization(TAG_NO_AUTH_REQUIRED)
6500 .Authorization(TAG_EARLY_BOOT_ONLY)
6501 .HmacKey(128)
6502 .Digest(Digest::SHA_2_256)
6503 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6504 AuthorizationSet output_params;
6505 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6506 AuthorizationSetBuilder()
6507 .Digest(Digest::SHA_2_256)
6508 .Authorization(TAG_MAC_LENGTH, 256),
6509 &output_params));
6510}
6511
6512/*
6513 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6514 *
6515 * Verifies that importing early boot keys fails.
6516 */
6517TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6518 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6519 .Authorization(TAG_NO_AUTH_REQUIRED)
6520 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdale308916b2021-06-08 15:46:11 +01006521 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale216d9922021-05-18 11:43:31 +01006522 .Digest(Digest::SHA_2_256)
6523 .SetDefaultValidity(),
6524 KeyFormat::PKCS8, ec_256_key));
6525}
6526
David Drysdaled2cc8c22021-04-15 13:29:45 +01006527// 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 +00006528// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6529// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6530// early boot, so you'll have to reboot between runs.
6531TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6532 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6533 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6534 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6535 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6536 EXPECT_TRUE(
6537 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6538 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6539 EXPECT_TRUE(
6540 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6541
6542 // Should be able to use keys, since early boot has not ended
6543 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6544 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6545 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6546 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6547
6548 // End early boot
6549 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6550 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6551
6552 // Should not be able to use already-created keys.
6553 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6554 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6555 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6556 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6557
6558 CheckedDeleteKey(&aesKeyData.blob);
6559 CheckedDeleteKey(&hmacKeyData.blob);
6560 CheckedDeleteKey(&rsaKeyData.blob);
6561 CheckedDeleteKey(&ecdsaKeyData.blob);
6562
6563 // Should not be able to create new keys
6564 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6565 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6566
6567 CheckedDeleteKey(&aesKeyData.blob);
6568 CheckedDeleteKey(&hmacKeyData.blob);
6569 CheckedDeleteKey(&rsaKeyData.blob);
6570 CheckedDeleteKey(&ecdsaKeyData.blob);
6571}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006572
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006573INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6574
Shawn Willdend659c7c2021-02-19 14:51:51 -07006575using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006576
6577// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6578// between runs... and on most test devices there are no enrolled credentials so it can't be
6579// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6580// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6581// a manual test process, which includes unlocking between runs, which is why it's included here.
6582// Well, that and the fact that it's the only test we can do without also making calls into the
6583// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6584// implications might be, so that may or may not be a solution.
6585TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6586 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6587 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6588
6589 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6590 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6591 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6592 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6593
6594 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006595 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006596 ASSERT_EQ(ErrorCode::OK, rc);
6597 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6598 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6599 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6600 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6601
6602 CheckedDeleteKey(&aesKeyData.blob);
6603 CheckedDeleteKey(&hmacKeyData.blob);
6604 CheckedDeleteKey(&rsaKeyData.blob);
6605 CheckedDeleteKey(&ecdsaKeyData.blob);
6606}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006607
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006608INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6609
Janis Danisevskis24c04702020-12-16 18:28:39 -08006610} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006611
6612int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006613 std::cout << "Testing ";
6614 auto halInstances =
6615 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6616 std::cout << "HAL instances:\n";
6617 for (auto& entry : halInstances) {
6618 std::cout << " " << entry << '\n';
6619 }
6620
Selene Huang31ab4042020-04-29 04:22:39 -07006621 ::testing::InitGoogleTest(&argc, argv);
6622 for (int i = 1; i < argc; ++i) {
6623 if (argv[i][0] == '-') {
6624 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006625 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6626 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006627 }
6628 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006629 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6630 dump_Attestations = true;
6631 } else {
6632 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006633 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006634 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6635 if (std::string(argv[i]) == "--check_patchLevels") {
6636 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6637 }
Selene Huang31ab4042020-04-29 04:22:39 -07006638 }
6639 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006640 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006641}