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