blob: d4b828afd2cd63cb461a6532a9b5ed8c800df88f [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale92464372021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Selene Huang31ab4042020-04-29 04:22:39 -070074template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000075bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
76 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070077 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080078 if (auto p = authorizationValue(ttag, param)) {
79 return *p == expected_value;
80 }
81 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070082 });
83 return (it != set.end());
84}
85
86template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(),
89 [&](const KeyParameter& param) { return param.tag == tag; });
90 return (it != set.end());
91}
92
93constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
97 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
109
110string hex2str(string a) {
111 string b;
112 size_t num = a.size() / 2;
113 b.resize(num);
114 for (size_t i = 0; i < num; i++) {
115 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
116 }
117 return b;
118}
119
David Drysdaled2cc8c22021-04-15 13:29:45 +0100120string rsa_key = hex2str(
121 // RFC 5208 s5
122 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
123 "020100" // INTEGER length 1 value 0x00 (version)
124 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
125 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
126 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
127 "0500" // NULL (parameters)
128 // } end SEQUENCE (AlgorithmIdentifier)
129 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
130 // RFC 8017 A.1.2
131 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
132 "020100" // INTEGER length 1 value 0x00 (version)
133 "028181" // INTEGER length 0x81 value (modulus) ...
134 "00c6095409047d8634812d5a218176e4"
135 "5c41d60a75b13901f234226cffe77652"
136 "1c5a77b9e389417b71c0b6a44d13afe4"
137 "e4a2805d46c9da2935adb1ff0c1f24ea"
138 "06e62b20d776430a4d435157233c6f91"
139 "6783c30e310fcbd89b85c2d567711697"
140 "85ac12bca244abda72bfb19fc44d27c8"
141 "1e1d92de284f4061edfd99280745ea6d"
142 "25"
143 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
144 "028180" // INTEGER length 0x80 (privateExponent) value...
145 "1be0f04d9cae3718691f035338308e91"
146 "564b55899ffb5084d2460e6630257e05"
147 "b3ceab02972dfabcd6ce5f6ee2589eb6"
148 "7911ed0fac16e43a444b8c861e544a05"
149 "93365772f8baf6b22fc9e3c5f1024b06"
150 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
151 "ace7240290bef16c0b3f7f3cdd64ce3a"
152 "b5912cf6e32f39ab188358afcccd8081"
153 "0241" // INTEGER length 0x41 (prime1)
154 "00e4b49ef50f765d3b24dde01aceaaf1"
155 "30f2c76670a91a61ae08af497b4a82be"
156 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
157 "8c92bfab137fba2285227b83c342ff7c"
158 "55"
159 "0241" // INTEGER length 0x41 (prime2)
160 "00ddabb5839c4c7f6bf3d4183231f005"
161 "b31aa58affdda5c79e4cce217f6bc930"
162 "dbe563d480706c24e9ebfcab28a6cdef"
163 "d324b77e1bf7251b709092c24ff501fd"
164 "91"
165 "0240" // INTEGER length 0x40 (exponent1)
166 "23d4340eda3445d8cd26c14411da6fdc"
167 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
168 "842c1d280405bc2f6c1bea214a1d742a"
169 "b996b35b63a82a5e470fa88dbf823cdd"
170 "0240" // INTEGER length 0x40 (exponent2)
171 "1b7b57449ad30d1518249a5f56bb9829"
172 "4d4b6ac12ffc86940497a5a5837a6cf9"
173 "46262b494526d328c11e1126380fde04"
174 "c24f916dec250892db09a6d77cdba351"
175 "0240" // INTEGER length 0x40 (coefficient)
176 "7762cd8f4d050da56bd591adb515d24d"
177 "7ccd32cca0d05f866d583514bd7324d5"
178 "f33645e8ed8b4a1cb3cc4a1d67987399"
179 "f2a09f5b3fb68c88d5e5d90ac33492d6"
180 // } end SEQUENCE (PrivateKey)
181 // } end SEQUENCE (PrivateKeyInfo)
182);
Selene Huang31ab4042020-04-29 04:22:39 -0700183
Selene Huange5727e62021-04-13 22:41:20 -0700184/*
185 * DER-encoded PKCS#8 format RSA key. Generated using:
186 *
187 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
188 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100189string rsa_2048_key = hex2str(
190 // RFC 5208 s5
191 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
192 "020100" // INTEGER length 1 value 0x00 (version)
193 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
194 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
195 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
196 "0500" // NULL (parameters)
197 // } end SEQUENCE (AlgorithmIdentifier)
198 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
199 // RFC 8017 A.1.2
200 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
201 "020100" // INTEGER length 1 value 0x00 (version)
202 "02820101" // INTEGER length 0x101 value (modulus) ...
203 "00BEBC342B56D443B1299F9A6A7056E8"
204 "0A897E318476A5A18029E63B2ED739A6"
205 "1791D339F58DC763D9D14911F2EDEC38"
206 "3DEE11F6319B44510E7A3ECD9B79B973"
207 "82E49500ACF8117DC89CAF0E621F7775"
208 "6554A2FD4664BFE7AB8B59AB48340DBF"
209 "A27B93B5A81F6ECDEB02D0759307128D"
210 "F3E3BAD4055C8B840216DFAA5700670E"
211 "6C5126F0962FCB70FF308F25049164CC"
212 "F76CC2DA66A7DD9A81A714C2809D6918"
213 "6133D29D84568E892B6FFBF3199BDB14"
214 "383EE224407F190358F111A949552ABA"
215 "6714227D1BD7F6B20DD0CB88F9467B71"
216 "9339F33BFF35B3870B3F62204E4286B0"
217 "948EA348B524544B5F9838F29EE643B0"
218 "79EEF8A713B220D7806924CDF7295070"
219 "C5"
220 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
221 "02820100" // INTEGER length 0x100 (privateExponent) value...
222 "69F377F35F2F584EF075353CCD1CA997"
223 "38DB3DBC7C7FF35F9366CE176DFD1B13"
224 "5AB10030344ABF5FBECF1D4659FDEF1C"
225 "0FC430834BE1BE3911951377BB3D563A"
226 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
227 "2686C7B4B3C09A7B8354133E6F93F790"
228 "D59EAEB92E84C9A4339302CCE28FDF04"
229 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
230 "6AB706645BF074A4E4090D06FB163124"
231 "365FD5EE7A20D350E9958CC30D91326E"
232 "1B292E9EF5DB408EC42DAF737D201497"
233 "04D0A678A0FB5B5446863B099228A352"
234 "D604BA8091A164D01D5AB05397C71EAD"
235 "20BE2A08FC528FE442817809C787FEE4"
236 "AB97F97B9130D022153EDC6EB6CBE7B0"
237 "F8E3473F2E901209B5DB10F93604DB01"
238 "028181" // INTEGER length 0x81 (prime1)
239 "00E83C0998214941EA4F9293F1B77E2E"
240 "99E6CF305FAF358238E126124FEAF2EB"
241 "9724B2EA7B78E6032343821A80E55D1D"
242 "88FB12D220C3F41A56142FEC85796D19"
243 "17F1E8C774F142B67D3D6E7B7E6B4383"
244 "E94DB5929089DBB346D5BDAB40CC2D96"
245 "EE0409475E175C63BF78CFD744136740"
246 "838127EA723FF3FE7FA368C1311B4A4E"
247 "05"
248 "028181" // INTEGER length 0x81 (prime2)
249 "00D240FCC0F5D7715CDE21CB2DC86EA1"
250 "46132EA3B06F61FF2AF54BF38473F59D"
251 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
252 "B1B58C39F95E4798CCBB43E83D0119AC"
253 "F532F359CA743C85199F0286610E2009"
254 "97D7312917179AC9B67558773212EC96"
255 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
256 "94D94E066A0900B7B70E82A44FB30053"
257 "C1"
258 "028181" // INTEGER length 0x81 (exponent1)
259 "00AD15DA1CBD6A492B66851BA8C316D3"
260 "8AB700E2CFDDD926A658003513C54BAA"
261 "152B30021D667D20078F500F8AD3E7F3"
262 "945D74A891ED1A28EAD0FEEAEC8C14A8"
263 "E834CF46A13D1378C99D18940823CFDD"
264 "27EC5810D59339E0C34198AC638E09C8"
265 "7CBB1B634A9864AE9F4D5EB2D53514F6"
266 "7B4CAEC048C8AB849A02E397618F3271"
267 "35"
268 "028180" // INTEGER length 0x80 (exponent2)
269 "1FA2C1A5331880A92D8F3E281C617108"
270 "BF38244F16E352E69ED417C7153F9EC3"
271 "18F211839C643DCF8B4DD67CE2AC312E"
272 "95178D5D952F06B1BF779F4916924B70"
273 "F582A23F11304E02A5E7565AE22A35E7"
274 "4FECC8B6FDC93F92A1A37703E4CF0E63"
275 "783BD02EB716A7ECBBFA606B10B74D01"
276 "579522E7EF84D91FC522292108D902C1"
277 "028180" // INTEGER length 0x80 (coefficient)
278 "796FE3825F9DCC85DF22D58690065D93"
279 "898ACD65C087BEA8DA3A63BF4549B795"
280 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
281 "0D74F40DED8E1102C52152A31B6165F8"
282 "3A6722AECFCC35A493D7634664B888A0"
283 "8D3EB034F12EA28BFEE346E205D33482"
284 "7F778B16ED40872BD29FCB36536B6E93"
285 "FFB06778696B4A9D81BB0A9423E63DE5"
286 // } end SEQUENCE (PrivateKey)
287 // } end SEQUENCE (PrivateKeyInfo)
288);
Selene Huange5727e62021-04-13 22:41:20 -0700289
David Drysdaled2cc8c22021-04-15 13:29:45 +0100290string ec_256_key = hex2str(
291 // RFC 5208 s5
292 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
293 "020100" // INTEGER length 1 value 0 (version)
294 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
295 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
296 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
297 "0608" // OBJECT IDENTIFIER length 8 (param)
298 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
299 // } end SEQUENCE (AlgorithmIdentifier)
300 "046d" // OCTET STRING length 0x6d (privateKey) holding...
301 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
302 "020101" // INTEGER length 1 value 1 (version)
303 "0420" // OCTET STRING length 0x20 (privateKey)
304 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
305 "941eed09366bc03299986481f3a4d859"
306 "a144" // TAG [1] len 0x44 (publicKey) {
307 "03420004bf85d7720d07c25461683bc6"
308 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
309 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
310 "bcc41c6eb00083cf3376d11fd44949e0"
311 "b2183bfe"
312 // } end SEQUENCE (ECPrivateKey)
313 // } end SEQUENCE (PrivateKeyInfo)
314);
Selene Huang31ab4042020-04-29 04:22:39 -0700315
David Drysdaled2cc8c22021-04-15 13:29:45 +0100316string ec_521_key = hex2str(
317 // RFC 5208 s5
318 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
319 "020100" // INTEGER length 1 value 0 (version)
320 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
321 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
322 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
323 "0605" // OBJECT IDENTIFIER length 5 (param)
324 "2B81040023" // 1.3.132.0.35 (secp521r1)
325 // } end SEQUENCE (AlgorithmIdentifier)
326 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
327 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
328 "020101" // INTEGER length 1 value 1 (version)
329 "0442" // OCTET STRING length 0x42 (privateKey)
330 "0011458C586DB5DAA92AFAB03F4FE46A"
331 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
332 "9D18D7D08B5BCFA0E53C75B064AD51C4"
333 "49BAE0258D54B94B1E885DED08ED4FB2"
334 "5CE9"
335 "A18189" // TAG [1] len 0x89 (publicKey) {
336 "03818600040149EC11C6DF0FA122C6A9"
337 "AFD9754A4FA9513A627CA329E349535A"
338 "5629875A8ADFBE27DCB932C051986377"
339 "108D054C28C6F39B6F2C9AF81802F9F3"
340 "26B842FF2E5F3C00AB7635CFB36157FC"
341 "0882D574A10D839C1A0C049DC5E0D775"
342 "E2EE50671A208431BB45E78E70BEFE93"
343 "0DB34818EE4D5C26259F5C6B8E28A652"
344 "950F9F88D7B4B2C9D9"
345 // } end SEQUENCE (ECPrivateKey)
346 // } end SEQUENCE (PrivateKeyInfo)
347);
Selene Huang31ab4042020-04-29 04:22:39 -0700348
David Drysdaled2cc8c22021-04-15 13:29:45 +0100349string ec_256_key_rfc5915 = hex2str(
350 // RFC 5208 s5
351 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
352 "020100" // INTEGER length 1 value 0 (version)
353 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
354 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
355 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
356 "0608" // OBJECT IDENTIFIER length 8 (param)
357 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
358 // } end SEQUENCE (AlgorithmIdentifier)
359 "0479" // OCTET STRING length 0x79 (privateKey) holding...
360 // RFC 5915 s3
361 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
362 "020101" // INTEGER length 1 value 1 (version)
363 "0420" // OCTET STRING length 0x42 (privateKey)
364 "782370a8c8ce5537baadd04dcff079c8"
365 "158cfa9c67b818b38e8d21c9fa750c1d"
366 "a00a" // TAG [0] length 0xa (parameters)
367 "0608" // OBJECT IDENTIFIER length 8
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end TAG [0]
370 "a144" // TAG [1] length 0x44 (publicKey) {
371 "0342" // BIT STRING length 0x42
372 "00" // no pad bits
373 "04e2cc561ee701da0ad0ef0d176bb0c9"
374 "19d42e79c393fdc1bd6c4010d85cf2cf"
375 "8e68c905464666f98dad4f01573ba810"
376 "78b3428570a439ba3229fbc026c55068"
377 "2f"
378 // } end SEQUENCE (ECPrivateKey)
379 // } end SEQUENCE (PrivateKeyInfo)
380);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
David Drysdaled2cc8c22021-04-15 13:29:45 +0100382string ec_256_key_sec1 = hex2str(
383 // RFC 5208 s5
384 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
385 "020100" // INTEGER length 1 value 0 (version)
386 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
387 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
388 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
389 "0608" // OBJECT IDENTIFIER length 8 (param)
390 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
391 // } end SEQUENCE (AlgorithmIdentifier)
392 "046d" // OCTET STRING length 0x6d (privateKey) holding...
393 // SEC1-v2 C.4
394 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
395 "020101" // INTEGER length 1 value 0x01 (version)
396 "0420" // OCTET STRING length 0x20 (privateKey)
397 "782370a8c8ce5537baadd04dcff079c8"
398 "158cfa9c67b818b38e8d21c9fa750c1d"
399 "a144" // TAG [1] length 0x44 (publicKey) {
400 "0342" // BIT STRING length 0x42
401 "00" // no pad bits
402 "04e2cc561ee701da0ad0ef0d176bb0c9"
403 "19d42e79c393fdc1bd6c4010d85cf2cf"
404 "8e68c905464666f98dad4f01573ba810"
405 "78b3428570a439ba3229fbc026c55068"
406 "2f"
407 // } end TAG [1] (publicKey)
408 // } end SEQUENCE (PrivateKeyInfo)
409);
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411struct RSA_Delete {
412 void operator()(RSA* p) { RSA_free(p); }
413};
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415std::string make_string(const uint8_t* data, size_t length) {
416 return std::string(reinterpret_cast<const char*>(data), length);
417}
418
419template <size_t N>
420std::string make_string(const uint8_t (&a)[N]) {
421 return make_string(a, N);
422}
423
424class AidlBuf : public vector<uint8_t> {
425 typedef vector<uint8_t> super;
426
427 public:
428 AidlBuf() {}
429 AidlBuf(const super& other) : super(other) {}
430 AidlBuf(super&& other) : super(std::move(other)) {}
431 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
432
433 AidlBuf& operator=(const super& other) {
434 super::operator=(other);
435 return *this;
436 }
437
438 AidlBuf& operator=(super&& other) {
439 super::operator=(std::move(other));
440 return *this;
441 }
442
443 AidlBuf& operator=(const string& other) {
444 resize(other.size());
445 for (size_t i = 0; i < other.size(); ++i) {
446 (*this)[i] = static_cast<uint8_t>(other[i]);
447 }
448 return *this;
449 }
450
451 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
452};
453
David Drysdale4dc01072021-04-01 12:17:35 +0100454string device_suffix(const string& name) {
455 size_t pos = name.find('/');
456 if (pos == string::npos) {
457 return name;
458 }
459 return name.substr(pos + 1);
460}
461
462bool matching_rp_instance(const string& km_name,
463 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
464 string km_suffix = device_suffix(km_name);
465
466 vector<string> rp_names =
467 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
468 for (const string& rp_name : rp_names) {
469 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
470 // KeyMint instance, assume they match.
471 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
472 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
473 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
474 return true;
475 }
476 }
477 return false;
478}
479
Selene Huang31ab4042020-04-29 04:22:39 -0700480} // namespace
481
482class NewKeyGenerationTest : public KeyMintAidlTestBase {
483 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700484 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000485 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700486 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700487
Selene Huang31ab4042020-04-29 04:22:39 -0700488 // Check that some unexpected tags/values are NOT present.
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
490 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 }
492
493 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
494 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
497
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000499 }
500
501 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
502 // TODO(swillden): Distinguish which params should be in which auth list.
503 AuthorizationSet auths;
504 for (auto& entry : keyCharacteristics) {
505 auths.push_back(AuthorizationSet(entry.authorizations));
506 }
507 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
508
509 // Verify that App data, ROT and auth timeout are NOT included.
510 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
511 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700512 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
513
David Drysdaled2cc8c22021-04-15 13:29:45 +0100514 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
515 // never adds it.
516 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
517
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700519 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000520 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700521 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700522 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000523 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700524 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000525
David Drysdalebb3d85e2021-04-13 11:15:51 +0100526 if (check_patchLevels) {
527 // Should include vendor and boot patchlevels.
528 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
529 EXPECT_TRUE(vendor_pl);
530 EXPECT_EQ(*vendor_pl, vendor_patch_level());
531 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
532 EXPECT_TRUE(boot_pl);
533 }
534
David Drysdale7de9feb2021-03-05 14:56:19 +0000535 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700536 }
537};
538
539/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000540 * NewKeyGenerationTest.Aes
541 *
542 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
543 * have correct characteristics.
544 */
545TEST_P(NewKeyGenerationTest, Aes) {
546 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
547 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
548 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
549 SCOPED_TRACE(testing::Message()
550 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
551 vector<uint8_t> key_blob;
552 vector<KeyCharacteristics> key_characteristics;
553 auto builder = AuthorizationSetBuilder()
554 .AesEncryptionKey(key_size)
555 .BlockMode(block_mode)
556 .Padding(padding_mode)
557 .SetDefaultValidity();
558 if (block_mode == BlockMode::GCM) {
559 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
560 }
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
562
563 EXPECT_GT(key_blob.size(), 0U);
564 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100565 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000566
567 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
568
569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
571 << "Key size " << key_size << "missing";
572
573 CheckedDeleteKey(&key_blob);
574 }
575 }
576 }
577}
578
579/*
580 * NewKeyGenerationTest.AesInvalidSize
581 *
582 * Verifies that specifying an invalid key size for AES key generation returns
583 * UNSUPPORTED_KEY_SIZE.
584 */
585TEST_P(NewKeyGenerationTest, AesInvalidSize) {
586 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
587 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
588 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
589 SCOPED_TRACE(testing::Message()
590 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
591 vector<uint8_t> key_blob;
592 vector<KeyCharacteristics> key_characteristics;
593 auto builder = AuthorizationSetBuilder()
594 .AesEncryptionKey(key_size)
595 .BlockMode(block_mode)
596 .Padding(padding_mode)
597 .SetDefaultValidity();
598 if (block_mode == BlockMode::GCM) {
599 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
600 }
601 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
602 GenerateKey(builder, &key_blob, &key_characteristics));
603 }
604 }
605 }
606
607 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
608 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611 // No key size specified
612 auto builder = AuthorizationSetBuilder()
613 .Authorization(TAG_ALGORITHM, Algorithm::AES)
614 .BlockMode(block_mode)
615 .Padding(padding_mode)
616 .SetDefaultValidity();
617 if (block_mode == BlockMode::GCM) {
618 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
619 }
620 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
621 GenerateKey(builder, &key_blob, &key_characteristics));
622 }
623 }
624}
625
626/*
627 * NewKeyGenerationTest.AesInvalidPadding
628 *
629 * Verifies that specifying an invalid padding on AES keys gives a failure
630 * somewhere along the way.
631 */
632TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
633 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
634 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
635 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
636 SCOPED_TRACE(testing::Message()
637 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000638 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 .AesEncryptionKey(key_size)
641 .BlockMode(block_mode)
642 .Padding(padding_mode)
643 .SetDefaultValidity();
644 if (block_mode == BlockMode::GCM) {
645 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
646 }
647
Tommy Chiu3950b452021-05-03 22:01:46 +0800648 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 if (result == ErrorCode::OK) {
650 // Key creation was OK but has generated a key that cannot be used.
651 auto params =
652 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800653 if (block_mode == BlockMode::GCM) {
654 params.Authorization(TAG_MAC_LENGTH, 128);
655 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 auto result = Begin(KeyPurpose::ENCRYPT, params);
657 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100658 result == ErrorCode::INVALID_KEY_BLOB)
659 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000660 } else {
661 // The KeyMint implementation detected that the generated key
662 // is unusable.
663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
664 }
665 }
666 }
667 }
668}
669
670/*
671 * NewKeyGenerationTest.AesGcmMissingMinMac
672 *
673 * Verifies that specifying an invalid key size for AES key generation returns
674 * UNSUPPORTED_KEY_SIZE.
675 */
676TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
677 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
678 BlockMode block_mode = BlockMode::GCM;
679 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
680 SCOPED_TRACE(testing::Message()
681 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
682 vector<uint8_t> key_blob;
683 vector<KeyCharacteristics> key_characteristics;
684 // No MIN_MAC_LENGTH provided.
685 auto builder = AuthorizationSetBuilder()
686 .AesEncryptionKey(key_size)
687 .BlockMode(block_mode)
688 .Padding(padding_mode)
689 .SetDefaultValidity();
690 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
691 GenerateKey(builder, &key_blob, &key_characteristics));
692 }
693 }
694}
695
696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100697 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
698 *
699 * Verifies that specifying an invalid min MAC size for AES key generation returns
700 * UNSUPPORTED_MIN_MAC_LENGTH.
701 */
702TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
703 for (size_t min_mac_len : {88, 136}) {
704 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
705 BlockMode block_mode = BlockMode::GCM;
706 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
707 SCOPED_TRACE(testing::Message()
708 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
709 vector<uint8_t> key_blob;
710 vector<KeyCharacteristics> key_characteristics;
711 auto builder = AuthorizationSetBuilder()
712 .AesEncryptionKey(key_size)
713 .BlockMode(block_mode)
714 .Padding(padding_mode)
715 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
716 .SetDefaultValidity();
717 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
718 GenerateKey(builder, &key_blob, &key_characteristics));
719 }
720 }
721 }
722}
723
724/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000725 * NewKeyGenerationTest.TripleDes
726 *
727 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
728 * have correct characteristics.
729 */
730TEST_P(NewKeyGenerationTest, TripleDes) {
731 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
732 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
733 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
734 SCOPED_TRACE(testing::Message()
735 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
736 vector<uint8_t> key_blob;
737 vector<KeyCharacteristics> key_characteristics;
738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
739 .TripleDesEncryptionKey(key_size)
740 .BlockMode(block_mode)
741 .Padding(padding_mode)
742 .Authorization(TAG_NO_AUTH_REQUIRED)
743 .SetDefaultValidity(),
744 &key_blob, &key_characteristics));
745
746 EXPECT_GT(key_blob.size(), 0U);
747 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100748 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000749
750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
751
752 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
753 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
754 << "Key size " << key_size << "missing";
755
756 CheckedDeleteKey(&key_blob);
757 }
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.TripleDesWithAttestation
764 *
765 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
766 * have correct characteristics.
767 *
768 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
769 * put in a certificate) but which isn't an error.
770 */
771TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
772 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
773 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
774 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
775 SCOPED_TRACE(testing::Message()
776 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
777
778 auto challenge = "hello";
779 auto app_id = "foo";
780
781 vector<uint8_t> key_blob;
782 vector<KeyCharacteristics> key_characteristics;
783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
784 .TripleDesEncryptionKey(key_size)
785 .BlockMode(block_mode)
786 .Padding(padding_mode)
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AttestationChallenge(challenge)
789 .AttestationApplicationId(app_id)
790 .SetDefaultValidity(),
791 &key_blob, &key_characteristics));
792
793 EXPECT_GT(key_blob.size(), 0U);
794 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100795 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000796
797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
798
799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
800 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
801 << "Key size " << key_size << "missing";
802
803 CheckedDeleteKey(&key_blob);
804 }
805 }
806 }
807}
808
809/*
810 * NewKeyGenerationTest.TripleDesInvalidSize
811 *
812 * Verifies that specifying an invalid key size for 3-DES key generation returns
813 * UNSUPPORTED_KEY_SIZE.
814 */
815TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
816 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
817 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
818 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
819 SCOPED_TRACE(testing::Message()
820 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
821 vector<uint8_t> key_blob;
822 vector<KeyCharacteristics> key_characteristics;
823 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
824 GenerateKey(AuthorizationSetBuilder()
825 .TripleDesEncryptionKey(key_size)
826 .BlockMode(block_mode)
827 .Padding(padding_mode)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .SetDefaultValidity(),
830 &key_blob, &key_characteristics));
831 }
832 }
833 }
834
835 // Omitting the key size fails.
836 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
837 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
838 SCOPED_TRACE(testing::Message()
839 << "3DES-default-" << block_mode << "-" << padding_mode);
840 vector<uint8_t> key_blob;
841 vector<KeyCharacteristics> key_characteristics;
842 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
843 GenerateKey(AuthorizationSetBuilder()
844 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
845 .BlockMode(block_mode)
846 .Padding(padding_mode)
847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity(),
849 &key_blob, &key_characteristics));
850 }
851 }
852}
853
854/*
Selene Huang31ab4042020-04-29 04:22:39 -0700855 * NewKeyGenerationTest.Rsa
856 *
857 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
858 * have correct characteristics.
859 */
860TEST_P(NewKeyGenerationTest, Rsa) {
861 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
862 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700863 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
865 .RsaSigningKey(key_size, 65537)
866 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700869 &key_blob, &key_characteristics));
870
871 ASSERT_GT(key_blob.size(), 0U);
872 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100873 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700874
Shawn Willden7f424372021-01-10 18:06:50 -0700875 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
877 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
878 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
879 << "Key size " << key_size << "missing";
880 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
881
882 CheckedDeleteKey(&key_blob);
883 }
884}
885
886/*
Qi Wud22ec842020-11-26 13:27:53 +0800887 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100889 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
890 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891 */
892TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700893 auto challenge = "hello";
894 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700895
Selene Huang6e46f142021-04-20 19:20:11 -0700896 auto subject = "cert subj 2";
897 vector<uint8_t> subject_der(make_name_from_str(subject));
898
899 uint64_t serial_int = 66;
900 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
901
Selene Huang4f64c222021-04-13 19:54:36 -0700902 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700905 ASSERT_EQ(ErrorCode::OK,
906 GenerateKey(AuthorizationSetBuilder()
907 .RsaSigningKey(key_size, 65537)
908 .Digest(Digest::NONE)
909 .Padding(PaddingMode::NONE)
910 .AttestationChallenge(challenge)
911 .AttestationApplicationId(app_id)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
914 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
915 .SetDefaultValidity(),
916 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700917
918 ASSERT_GT(key_blob.size(), 0U);
919 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100920 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700921
922 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
923
924 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
925 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
926 << "Key size " << key_size << "missing";
927 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
928
Selene Huang6e46f142021-04-20 19:20:11 -0700929 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700930 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931 ASSERT_GT(cert_chain_.size(), 0);
932
933 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
934 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
935 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
936 sw_enforced, hw_enforced, SecLevel(),
937 cert_chain_[0].encodedCertificate));
938
939 CheckedDeleteKey(&key_blob);
940 }
941}
942
943/*
David Drysdale4dc01072021-04-01 12:17:35 +0100944 * NewKeyGenerationTest.RsaWithRpkAttestation
945 *
946 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
947 * that has been generated using an associate IRemotelyProvisionedComponent.
948 */
949TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
950 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
951 // instance.
952 std::shared_ptr<IRemotelyProvisionedComponent> rp;
953 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
954 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
955
956 // Generate a P-256 keypair to use as an attestation key.
957 MacedPublicKey macedPubKey;
958 std::vector<uint8_t> privateKeyBlob;
959 auto status =
960 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
961 ASSERT_TRUE(status.isOk());
962 vector<uint8_t> coseKeyData;
963 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
964
965 AttestationKey attestation_key;
966 attestation_key.keyBlob = std::move(privateKeyBlob);
967 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
968
969 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
970 auto challenge = "hello";
971 auto app_id = "foo";
972
973 vector<uint8_t> key_blob;
974 vector<KeyCharacteristics> key_characteristics;
975 ASSERT_EQ(ErrorCode::OK,
976 GenerateKey(AuthorizationSetBuilder()
977 .RsaSigningKey(key_size, 65537)
978 .Digest(Digest::NONE)
979 .Padding(PaddingMode::NONE)
980 .AttestationChallenge(challenge)
981 .AttestationApplicationId(app_id)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
985
986 ASSERT_GT(key_blob.size(), 0U);
987 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100988 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100989
990 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
991
992 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
993 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
994 << "Key size " << key_size << "missing";
995 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
996
997 // Attestation by itself is not valid (last entry is not self-signed).
998 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
999
1000 // The signature over the attested key should correspond to the P256 public key.
1001 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1002 ASSERT_TRUE(key_cert.get());
1003 EVP_PKEY_Ptr signing_pubkey;
1004 p256_pub_key(coseKeyData, &signing_pubkey);
1005 ASSERT_TRUE(signing_pubkey.get());
1006
1007 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1008 << "Verification of attested certificate failed "
1009 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1010
1011 CheckedDeleteKey(&key_blob);
1012 }
1013}
1014
1015/*
Selene Huang4f64c222021-04-13 19:54:36 -07001016 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1017 *
1018 * Verifies that keymint attestation for RSA encryption keys with challenge and
1019 * app id is also successful.
1020 */
1021TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1022 auto key_size = 2048;
1023 auto challenge = "hello";
1024 auto app_id = "foo";
1025
Selene Huang6e46f142021-04-20 19:20:11 -07001026 auto subject = "subj 2";
1027 vector<uint8_t> subject_der(make_name_from_str(subject));
1028
1029 uint64_t serial_int = 111166;
1030 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1031
Selene Huang4f64c222021-04-13 19:54:36 -07001032 vector<uint8_t> key_blob;
1033 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001034 ASSERT_EQ(ErrorCode::OK,
1035 GenerateKey(AuthorizationSetBuilder()
1036 .RsaEncryptionKey(key_size, 65537)
1037 .Padding(PaddingMode::NONE)
1038 .AttestationChallenge(challenge)
1039 .AttestationApplicationId(app_id)
1040 .Authorization(TAG_NO_AUTH_REQUIRED)
1041 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1042 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1043 .SetDefaultValidity(),
1044 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001045
1046 ASSERT_GT(key_blob.size(), 0U);
1047 AuthorizationSet auths;
1048 for (auto& entry : key_characteristics) {
1049 auths.push_back(AuthorizationSet(entry.authorizations));
1050 }
1051
1052 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1053 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1054
1055 // Verify that App data and ROT are NOT included.
1056 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1057 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1058
1059 // Check that some unexpected tags/values are NOT present.
1060 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1061 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1062
1063 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1064
1065 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1066 ASSERT_TRUE(os_ver);
1067 EXPECT_EQ(*os_ver, os_version());
1068
1069 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1070
1071 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1072 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1073 << "Key size " << key_size << "missing";
1074 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1075
Selene Huang6e46f142021-04-20 19:20:11 -07001076 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001077 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1078 ASSERT_GT(cert_chain_.size(), 0);
1079
1080 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1081 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1082 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1083 sw_enforced, hw_enforced, SecLevel(),
1084 cert_chain_[0].encodedCertificate));
1085
1086 CheckedDeleteKey(&key_blob);
1087}
1088
1089/*
1090 * NewKeyGenerationTest.RsaWithSelfSign
1091 *
1092 * Verifies that attesting to RSA key generation is successful, and returns
1093 * self signed certificate if no challenge is provided. And signing etc
1094 * works as expected.
1095 */
1096TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001097 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1098 vector<uint8_t> subject_der(make_name_from_str(subject));
1099
1100 uint64_t serial_int = 0;
1101 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1102
Selene Huang4f64c222021-04-13 19:54:36 -07001103 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1104 vector<uint8_t> key_blob;
1105 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001106 ASSERT_EQ(ErrorCode::OK,
1107 GenerateKey(AuthorizationSetBuilder()
1108 .RsaSigningKey(key_size, 65537)
1109 .Digest(Digest::NONE)
1110 .Padding(PaddingMode::NONE)
1111 .Authorization(TAG_NO_AUTH_REQUIRED)
1112 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1113 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1114 .SetDefaultValidity(),
1115 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001116
1117 ASSERT_GT(key_blob.size(), 0U);
1118 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001119 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001120
1121 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1122
1123 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1124 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1125 << "Key size " << key_size << "missing";
1126 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1127
Selene Huang6e46f142021-04-20 19:20:11 -07001128 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001129 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1130 ASSERT_EQ(cert_chain_.size(), 1);
1131
1132 CheckedDeleteKey(&key_blob);
1133 }
1134}
1135
1136/*
1137 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1138 *
1139 * Verifies that attesting to RSA checks for missing app ID.
1140 */
1141TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1142 auto challenge = "hello";
1143 vector<uint8_t> key_blob;
1144 vector<KeyCharacteristics> key_characteristics;
1145
1146 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1147 GenerateKey(AuthorizationSetBuilder()
1148 .RsaSigningKey(2048, 65537)
1149 .Digest(Digest::NONE)
1150 .Padding(PaddingMode::NONE)
1151 .AttestationChallenge(challenge)
1152 .Authorization(TAG_NO_AUTH_REQUIRED)
1153 .SetDefaultValidity(),
1154 &key_blob, &key_characteristics));
1155}
1156
1157/*
1158 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1159 *
1160 * Verifies that attesting to RSA ignores app id if challenge is missing.
1161 */
1162TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1163 auto key_size = 2048;
1164 auto app_id = "foo";
1165
Selene Huang6e46f142021-04-20 19:20:11 -07001166 auto subject = "cert subj 2";
1167 vector<uint8_t> subject_der(make_name_from_str(subject));
1168
1169 uint64_t serial_int = 1;
1170 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1171
Selene Huang4f64c222021-04-13 19:54:36 -07001172 vector<uint8_t> key_blob;
1173 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001174 ASSERT_EQ(ErrorCode::OK,
1175 GenerateKey(AuthorizationSetBuilder()
1176 .RsaSigningKey(key_size, 65537)
1177 .Digest(Digest::NONE)
1178 .Padding(PaddingMode::NONE)
1179 .AttestationApplicationId(app_id)
1180 .Authorization(TAG_NO_AUTH_REQUIRED)
1181 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1182 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1183 .SetDefaultValidity(),
1184 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001185
1186 ASSERT_GT(key_blob.size(), 0U);
1187 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001188 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001189
1190 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1191
1192 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1193 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1194 << "Key size " << key_size << "missing";
1195 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1196
Selene Huang6e46f142021-04-20 19:20:11 -07001197 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001198 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1199 ASSERT_EQ(cert_chain_.size(), 1);
1200
1201 CheckedDeleteKey(&key_blob);
1202}
1203
1204/*
Qi Wud22ec842020-11-26 13:27:53 +08001205 * NewKeyGenerationTest.LimitedUsageRsa
1206 *
1207 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1208 * resulting keys have correct characteristics.
1209 */
1210TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1211 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1212 vector<uint8_t> key_blob;
1213 vector<KeyCharacteristics> key_characteristics;
1214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1215 .RsaSigningKey(key_size, 65537)
1216 .Digest(Digest::NONE)
1217 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001218 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1219 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001220 &key_blob, &key_characteristics));
1221
1222 ASSERT_GT(key_blob.size(), 0U);
1223 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001224 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001225
1226 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1227
1228 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1229 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1230 << "Key size " << key_size << "missing";
1231 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1232
1233 // Check the usage count limit tag appears in the authorizations.
1234 AuthorizationSet auths;
1235 for (auto& entry : key_characteristics) {
1236 auths.push_back(AuthorizationSet(entry.authorizations));
1237 }
1238 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1239 << "key usage count limit " << 1U << " missing";
1240
1241 CheckedDeleteKey(&key_blob);
1242 }
1243}
1244
1245/*
Qi Wubeefae42021-01-28 23:16:37 +08001246 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1247 *
1248 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1249 * resulting keys have correct characteristics and attestation.
1250 */
1251TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001252 auto challenge = "hello";
1253 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001254
Selene Huang6e46f142021-04-20 19:20:11 -07001255 auto subject = "cert subj 2";
1256 vector<uint8_t> subject_der(make_name_from_str(subject));
1257
1258 uint64_t serial_int = 66;
1259 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1260
Selene Huang4f64c222021-04-13 19:54:36 -07001261 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001262 vector<uint8_t> key_blob;
1263 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001264 ASSERT_EQ(ErrorCode::OK,
1265 GenerateKey(AuthorizationSetBuilder()
1266 .RsaSigningKey(key_size, 65537)
1267 .Digest(Digest::NONE)
1268 .Padding(PaddingMode::NONE)
1269 .AttestationChallenge(challenge)
1270 .AttestationApplicationId(app_id)
1271 .Authorization(TAG_NO_AUTH_REQUIRED)
1272 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1273 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1274 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1275 .SetDefaultValidity(),
1276 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001277
1278 ASSERT_GT(key_blob.size(), 0U);
1279 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001280 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001281
1282 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1283
1284 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1285 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1286 << "Key size " << key_size << "missing";
1287 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1288
1289 // Check the usage count limit tag appears in the authorizations.
1290 AuthorizationSet auths;
1291 for (auto& entry : key_characteristics) {
1292 auths.push_back(AuthorizationSet(entry.authorizations));
1293 }
1294 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1295 << "key usage count limit " << 1U << " missing";
1296
1297 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001298 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001299 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001300 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001301
1302 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1303 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1304 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1305 sw_enforced, hw_enforced, SecLevel(),
1306 cert_chain_[0].encodedCertificate));
1307
1308 CheckedDeleteKey(&key_blob);
1309 }
1310}
1311
1312/*
Selene Huang31ab4042020-04-29 04:22:39 -07001313 * NewKeyGenerationTest.NoInvalidRsaSizes
1314 *
1315 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1316 */
1317TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1318 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1319 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001320 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001321 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1322 GenerateKey(AuthorizationSetBuilder()
1323 .RsaSigningKey(key_size, 65537)
1324 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001325 .Padding(PaddingMode::NONE)
1326 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001327 &key_blob, &key_characteristics));
1328 }
1329}
1330
1331/*
1332 * NewKeyGenerationTest.RsaNoDefaultSize
1333 *
1334 * Verifies that failing to specify a key size for RSA key generation returns
1335 * UNSUPPORTED_KEY_SIZE.
1336 */
1337TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1338 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1339 GenerateKey(AuthorizationSetBuilder()
1340 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1341 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001342 .SigningKey()
1343 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001344}
1345
1346/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001347 * NewKeyGenerationTest.RsaMissingParams
1348 *
1349 * Verifies that omitting optional tags works.
1350 */
1351TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1352 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1353 ASSERT_EQ(ErrorCode::OK,
1354 GenerateKey(
1355 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1356 CheckedDeleteKey();
1357 }
1358}
1359
1360/*
Selene Huang31ab4042020-04-29 04:22:39 -07001361 * NewKeyGenerationTest.Ecdsa
1362 *
1363 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1364 * have correct characteristics.
1365 */
1366TEST_P(NewKeyGenerationTest, Ecdsa) {
1367 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1368 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001369 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1371 .EcdsaSigningKey(key_size)
1372 .Digest(Digest::NONE)
1373 .SetDefaultValidity(),
1374 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001375 ASSERT_GT(key_blob.size(), 0U);
1376 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001377 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001378
Shawn Willden7f424372021-01-10 18:06:50 -07001379 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001380
1381 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1382 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1383 << "Key size " << key_size << "missing";
1384
1385 CheckedDeleteKey(&key_blob);
1386 }
1387}
1388
1389/*
Selene Huang4f64c222021-04-13 19:54:36 -07001390 * NewKeyGenerationTest.EcdsaAttestation
1391 *
1392 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1393 * an attestation will be generated.
1394 */
1395TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1396 auto challenge = "hello";
1397 auto app_id = "foo";
1398
Selene Huang6e46f142021-04-20 19:20:11 -07001399 auto subject = "cert subj 2";
1400 vector<uint8_t> subject_der(make_name_from_str(subject));
1401
1402 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1403 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1404
Selene Huang4f64c222021-04-13 19:54:36 -07001405 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1406 vector<uint8_t> key_blob;
1407 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001408 ASSERT_EQ(ErrorCode::OK,
1409 GenerateKey(AuthorizationSetBuilder()
1410 .Authorization(TAG_NO_AUTH_REQUIRED)
1411 .EcdsaSigningKey(key_size)
1412 .Digest(Digest::NONE)
1413 .AttestationChallenge(challenge)
1414 .AttestationApplicationId(app_id)
1415 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1416 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1417 .SetDefaultValidity(),
1418 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001419 ASSERT_GT(key_blob.size(), 0U);
1420 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001421 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001422
1423 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1424
1425 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1426 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1427 << "Key size " << key_size << "missing";
1428
1429 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1430 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001431 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001432
1433 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1434 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1435 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1436 sw_enforced, hw_enforced, SecLevel(),
1437 cert_chain_[0].encodedCertificate));
1438
1439 CheckedDeleteKey(&key_blob);
1440 }
1441}
1442
1443/*
David Drysdale92464372021-05-14 16:46:59 +01001444 * NewKeyGenerationTest.EcdsaAttestationTags
1445 *
1446 * Verifies that creation of an attested ECDSA key includes various tags in the
1447 * attestation extension.
1448 */
1449TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1450 auto challenge = "hello";
1451 auto app_id = "foo";
1452 auto subject = "cert subj 2";
1453 vector<uint8_t> subject_der(make_name_from_str(subject));
1454 uint64_t serial_int = 0x1010;
1455 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1456 const AuthorizationSetBuilder base_builder =
1457 AuthorizationSetBuilder()
1458 .Authorization(TAG_NO_AUTH_REQUIRED)
1459 .EcdsaSigningKey(256)
1460 .Digest(Digest::NONE)
1461 .AttestationChallenge(challenge)
1462 .AttestationApplicationId(app_id)
1463 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1464 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1465 .SetDefaultValidity();
1466
1467 // Various tags that map to fields in the attestation extension ASN.1 schema.
1468 auto extra_tags = AuthorizationSetBuilder()
1469 .Authorization(TAG_ROLLBACK_RESISTANCE)
1470 .Authorization(TAG_EARLY_BOOT_ONLY)
1471 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1472 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1473 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1474 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1475 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1476 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1477 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1478 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1479 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1480 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1481 for (const KeyParameter& tag : extra_tags) {
1482 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1483 vector<uint8_t> key_blob;
1484 vector<KeyCharacteristics> key_characteristics;
1485 AuthorizationSetBuilder builder = base_builder;
1486 builder.push_back(tag);
1487 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1488 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1489 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1490 continue;
1491 }
1492 if (result == ErrorCode::UNSUPPORTED_TAG &&
1493 (tag.tag == TAG_ALLOW_WHILE_ON_BODY || tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1494 // Optional tag not supported by this KeyMint implementation.
1495 continue;
1496 }
1497 ASSERT_EQ(result, ErrorCode::OK);
1498 ASSERT_GT(key_blob.size(), 0U);
1499
1500 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1501 ASSERT_GT(cert_chain_.size(), 0);
1502 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1503
1504 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1505 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1506 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID) {
1507 // Expect to find most of the extra tags in the key characteristics
1508 // of the generated key (but not for ATTESTATION_APPLICATION_ID).
1509 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)
1539 .EcdsaSigningKey(256)
1540 .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
Selene Huang4f64c222021-04-13 19:54:36 -07001620 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1621 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()
1625 .EcdsaSigningKey(key_size)
1626 .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));
1638 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1639 << "Key size " << key_size << "missing";
1640
1641 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001642 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001643 ASSERT_EQ(cert_chain_.size(), 1);
1644
1645 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1646 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1647
1648 CheckedDeleteKey(&key_blob);
1649 }
1650}
1651
1652/*
1653 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1654 *
1655 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1656 * app id must also be provided or else it will fail.
1657 */
1658TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1659 auto challenge = "hello";
1660 vector<uint8_t> key_blob;
1661 vector<KeyCharacteristics> key_characteristics;
1662
1663 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1664 GenerateKey(AuthorizationSetBuilder()
1665 .EcdsaSigningKey(EcCurve::P_256)
1666 .Digest(Digest::NONE)
1667 .AttestationChallenge(challenge)
1668 .SetDefaultValidity(),
1669 &key_blob, &key_characteristics));
1670}
1671
1672/*
1673 * NewKeyGenerationTest.EcdsaIgnoreAppId
1674 *
1675 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1676 * any appid will be ignored, and keymint will generate a self sign certificate.
1677 */
1678TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1679 auto app_id = "foo";
1680
1681 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1682 vector<uint8_t> key_blob;
1683 vector<KeyCharacteristics> key_characteristics;
1684 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1685 .EcdsaSigningKey(key_size)
1686 .Digest(Digest::NONE)
1687 .AttestationApplicationId(app_id)
1688 .SetDefaultValidity(),
1689 &key_blob, &key_characteristics));
1690
1691 ASSERT_GT(key_blob.size(), 0U);
1692 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001693 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001694
1695 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1696
1697 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1698 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1699 << "Key size " << key_size << "missing";
1700
1701 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1702 ASSERT_EQ(cert_chain_.size(), 1);
1703
1704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1706
1707 CheckedDeleteKey(&key_blob);
1708 }
1709}
1710
1711/*
1712 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1713 *
1714 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1715 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1716 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1717 * to specify how many following bytes will be used to encode the length.
1718 */
1719TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1720 auto challenge = "hello";
1721 auto key_size = 256;
1722 std::vector<uint32_t> app_id_lengths{143, 258};
1723
1724 for (uint32_t length : app_id_lengths) {
1725 const string app_id(length, 'a');
1726 vector<uint8_t> key_blob;
1727 vector<KeyCharacteristics> key_characteristics;
1728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1729 .Authorization(TAG_NO_AUTH_REQUIRED)
1730 .EcdsaSigningKey(key_size)
1731 .Digest(Digest::NONE)
1732 .AttestationChallenge(challenge)
1733 .AttestationApplicationId(app_id)
1734 .SetDefaultValidity(),
1735 &key_blob, &key_characteristics));
1736 ASSERT_GT(key_blob.size(), 0U);
1737 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001738 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001739
1740 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1741
1742 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1743 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1744 << "Key size " << key_size << "missing";
1745
1746 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1747 ASSERT_GT(cert_chain_.size(), 0);
1748
1749 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1750 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1751 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1752 sw_enforced, hw_enforced, SecLevel(),
1753 cert_chain_[0].encodedCertificate));
1754
1755 CheckedDeleteKey(&key_blob);
1756 }
1757}
1758
1759/*
Qi Wud22ec842020-11-26 13:27:53 +08001760 * NewKeyGenerationTest.LimitedUsageEcdsa
1761 *
1762 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1763 * resulting keys have correct characteristics.
1764 */
1765TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1766 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1767 vector<uint8_t> key_blob;
1768 vector<KeyCharacteristics> key_characteristics;
1769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1770 .EcdsaSigningKey(key_size)
1771 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001772 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1773 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001774 &key_blob, &key_characteristics));
1775
1776 ASSERT_GT(key_blob.size(), 0U);
1777 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001778 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001779
1780 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1781
1782 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1783 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1784 << "Key size " << key_size << "missing";
1785
1786 // Check the usage count limit tag appears in the authorizations.
1787 AuthorizationSet auths;
1788 for (auto& entry : key_characteristics) {
1789 auths.push_back(AuthorizationSet(entry.authorizations));
1790 }
1791 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1792 << "key usage count limit " << 1U << " missing";
1793
1794 CheckedDeleteKey(&key_blob);
1795 }
1796}
1797
1798/*
Selene Huang31ab4042020-04-29 04:22:39 -07001799 * NewKeyGenerationTest.EcdsaDefaultSize
1800 *
1801 * Verifies that failing to specify a key size for EC key generation returns
1802 * UNSUPPORTED_KEY_SIZE.
1803 */
1804TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1805 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1806 GenerateKey(AuthorizationSetBuilder()
1807 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1808 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001809 .Digest(Digest::NONE)
1810 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001811}
1812
1813/*
1814 * NewKeyGenerationTest.EcdsaInvalidSize
1815 *
1816 * Verifies that specifying an invalid key size for EC key generation returns
1817 * UNSUPPORTED_KEY_SIZE.
1818 */
1819TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1820 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1821 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001822 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001823 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1824 .EcdsaSigningKey(key_size)
1825 .Digest(Digest::NONE)
1826 .SetDefaultValidity(),
1827 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001828 }
1829
Janis Danisevskis164bb872021-02-09 11:30:25 -08001830 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1831 .EcdsaSigningKey(190)
1832 .Digest(Digest::NONE)
1833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001834}
1835
1836/*
1837 * NewKeyGenerationTest.EcdsaMismatchKeySize
1838 *
1839 * Verifies that specifying mismatched key size and curve for EC key generation returns
1840 * INVALID_ARGUMENT.
1841 */
1842TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1843 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1844
1845 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1846 GenerateKey(AuthorizationSetBuilder()
1847 .EcdsaSigningKey(224)
1848 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001849 .Digest(Digest::NONE)
1850 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001851}
1852
1853/*
1854 * NewKeyGenerationTest.EcdsaAllValidSizes
1855 *
1856 * Verifies that keymint supports all required EC key sizes.
1857 */
1858TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1859 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1860 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001861 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1862 .EcdsaSigningKey(size)
1863 .Digest(Digest::NONE)
1864 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001865 << "Failed to generate size: " << size;
1866 CheckedDeleteKey();
1867 }
1868}
1869
1870/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001871 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001872 *
1873 * Verifies that keymint does not support any curve designated as unsupported.
1874 */
1875TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1876 Digest digest;
1877 if (SecLevel() == SecurityLevel::STRONGBOX) {
1878 digest = Digest::SHA_2_256;
1879 } else {
1880 digest = Digest::SHA_2_512;
1881 }
1882 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001883 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1884 .EcdsaSigningKey(curve)
1885 .Digest(digest)
1886 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001887 << "Failed to generate key on curve: " << curve;
1888 CheckedDeleteKey();
1889 }
1890}
1891
1892/*
1893 * NewKeyGenerationTest.Hmac
1894 *
1895 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1896 * characteristics.
1897 */
1898TEST_P(NewKeyGenerationTest, Hmac) {
1899 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1900 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001901 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001902 constexpr size_t key_size = 128;
1903 ASSERT_EQ(ErrorCode::OK,
1904 GenerateKey(
1905 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1906 TAG_MIN_MAC_LENGTH, 128),
1907 &key_blob, &key_characteristics));
1908
1909 ASSERT_GT(key_blob.size(), 0U);
1910 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001911 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001912
Shawn Willden7f424372021-01-10 18:06:50 -07001913 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1914 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1915 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1916 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001917
1918 CheckedDeleteKey(&key_blob);
1919 }
1920}
1921
1922/*
Selene Huang4f64c222021-04-13 19:54:36 -07001923 * NewKeyGenerationTest.HmacNoAttestation
1924 *
1925 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1926 * and app id are provided.
1927 */
1928TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1929 auto challenge = "hello";
1930 auto app_id = "foo";
1931
1932 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1933 vector<uint8_t> key_blob;
1934 vector<KeyCharacteristics> key_characteristics;
1935 constexpr size_t key_size = 128;
1936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1937 .HmacKey(key_size)
1938 .Digest(digest)
1939 .AttestationChallenge(challenge)
1940 .AttestationApplicationId(app_id)
1941 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1942 &key_blob, &key_characteristics));
1943
1944 ASSERT_GT(key_blob.size(), 0U);
1945 ASSERT_EQ(cert_chain_.size(), 0);
1946 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001947 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001948
1949 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1950 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1951 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1952 << "Key size " << key_size << "missing";
1953
1954 CheckedDeleteKey(&key_blob);
1955 }
1956}
1957
1958/*
Qi Wud22ec842020-11-26 13:27:53 +08001959 * NewKeyGenerationTest.LimitedUsageHmac
1960 *
1961 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1962 * resulting keys have correct characteristics.
1963 */
1964TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1965 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1966 vector<uint8_t> key_blob;
1967 vector<KeyCharacteristics> key_characteristics;
1968 constexpr size_t key_size = 128;
1969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1970 .HmacKey(key_size)
1971 .Digest(digest)
1972 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1973 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1974 &key_blob, &key_characteristics));
1975
1976 ASSERT_GT(key_blob.size(), 0U);
1977 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001978 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001979
1980 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1981 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1982 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1983 << "Key size " << key_size << "missing";
1984
1985 // Check the usage count limit tag appears in the authorizations.
1986 AuthorizationSet auths;
1987 for (auto& entry : key_characteristics) {
1988 auths.push_back(AuthorizationSet(entry.authorizations));
1989 }
1990 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1991 << "key usage count limit " << 1U << " missing";
1992
1993 CheckedDeleteKey(&key_blob);
1994 }
1995}
1996
1997/*
Selene Huang31ab4042020-04-29 04:22:39 -07001998 * NewKeyGenerationTest.HmacCheckKeySizes
1999 *
2000 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2001 */
2002TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2003 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2004 if (key_size < 64 || key_size % 8 != 0) {
2005 // To keep this test from being very slow, we only test a random fraction of
2006 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2007 // them, we expect to run ~40 of them in each run.
2008 if (key_size % 8 == 0 || random() % 10 == 0) {
2009 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2010 GenerateKey(AuthorizationSetBuilder()
2011 .HmacKey(key_size)
2012 .Digest(Digest::SHA_2_256)
2013 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2014 << "HMAC key size " << key_size << " invalid";
2015 }
2016 } else {
2017 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2018 .HmacKey(key_size)
2019 .Digest(Digest::SHA_2_256)
2020 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2021 << "Failed to generate HMAC key of size " << key_size;
2022 CheckedDeleteKey();
2023 }
2024 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002025 if (SecLevel() == SecurityLevel::STRONGBOX) {
2026 // STRONGBOX devices must not support keys larger than 512 bits.
2027 size_t key_size = 520;
2028 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2029 GenerateKey(AuthorizationSetBuilder()
2030 .HmacKey(key_size)
2031 .Digest(Digest::SHA_2_256)
2032 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2033 << "HMAC key size " << key_size << " unexpectedly valid";
2034 }
Selene Huang31ab4042020-04-29 04:22:39 -07002035}
2036
2037/*
2038 * NewKeyGenerationTest.HmacCheckMinMacLengths
2039 *
2040 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2041 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2042 * specific MAC length that failed, so reproducing a failed run will be easy.
2043 */
2044TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2045 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2046 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2047 // To keep this test from being very long, we only test a random fraction of
2048 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2049 // we expect to run ~17 of them in each run.
2050 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2051 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2052 GenerateKey(AuthorizationSetBuilder()
2053 .HmacKey(128)
2054 .Digest(Digest::SHA_2_256)
2055 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2056 << "HMAC min mac length " << min_mac_length << " invalid.";
2057 }
2058 } else {
2059 EXPECT_EQ(ErrorCode::OK,
2060 GenerateKey(AuthorizationSetBuilder()
2061 .HmacKey(128)
2062 .Digest(Digest::SHA_2_256)
2063 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2064 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2065 CheckedDeleteKey();
2066 }
2067 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002068
2069 // Minimum MAC length must be no more than 512 bits.
2070 size_t min_mac_length = 520;
2071 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2072 GenerateKey(AuthorizationSetBuilder()
2073 .HmacKey(128)
2074 .Digest(Digest::SHA_2_256)
2075 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2076 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002077}
2078
2079/*
2080 * NewKeyGenerationTest.HmacMultipleDigests
2081 *
2082 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2083 */
2084TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2085 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2086
2087 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2088 GenerateKey(AuthorizationSetBuilder()
2089 .HmacKey(128)
2090 .Digest(Digest::SHA1)
2091 .Digest(Digest::SHA_2_256)
2092 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2093}
2094
2095/*
2096 * NewKeyGenerationTest.HmacDigestNone
2097 *
2098 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2099 */
2100TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2101 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2102 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2103 128)));
2104
2105 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2106 GenerateKey(AuthorizationSetBuilder()
2107 .HmacKey(128)
2108 .Digest(Digest::NONE)
2109 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2110}
2111
Selene Huang4f64c222021-04-13 19:54:36 -07002112/*
2113 * NewKeyGenerationTest.AesNoAttestation
2114 *
2115 * Verifies that attestation parameters to AES keys are ignored and generateKey
2116 * will succeed.
2117 */
2118TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2119 auto challenge = "hello";
2120 auto app_id = "foo";
2121
2122 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2123 .Authorization(TAG_NO_AUTH_REQUIRED)
2124 .AesEncryptionKey(128)
2125 .EcbMode()
2126 .Padding(PaddingMode::PKCS7)
2127 .AttestationChallenge(challenge)
2128 .AttestationApplicationId(app_id)));
2129
2130 ASSERT_EQ(cert_chain_.size(), 0);
2131}
2132
2133/*
2134 * NewKeyGenerationTest.TripleDesNoAttestation
2135 *
2136 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2137 * will be successful. No attestation should be generated.
2138 */
2139TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2140 auto challenge = "hello";
2141 auto app_id = "foo";
2142
2143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2144 .TripleDesEncryptionKey(168)
2145 .BlockMode(BlockMode::ECB)
2146 .Authorization(TAG_NO_AUTH_REQUIRED)
2147 .Padding(PaddingMode::NONE)
2148 .AttestationChallenge(challenge)
2149 .AttestationApplicationId(app_id)));
2150 ASSERT_EQ(cert_chain_.size(), 0);
2151}
2152
Selene Huang31ab4042020-04-29 04:22:39 -07002153INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2154
2155typedef KeyMintAidlTestBase SigningOperationsTest;
2156
2157/*
2158 * SigningOperationsTest.RsaSuccess
2159 *
2160 * Verifies that raw RSA signature operations succeed.
2161 */
2162TEST_P(SigningOperationsTest, RsaSuccess) {
2163 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2164 .RsaSigningKey(2048, 65537)
2165 .Digest(Digest::NONE)
2166 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002167 .Authorization(TAG_NO_AUTH_REQUIRED)
2168 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002169 string message = "12345678901234567890123456789012";
2170 string signature = SignMessage(
2171 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdalefe42aa32021-05-06 08:10:58 +01002172 LocalVerifyMessage(message, signature,
2173 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2174}
2175
2176/*
2177 * SigningOperationsTest.RsaAllPaddingsAndDigests
2178 *
2179 * Verifies RSA signature/verification for all padding modes and digests.
2180 */
2181TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2182 auto authorizations = AuthorizationSetBuilder()
2183 .Authorization(TAG_NO_AUTH_REQUIRED)
2184 .RsaSigningKey(2048, 65537)
2185 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2186 .Padding(PaddingMode::NONE)
2187 .Padding(PaddingMode::RSA_PSS)
2188 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2189 .SetDefaultValidity();
2190
2191 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2192
2193 string message(128, 'a');
2194 string corrupt_message(message);
2195 ++corrupt_message[corrupt_message.size() / 2];
2196
2197 for (auto padding :
2198 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2199 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2200 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2201 // Digesting only makes sense with padding.
2202 continue;
2203 }
2204
2205 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2206 // PSS requires digesting.
2207 continue;
2208 }
2209
2210 string signature =
2211 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2212 LocalVerifyMessage(message, signature,
2213 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2214 }
2215 }
Selene Huang31ab4042020-04-29 04:22:39 -07002216}
2217
2218/*
2219 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2220 *
Shawn Willden7f424372021-01-10 18:06:50 -07002221 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002222 */
2223TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2225 .Authorization(TAG_NO_AUTH_REQUIRED)
2226 .RsaSigningKey(2048, 65537)
2227 .Digest(Digest::NONE)
2228 .Padding(PaddingMode::NONE)
2229 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002230 .Authorization(TAG_APPLICATION_DATA, "appdata")
2231 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002232
2233 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2234
Selene Huang31ab4042020-04-29 04:22:39 -07002235 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2236 Begin(KeyPurpose::SIGN,
2237 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2238 AbortIfNeeded();
2239 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2240 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2241 .Digest(Digest::NONE)
2242 .Padding(PaddingMode::NONE)
2243 .Authorization(TAG_APPLICATION_ID, "clientid")));
2244 AbortIfNeeded();
2245 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2246 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2247 .Digest(Digest::NONE)
2248 .Padding(PaddingMode::NONE)
2249 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2250 AbortIfNeeded();
2251 EXPECT_EQ(ErrorCode::OK,
2252 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2253 .Digest(Digest::NONE)
2254 .Padding(PaddingMode::NONE)
2255 .Authorization(TAG_APPLICATION_DATA, "appdata")
2256 .Authorization(TAG_APPLICATION_ID, "clientid")));
2257 AbortIfNeeded();
2258}
2259
2260/*
2261 * SigningOperationsTest.RsaPssSha256Success
2262 *
2263 * Verifies that RSA-PSS signature operations succeed.
2264 */
2265TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2267 .RsaSigningKey(2048, 65537)
2268 .Digest(Digest::SHA_2_256)
2269 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002270 .Authorization(TAG_NO_AUTH_REQUIRED)
2271 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002272 // Use large message, which won't work without digesting.
2273 string message(1024, 'a');
2274 string signature = SignMessage(
2275 message,
2276 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2277}
2278
2279/*
2280 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2281 *
2282 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2283 * supports only unpadded operations.
2284 */
2285TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2287 .RsaSigningKey(2048, 65537)
2288 .Digest(Digest::NONE)
2289 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002290 .Padding(PaddingMode::NONE)
2291 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002292 string message = "12345678901234567890123456789012";
2293 string signature;
2294
2295 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2296 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2297 .Digest(Digest::NONE)
2298 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2299}
2300
2301/*
2302 * SigningOperationsTest.NoUserConfirmation
2303 *
2304 * Verifies that keymint rejects signing operations for keys with
2305 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2306 * presented.
2307 */
2308TEST_P(SigningOperationsTest, NoUserConfirmation) {
2309 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2311 .RsaSigningKey(1024, 65537)
2312 .Digest(Digest::NONE)
2313 .Padding(PaddingMode::NONE)
2314 .Authorization(TAG_NO_AUTH_REQUIRED)
2315 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2316 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002317
2318 const string message = "12345678901234567890123456789012";
2319 EXPECT_EQ(ErrorCode::OK,
2320 Begin(KeyPurpose::SIGN,
2321 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2322 string signature;
2323 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2324}
2325
2326/*
2327 * SigningOperationsTest.RsaPkcs1Sha256Success
2328 *
2329 * Verifies that digested RSA-PKCS1 signature operations succeed.
2330 */
2331TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2333 .RsaSigningKey(2048, 65537)
2334 .Digest(Digest::SHA_2_256)
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(1024, 'a');
2339 string signature = SignMessage(message, AuthorizationSetBuilder()
2340 .Digest(Digest::SHA_2_256)
2341 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2342}
2343
2344/*
2345 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2346 *
2347 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2348 */
2349TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2350 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2351 .RsaSigningKey(2048, 65537)
2352 .Digest(Digest::NONE)
2353 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002354 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2355 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002356 string message(53, 'a');
2357 string signature = SignMessage(message, AuthorizationSetBuilder()
2358 .Digest(Digest::NONE)
2359 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2360}
2361
2362/*
2363 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2364 *
2365 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2366 * given a too-long message.
2367 */
2368TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2369 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2370 .RsaSigningKey(2048, 65537)
2371 .Digest(Digest::NONE)
2372 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002373 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2374 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002375 string message(257, 'a');
2376
2377 EXPECT_EQ(ErrorCode::OK,
2378 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2379 .Digest(Digest::NONE)
2380 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2381 string signature;
2382 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2383}
2384
2385/*
2386 * SigningOperationsTest.RsaPssSha512TooSmallKey
2387 *
2388 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2389 * used with a key that is too small for the message.
2390 *
2391 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2392 * keymint specification requires that salt_size == digest_size, so the message will be
2393 * digest_size * 2 +
2394 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2395 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2396 * for a 1024-bit key.
2397 */
2398TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2399 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2401 .RsaSigningKey(1024, 65537)
2402 .Digest(Digest::SHA_2_512)
2403 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002404 .Padding(PaddingMode::RSA_PSS)
2405 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002406 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2407 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2408 .Digest(Digest::SHA_2_512)
2409 .Padding(PaddingMode::RSA_PSS)));
2410}
2411
2412/*
2413 * SigningOperationsTest.RsaNoPaddingTooLong
2414 *
2415 * Verifies that raw RSA signature operations fail with the correct error code when
2416 * given a too-long message.
2417 */
2418TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2420 .RsaSigningKey(2048, 65537)
2421 .Digest(Digest::NONE)
2422 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002423 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2424 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002425 // One byte too long
2426 string message(2048 / 8 + 1, 'a');
2427 ASSERT_EQ(ErrorCode::OK,
2428 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2429 .Digest(Digest::NONE)
2430 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2431 string result;
2432 ErrorCode finish_error_code = Finish(message, &result);
2433 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2434 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2435
2436 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2437 message = string(128 * 1024, 'a');
2438 ASSERT_EQ(ErrorCode::OK,
2439 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2440 .Digest(Digest::NONE)
2441 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2442 finish_error_code = Finish(message, &result);
2443 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2444 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2445}
2446
2447/*
2448 * SigningOperationsTest.RsaAbort
2449 *
2450 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2451 * test, but the behavior should be algorithm and purpose-independent.
2452 */
2453TEST_P(SigningOperationsTest, RsaAbort) {
2454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2455 .RsaSigningKey(2048, 65537)
2456 .Digest(Digest::NONE)
2457 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002458 .Padding(PaddingMode::NONE)
2459 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002460
2461 ASSERT_EQ(ErrorCode::OK,
2462 Begin(KeyPurpose::SIGN,
2463 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2464 EXPECT_EQ(ErrorCode::OK, Abort());
2465
2466 // Another abort should fail
2467 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2468
2469 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002470 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002471}
2472
2473/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002474 * SigningOperationsTest.RsaNonUniqueParams
2475 *
2476 * Verifies that an operation with multiple padding modes is rejected.
2477 */
2478TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2480 .RsaSigningKey(2048, 65537)
2481 .Digest(Digest::NONE)
2482 .Digest(Digest::SHA1)
2483 .Authorization(TAG_NO_AUTH_REQUIRED)
2484 .Padding(PaddingMode::NONE)
2485 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2486 .SetDefaultValidity()));
2487
2488 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2489 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2490 .Digest(Digest::NONE)
2491 .Padding(PaddingMode::NONE)
2492 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2493
Tommy Chiu3b56cbc2021-05-11 18:36:50 +08002494 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2495 .Digest(Digest::NONE)
2496 .Digest(Digest::SHA1)
2497 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2498 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002499
2500 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2501 Begin(KeyPurpose::SIGN,
2502 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2503}
2504
2505/*
Selene Huang31ab4042020-04-29 04:22:39 -07002506 * SigningOperationsTest.RsaUnsupportedPadding
2507 *
2508 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2509 * with a padding mode inappropriate for RSA.
2510 */
2511TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2512 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2513 .RsaSigningKey(2048, 65537)
2514 .Authorization(TAG_NO_AUTH_REQUIRED)
2515 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002516 .Padding(PaddingMode::PKCS7)
2517 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002518 ASSERT_EQ(
2519 ErrorCode::UNSUPPORTED_PADDING_MODE,
2520 Begin(KeyPurpose::SIGN,
2521 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002522 CheckedDeleteKey();
2523
2524 ASSERT_EQ(ErrorCode::OK,
2525 GenerateKey(
2526 AuthorizationSetBuilder()
2527 .RsaSigningKey(2048, 65537)
2528 .Authorization(TAG_NO_AUTH_REQUIRED)
2529 .Digest(Digest::SHA_2_256 /* supported digest */)
2530 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2531 .SetDefaultValidity()));
2532 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2533 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2534 .Digest(Digest::SHA_2_256)
2535 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002536}
2537
2538/*
2539 * SigningOperationsTest.RsaPssNoDigest
2540 *
2541 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2542 */
2543TEST_P(SigningOperationsTest, RsaNoDigest) {
2544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2545 .RsaSigningKey(2048, 65537)
2546 .Authorization(TAG_NO_AUTH_REQUIRED)
2547 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002548 .Padding(PaddingMode::RSA_PSS)
2549 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002550 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2551 Begin(KeyPurpose::SIGN,
2552 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2553
2554 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2555 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2556}
2557
2558/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002559 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002560 *
2561 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2562 * supported in some cases (as validated in other tests), but a mode must be specified.
2563 */
2564TEST_P(SigningOperationsTest, RsaNoPadding) {
2565 // Padding must be specified
2566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2567 .RsaKey(2048, 65537)
2568 .Authorization(TAG_NO_AUTH_REQUIRED)
2569 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002570 .Digest(Digest::NONE)
2571 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002572 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2573 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2574}
2575
2576/*
2577 * SigningOperationsTest.RsaShortMessage
2578 *
2579 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2580 */
2581TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2583 .Authorization(TAG_NO_AUTH_REQUIRED)
2584 .RsaSigningKey(2048, 65537)
2585 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002586 .Padding(PaddingMode::NONE)
2587 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002588
2589 // Barely shorter
2590 string message(2048 / 8 - 1, 'a');
2591 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2592
2593 // Much shorter
2594 message = "a";
2595 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2596}
2597
2598/*
2599 * SigningOperationsTest.RsaSignWithEncryptionKey
2600 *
2601 * Verifies that RSA encryption keys cannot be used to sign.
2602 */
2603TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2605 .Authorization(TAG_NO_AUTH_REQUIRED)
2606 .RsaEncryptionKey(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 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2611 Begin(KeyPurpose::SIGN,
2612 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2613}
2614
2615/*
2616 * SigningOperationsTest.RsaSignTooLargeMessage
2617 *
2618 * Verifies that attempting a raw signature of a message which is the same length as the key,
2619 * but numerically larger than the public modulus, fails with the correct error.
2620 */
2621TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2623 .Authorization(TAG_NO_AUTH_REQUIRED)
2624 .RsaSigningKey(2048, 65537)
2625 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002626 .Padding(PaddingMode::NONE)
2627 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002628
2629 // Largest possible message will always be larger than the public modulus.
2630 string message(2048 / 8, static_cast<char>(0xff));
2631 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2632 .Authorization(TAG_NO_AUTH_REQUIRED)
2633 .Digest(Digest::NONE)
2634 .Padding(PaddingMode::NONE)));
2635 string signature;
2636 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2637}
2638
2639/*
2640 * SigningOperationsTest.EcdsaAllSizesAndHashes
2641 *
2642 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2643 */
2644TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2645 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2646 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2647 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2648 .Authorization(TAG_NO_AUTH_REQUIRED)
2649 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002650 .Digest(digest)
2651 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002652 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2653 << " and digest " << digest;
2654 if (error != ErrorCode::OK) continue;
2655
2656 string message(1024, 'a');
2657 if (digest == Digest::NONE) message.resize(key_size / 8);
2658 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2659 CheckedDeleteKey();
2660 }
2661 }
2662}
2663
2664/*
David Drysdalefe42aa32021-05-06 08:10:58 +01002665 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2666 *
2667 * Verifies ECDSA signature/verification for all digests and curves.
2668 */
2669TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2670 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2671
2672 string message = "1234567890";
2673 string corrupt_message = "2234567890";
2674 for (auto curve : ValidCurves()) {
2675 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2676 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2677 .Authorization(TAG_NO_AUTH_REQUIRED)
2678 .EcdsaSigningKey(curve)
2679 .Digest(digests)
2680 .SetDefaultValidity());
2681 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2682 if (error != ErrorCode::OK) {
2683 continue;
2684 }
2685
2686 for (auto digest : digests) {
2687 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2688 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2689 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2690 }
2691
2692 auto rc = DeleteKey();
2693 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2694 }
2695}
2696
2697/*
Selene Huang31ab4042020-04-29 04:22:39 -07002698 * SigningOperationsTest.EcdsaAllCurves
2699 *
2700 * Verifies that ECDSA operations succeed with all possible curves.
2701 */
2702TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2703 for (auto curve : ValidCurves()) {
2704 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2705 .Authorization(TAG_NO_AUTH_REQUIRED)
2706 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002707 .Digest(Digest::SHA_2_256)
2708 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002709 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2710 if (error != ErrorCode::OK) continue;
2711
2712 string message(1024, 'a');
2713 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2714 CheckedDeleteKey();
2715 }
2716}
2717
2718/*
2719 * SigningOperationsTest.EcdsaNoDigestHugeData
2720 *
2721 * Verifies that ECDSA operations support very large messages, even without digesting. This
2722 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2723 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2724 * the framework.
2725 */
2726TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2728 .Authorization(TAG_NO_AUTH_REQUIRED)
2729 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002730 .Digest(Digest::NONE)
2731 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002732 string message(1 * 1024, 'a');
2733 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2734}
2735
2736/*
2737 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2738 *
2739 * Verifies that using an EC key requires the correct app ID/data.
2740 */
2741TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2743 .Authorization(TAG_NO_AUTH_REQUIRED)
2744 .EcdsaSigningKey(256)
2745 .Digest(Digest::NONE)
2746 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002747 .Authorization(TAG_APPLICATION_DATA, "appdata")
2748 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002749
2750 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2751
Selene Huang31ab4042020-04-29 04:22:39 -07002752 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2753 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2754 AbortIfNeeded();
2755 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2756 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2757 .Digest(Digest::NONE)
2758 .Authorization(TAG_APPLICATION_ID, "clientid")));
2759 AbortIfNeeded();
2760 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2761 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2762 .Digest(Digest::NONE)
2763 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2764 AbortIfNeeded();
2765 EXPECT_EQ(ErrorCode::OK,
2766 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2767 .Digest(Digest::NONE)
2768 .Authorization(TAG_APPLICATION_DATA, "appdata")
2769 .Authorization(TAG_APPLICATION_ID, "clientid")));
2770 AbortIfNeeded();
2771}
2772
2773/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002774 * SigningOperationsTest.EcdsaIncompatibleDigest
2775 *
2776 * Verifies that using an EC key requires compatible digest.
2777 */
2778TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2779 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2780 .Authorization(TAG_NO_AUTH_REQUIRED)
2781 .EcdsaSigningKey(256)
2782 .Digest(Digest::NONE)
2783 .Digest(Digest::SHA1)
2784 .SetDefaultValidity()));
2785 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2786 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2787 AbortIfNeeded();
2788}
2789
2790/*
Selene Huang31ab4042020-04-29 04:22:39 -07002791 * SigningOperationsTest.AesEcbSign
2792 *
2793 * Verifies that attempts to use AES keys to sign fail in the correct way.
2794 */
2795TEST_P(SigningOperationsTest, AesEcbSign) {
2796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2797 .Authorization(TAG_NO_AUTH_REQUIRED)
2798 .SigningKey()
2799 .AesEncryptionKey(128)
2800 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2801
2802 AuthorizationSet out_params;
2803 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2804 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2805 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2806 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2807}
2808
2809/*
2810 * SigningOperationsTest.HmacAllDigests
2811 *
2812 * Verifies that HMAC works with all digests.
2813 */
2814TEST_P(SigningOperationsTest, HmacAllDigests) {
2815 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2817 .Authorization(TAG_NO_AUTH_REQUIRED)
2818 .HmacKey(128)
2819 .Digest(digest)
2820 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2821 << "Failed to create HMAC key with digest " << digest;
2822 string message = "12345678901234567890123456789012";
2823 string signature = MacMessage(message, digest, 160);
2824 EXPECT_EQ(160U / 8U, signature.size())
2825 << "Failed to sign with HMAC key with digest " << digest;
2826 CheckedDeleteKey();
2827 }
2828}
2829
2830/*
2831 * SigningOperationsTest.HmacSha256TooLargeMacLength
2832 *
2833 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2834 * digest size.
2835 */
2836TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2838 .Authorization(TAG_NO_AUTH_REQUIRED)
2839 .HmacKey(128)
2840 .Digest(Digest::SHA_2_256)
2841 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2842 AuthorizationSet output_params;
2843 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2844 AuthorizationSetBuilder()
2845 .Digest(Digest::SHA_2_256)
2846 .Authorization(TAG_MAC_LENGTH, 264),
2847 &output_params));
2848}
2849
2850/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002851 * SigningOperationsTest.HmacSha256InvalidMacLength
2852 *
2853 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2854 * not a multiple of 8.
2855 */
2856TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2858 .Authorization(TAG_NO_AUTH_REQUIRED)
2859 .HmacKey(128)
2860 .Digest(Digest::SHA_2_256)
2861 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2862 AuthorizationSet output_params;
2863 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2864 AuthorizationSetBuilder()
2865 .Digest(Digest::SHA_2_256)
2866 .Authorization(TAG_MAC_LENGTH, 161),
2867 &output_params));
2868}
2869
2870/*
Selene Huang31ab4042020-04-29 04:22:39 -07002871 * SigningOperationsTest.HmacSha256TooSmallMacLength
2872 *
2873 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2874 * specified minimum MAC length.
2875 */
2876TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2878 .Authorization(TAG_NO_AUTH_REQUIRED)
2879 .HmacKey(128)
2880 .Digest(Digest::SHA_2_256)
2881 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2882 AuthorizationSet output_params;
2883 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2884 AuthorizationSetBuilder()
2885 .Digest(Digest::SHA_2_256)
2886 .Authorization(TAG_MAC_LENGTH, 120),
2887 &output_params));
2888}
2889
2890/*
2891 * SigningOperationsTest.HmacRfc4231TestCase3
2892 *
2893 * Validates against the test vectors from RFC 4231 test case 3.
2894 */
2895TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2896 string key(20, 0xaa);
2897 string message(50, 0xdd);
2898 uint8_t sha_224_expected[] = {
2899 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2900 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2901 };
2902 uint8_t sha_256_expected[] = {
2903 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2904 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2905 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2906 };
2907 uint8_t sha_384_expected[] = {
2908 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2909 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2910 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2911 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2912 };
2913 uint8_t sha_512_expected[] = {
2914 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2915 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2916 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2917 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2918 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2919 };
2920
2921 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2922 if (SecLevel() != SecurityLevel::STRONGBOX) {
2923 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2924 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2925 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2926 }
2927}
2928
2929/*
2930 * SigningOperationsTest.HmacRfc4231TestCase5
2931 *
2932 * Validates against the test vectors from RFC 4231 test case 5.
2933 */
2934TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2935 string key(20, 0x0c);
2936 string message = "Test With Truncation";
2937
2938 uint8_t sha_224_expected[] = {
2939 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2940 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2941 };
2942 uint8_t sha_256_expected[] = {
2943 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2944 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2945 };
2946 uint8_t sha_384_expected[] = {
2947 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2948 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2949 };
2950 uint8_t sha_512_expected[] = {
2951 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2952 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2953 };
2954
2955 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2956 if (SecLevel() != SecurityLevel::STRONGBOX) {
2957 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2958 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2959 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2960 }
2961}
2962
2963INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2964
2965typedef KeyMintAidlTestBase VerificationOperationsTest;
2966
2967/*
Selene Huang31ab4042020-04-29 04:22:39 -07002968 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2969 *
2970 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2971 */
2972TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2973 string key_material = "HelloThisIsAKey";
2974
2975 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002976 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002977 EXPECT_EQ(ErrorCode::OK,
2978 ImportKey(AuthorizationSetBuilder()
2979 .Authorization(TAG_NO_AUTH_REQUIRED)
2980 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2981 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2982 .Digest(Digest::SHA_2_256)
2983 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2984 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2985 EXPECT_EQ(ErrorCode::OK,
2986 ImportKey(AuthorizationSetBuilder()
2987 .Authorization(TAG_NO_AUTH_REQUIRED)
2988 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2989 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2990 .Digest(Digest::SHA_2_256)
2991 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2992 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2993
2994 string message = "This is a message.";
2995 string signature = SignMessage(
2996 signing_key, message,
2997 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2998
2999 // Signing key should not work.
3000 AuthorizationSet out_params;
3001 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3002 Begin(KeyPurpose::VERIFY, signing_key,
3003 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3004
3005 // Verification key should work.
3006 VerifyMessage(verification_key, message, signature,
3007 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3008
3009 CheckedDeleteKey(&signing_key);
3010 CheckedDeleteKey(&verification_key);
3011}
3012
3013INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3014
3015typedef KeyMintAidlTestBase ExportKeyTest;
3016
3017/*
3018 * ExportKeyTest.RsaUnsupportedKeyFormat
3019 *
3020 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3021 */
3022// TODO(seleneh) add ExportKey to GenerateKey
3023// check result
3024
3025class ImportKeyTest : public KeyMintAidlTestBase {
3026 public:
3027 template <TagType tag_type, Tag tag, typename ValueT>
3028 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3029 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003030 for (auto& entry : key_characteristics_) {
3031 if (entry.securityLevel == SecLevel()) {
3032 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3033 << "Tag " << tag << " with value " << expected
3034 << " not found at security level" << entry.securityLevel;
3035 } else {
3036 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3037 << "Tag " << tag << " found at security level " << entry.securityLevel;
3038 }
Selene Huang31ab4042020-04-29 04:22:39 -07003039 }
3040 }
3041
3042 void CheckOrigin() {
3043 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003044 // Origin isn't a crypto param, but it always lives with them.
3045 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003046 }
3047};
3048
3049/*
3050 * ImportKeyTest.RsaSuccess
3051 *
3052 * Verifies that importing and using an RSA key pair works correctly.
3053 */
3054TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003055 uint32_t key_size;
3056 string key;
3057
3058 if (SecLevel() == SecurityLevel::STRONGBOX) {
3059 key_size = 2048;
3060 key = rsa_2048_key;
3061 } else {
3062 key_size = 1024;
3063 key = rsa_key;
3064 }
3065
Selene Huang31ab4042020-04-29 04:22:39 -07003066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3067 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003068 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003069 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003070 .Padding(PaddingMode::RSA_PSS)
3071 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003072 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003073
3074 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003075 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003076 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3077 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3078 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3079 CheckOrigin();
3080
3081 string message(1024 / 8, 'a');
3082 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3083 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003084 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003085}
3086
3087/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003088 * ImportKeyTest.RsaSuccessWithoutParams
3089 *
3090 * Verifies that importing and using an RSA key pair without specifying parameters
3091 * works correctly.
3092 */
3093TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3094 uint32_t key_size;
3095 string key;
3096
3097 if (SecLevel() == SecurityLevel::STRONGBOX) {
3098 key_size = 2048;
3099 key = rsa_2048_key;
3100 } else {
3101 key_size = 1024;
3102 key = rsa_key;
3103 }
3104
3105 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3106 .Authorization(TAG_NO_AUTH_REQUIRED)
3107 .SigningKey()
3108 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3109 .Digest(Digest::SHA_2_256)
3110 .Padding(PaddingMode::RSA_PSS)
3111 .SetDefaultValidity(),
3112 KeyFormat::PKCS8, key));
3113
3114 // Key size and public exponent are determined from the imported key material.
3115 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3116 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3117
3118 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3119 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3120 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3121 CheckOrigin();
3122
3123 string message(1024 / 8, 'a');
3124 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3125 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003126 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003127}
3128
3129/*
Selene Huang31ab4042020-04-29 04:22:39 -07003130 * ImportKeyTest.RsaKeySizeMismatch
3131 *
3132 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3133 * correct way.
3134 */
3135TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3136 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3137 ImportKey(AuthorizationSetBuilder()
3138 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3139 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003140 .Padding(PaddingMode::NONE)
3141 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003142 KeyFormat::PKCS8, rsa_key));
3143}
3144
3145/*
3146 * ImportKeyTest.RsaPublicExponentMismatch
3147 *
3148 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3149 * fails in the correct way.
3150 */
3151TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3152 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3153 ImportKey(AuthorizationSetBuilder()
3154 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3155 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003156 .Padding(PaddingMode::NONE)
3157 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003158 KeyFormat::PKCS8, rsa_key));
3159}
3160
3161/*
3162 * ImportKeyTest.EcdsaSuccess
3163 *
3164 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3165 */
3166TEST_P(ImportKeyTest, EcdsaSuccess) {
3167 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3168 .Authorization(TAG_NO_AUTH_REQUIRED)
3169 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003170 .Digest(Digest::SHA_2_256)
3171 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003172 KeyFormat::PKCS8, ec_256_key));
3173
3174 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3175 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3176 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3177 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3178
3179 CheckOrigin();
3180
3181 string message(32, 'a');
3182 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3183 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003184 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003185}
3186
3187/*
3188 * ImportKeyTest.EcdsaP256RFC5915Success
3189 *
3190 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3191 * correctly.
3192 */
3193TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3194 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3195 .Authorization(TAG_NO_AUTH_REQUIRED)
3196 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003197 .Digest(Digest::SHA_2_256)
3198 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003199 KeyFormat::PKCS8, ec_256_key_rfc5915));
3200
3201 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3202 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3203 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3204 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3205
3206 CheckOrigin();
3207
3208 string message(32, 'a');
3209 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3210 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003211 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003212}
3213
3214/*
3215 * ImportKeyTest.EcdsaP256SEC1Success
3216 *
3217 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3218 */
3219TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3220 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3221 .Authorization(TAG_NO_AUTH_REQUIRED)
3222 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003223 .Digest(Digest::SHA_2_256)
3224 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003225 KeyFormat::PKCS8, ec_256_key_sec1));
3226
3227 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3228 CheckCryptoParam(TAG_KEY_SIZE, 256U);
3229 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3230 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3231
3232 CheckOrigin();
3233
3234 string message(32, 'a');
3235 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3236 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003237 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003238}
3239
3240/*
3241 * ImportKeyTest.Ecdsa521Success
3242 *
3243 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3244 */
3245TEST_P(ImportKeyTest, Ecdsa521Success) {
3246 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3247 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3248 .Authorization(TAG_NO_AUTH_REQUIRED)
3249 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003250 .Digest(Digest::SHA_2_256)
3251 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003252 KeyFormat::PKCS8, ec_521_key));
3253
3254 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
3255 CheckCryptoParam(TAG_KEY_SIZE, 521U);
3256 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3257 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3258 CheckOrigin();
3259
3260 string message(32, 'a');
3261 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3262 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003263 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003264}
3265
3266/*
3267 * ImportKeyTest.EcdsaSizeMismatch
3268 *
3269 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
3270 * correct way.
3271 */
3272TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
3273 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3274 ImportKey(AuthorizationSetBuilder()
3275 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003276 .Digest(Digest::NONE)
3277 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003278 KeyFormat::PKCS8, ec_256_key));
3279}
3280
3281/*
3282 * ImportKeyTest.EcdsaCurveMismatch
3283 *
3284 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3285 * the correct way.
3286 */
3287TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3288 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3289 ImportKey(AuthorizationSetBuilder()
3290 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003291 .Digest(Digest::NONE)
3292 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003293 KeyFormat::PKCS8, ec_256_key));
3294}
3295
3296/*
3297 * ImportKeyTest.AesSuccess
3298 *
3299 * Verifies that importing and using an AES key works.
3300 */
3301TEST_P(ImportKeyTest, AesSuccess) {
3302 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3303 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3304 .Authorization(TAG_NO_AUTH_REQUIRED)
3305 .AesEncryptionKey(key.size() * 8)
3306 .EcbMode()
3307 .Padding(PaddingMode::PKCS7),
3308 KeyFormat::RAW, key));
3309
3310 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3311 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3312 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3313 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3314 CheckOrigin();
3315
3316 string message = "Hello World!";
3317 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3318 string ciphertext = EncryptMessage(message, params);
3319 string plaintext = DecryptMessage(ciphertext, params);
3320 EXPECT_EQ(message, plaintext);
3321}
3322
3323/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003324 * ImportKeyTest.AesFailure
3325 *
3326 * Verifies that importing an invalid AES key fails.
3327 */
3328TEST_P(ImportKeyTest, AesFailure) {
3329 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3330 uint32_t bitlen = key.size() * 8;
3331 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003332 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003333 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003334 .Authorization(TAG_NO_AUTH_REQUIRED)
3335 .AesEncryptionKey(key_size)
3336 .EcbMode()
3337 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003338 KeyFormat::RAW, key);
3339 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003340 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3341 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003342 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003343
3344 // Explicit key size matches that of the provided key, but it's not a valid size.
3345 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3346 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3347 ImportKey(AuthorizationSetBuilder()
3348 .Authorization(TAG_NO_AUTH_REQUIRED)
3349 .AesEncryptionKey(long_key.size() * 8)
3350 .EcbMode()
3351 .Padding(PaddingMode::PKCS7),
3352 KeyFormat::RAW, long_key));
3353 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3354 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3355 ImportKey(AuthorizationSetBuilder()
3356 .Authorization(TAG_NO_AUTH_REQUIRED)
3357 .AesEncryptionKey(short_key.size() * 8)
3358 .EcbMode()
3359 .Padding(PaddingMode::PKCS7),
3360 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003361}
3362
3363/*
3364 * ImportKeyTest.TripleDesSuccess
3365 *
3366 * Verifies that importing and using a 3DES key works.
3367 */
3368TEST_P(ImportKeyTest, TripleDesSuccess) {
3369 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3370 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3371 .Authorization(TAG_NO_AUTH_REQUIRED)
3372 .TripleDesEncryptionKey(168)
3373 .EcbMode()
3374 .Padding(PaddingMode::PKCS7),
3375 KeyFormat::RAW, key));
3376
3377 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3378 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3379 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3380 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3381 CheckOrigin();
3382
3383 string message = "Hello World!";
3384 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3385 string ciphertext = EncryptMessage(message, params);
3386 string plaintext = DecryptMessage(ciphertext, params);
3387 EXPECT_EQ(message, plaintext);
3388}
3389
3390/*
3391 * ImportKeyTest.TripleDesFailure
3392 *
3393 * Verifies that importing an invalid 3DES key fails.
3394 */
3395TEST_P(ImportKeyTest, TripleDesFailure) {
3396 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003397 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003398 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003399 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003400 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003401 .Authorization(TAG_NO_AUTH_REQUIRED)
3402 .TripleDesEncryptionKey(key_size)
3403 .EcbMode()
3404 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003405 KeyFormat::RAW, key);
3406 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003407 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3408 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003409 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003410 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003411 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003412 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3413 ImportKey(AuthorizationSetBuilder()
3414 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003415 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003416 .EcbMode()
3417 .Padding(PaddingMode::PKCS7),
3418 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003419 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003420 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3421 ImportKey(AuthorizationSetBuilder()
3422 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003423 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003424 .EcbMode()
3425 .Padding(PaddingMode::PKCS7),
3426 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003427}
3428
3429/*
3430 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003431 *
3432 * Verifies that importing and using an HMAC key works.
3433 */
3434TEST_P(ImportKeyTest, HmacKeySuccess) {
3435 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3436 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3437 .Authorization(TAG_NO_AUTH_REQUIRED)
3438 .HmacKey(key.size() * 8)
3439 .Digest(Digest::SHA_2_256)
3440 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3441 KeyFormat::RAW, key));
3442
3443 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3444 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3445 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3446 CheckOrigin();
3447
3448 string message = "Hello World!";
3449 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3450 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3451}
3452
3453INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3454
3455auto wrapped_key = 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 "934bf94e2aa28a3f83c9f79297250262"
3461 "fbe3276b5a1c91159bbfa3ef8957aac8"
3462 "4b59b30b455a79c2973480823d8b3863"
3463 "c3deef4a8e243590268d80e18751a0e1"
3464 "30f67ce6a1ace9f79b95e097474febc9"
3465 "81195b1d13a69086c0863f66a7b7fdb4"
3466 "8792227b1ac5e2489febdf087ab54864"
3467 "83033a6f001ca5d1ec1e27f5c30f4cec"
3468 "2642074a39ae68aee552e196627a8e3d"
3469 "867e67a8c01b11e75f13cca0a97ab668"
3470 "b50cda07a8ecb7cd8e3dd7009c963653"
3471 "4f6f239cffe1fc8daa466f78b676c711"
3472 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3473 "99b801597d5220e307eaa5bee507fb94"
3474 "d1fa69f9e519b2de315bac92c36f2ea1"
3475 "fa1df4478c0ddedeae8c70e0233cd098"
3476 "040c" // OCTET STRING length 0x0c (initializationVector)
3477 "d796b02c370f1fa4cc0124f1"
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 "ccd540855f833a5e1480bfd2d36faf3a"
3511 "eee15df5beabe2691bc82dde2a7aa910"
3512 "0410" // OCTET STRING length 0x10 (tag)
3513 "64c9f689c60ff6223ab6e6999e0eb6e5"
3514 // } SEQUENCE (SecureKeyWrapper)
3515);
Selene Huang31ab4042020-04-29 04:22:39 -07003516
3517auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003518 // IKeyMintDevice.aidl
3519 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3520 "020100" // INTEGER length 1 value 0x00 (version)
3521 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3522 "aad93ed5924f283b4bb5526fbe7a1412"
3523 "f9d9749ec30db9062b29e574a8546f33"
3524 "c88732452f5b8e6a391ee76c39ed1712"
3525 "c61d8df6213dec1cffbc17a8c6d04c7b"
3526 "30893d8daa9b2015213e219468215532"
3527 "07f8f9931c4caba23ed3bee28b36947e"
3528 "47f10e0a5c3dc51c988a628daad3e5e1"
3529 "f4005e79c2d5a96c284b4b8d7e4948f3"
3530 "31e5b85dd5a236f85579f3ea1d1b8484"
3531 "87470bdb0ab4f81a12bee42c99fe0df4"
3532 "bee3759453e69ad1d68a809ce06b949f"
3533 "7694a990429b2fe81e066ff43e56a216"
3534 "02db70757922a4bcc23ab89f1e35da77"
3535 "586775f423e519c2ea394caf48a28d0c"
3536 "8020f1dcf6b3a68ec246f615ae96dae9"
3537 "a079b1f6eb959033c1af5c125fd94168"
3538 "040c" // OCTET STRING length 0x0c (initializationVector)
3539 "6d9721d08589581ab49204a3"
3540 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3541 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3542 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3543 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3544 "3106" // SET length 0x06
3545 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3546 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3547 // } end SET
3548 // } end [1]
3549 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3550 "020120" // INTEGER length 1 value 0x20 (AES)
3551 // } end [2]
3552 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3553 "02020100" // INTEGER length 2 value 0x100
3554 // } end [3]
3555 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3556 "3103" // SET length 0x03 {
3557 "020101" // INTEGER length 1 value 0x01 (ECB)
3558 // } end SET
3559 // } end [4]
3560 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3561 "3103" // SET length 0x03 {
3562 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3563 // } end SET
3564 // } end [5]
3565 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3566 // (noAuthRequired)
3567 "0500" // NULL
3568 // } end [503]
3569 // } end SEQUENCE (AuthorizationList)
3570 // } end SEQUENCE (KeyDescription)
3571 "0420" // OCTET STRING length 0x20 (encryptedKey)
3572 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3573 "c20d1f99a9a024a76f35c8e2cab9b68d"
3574 "0410" // OCTET STRING length 0x10 (tag)
3575 "2560c70109ae67c030f00b98b512a670"
3576 // } SEQUENCE (SecureKeyWrapper)
3577);
Selene Huang31ab4042020-04-29 04:22:39 -07003578
3579auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003580 // RFC 5208 s5
3581 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3582 "020100" // INTEGER length 1 value 0x00 (version)
3583 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3584 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3585 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3586 "0500" // NULL (parameters)
3587 // } SEQUENCE (AlgorithmIdentifier)
3588 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3589 // RFC 8017 A.1.2
3590 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3591 "020100" // INTEGER length 1 value 0x00 (version)
3592 "02820101" // INTEGER length 0x0101 (modulus) value...
3593 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3594 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3595 "7b06e673a837313d56b1c725150a3fef" // 0x30
3596 "86acbddc41bb759c2854eae32d35841e" // 0x40
3597 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3598 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3599 "312d7bd5921ffaea1347c157406fef71" // 0x70
3600 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3601 "f4645c11f5c1374c3886427411c44979" // 0x90
3602 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3603 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3604 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3605 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3606 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3607 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3608 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3609 "55" // 0x101
3610 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3611 "02820100" // INTEGER length 0x100 (privateExponent) value...
3612 "431447b6251908112b1ee76f99f3711a" // 0x10
3613 "52b6630960046c2de70de188d833f8b8" // 0x20
3614 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3615 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3616 "e710b630a03adc683b5d2c43080e52be" // 0x50
3617 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3618 "822bccff087d63c940ba8a45f670feb2" // 0x70
3619 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3620 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3621 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3622 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3623 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3624 "52659d5a5ba05b663737a8696281865b" // 0xd0
3625 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3626 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3627 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3628 "028181" // INTEGER length 0x81 (prime1) value...
3629 "00de392e18d682c829266cc3454e1d61" // 0x10
3630 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3631 "ff841be5bac82a164c5970007047b8c5" // 0x30
3632 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3633 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3634 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3635 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3636 "9e91346130748a6e3c124f9149d71c74" // 0x80
3637 "35"
3638 "028181" // INTEGER length 0x81 (prime2) value...
3639 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3640 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3641 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3642 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3643 "9ed39a2d934c880440aed8832f984316" // 0x50
3644 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3645 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3646 "b880677c068e1be936e81288815252a8" // 0x80
3647 "a1"
3648 "028180" // INTEGER length 0x80 (exponent1) value...
3649 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3650 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3651 "5a063212a4f105a3764743e53281988a" // 0x30
3652 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3653 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3654 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3655 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3656 "4719d6e2b9439823719cd08bcd031781" // 0x80
3657 "028181" // INTEGER length 0x81 (exponent2) value...
3658 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3659 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3660 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3661 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3662 "1254186af30b22c10582a8a43e34fe94" // 0x50
3663 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3664 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3665 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3666 "61"
3667 "028181" // INTEGER length 0x81 (coefficient) value...
3668 "00c931617c77829dfb1270502be9195c" // 0x10
3669 "8f2830885f57dba869536811e6864236" // 0x20
3670 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3671 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3672 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3673 "959356210723287b0affcc9f727044d4" // 0x60
3674 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3675 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3676 "22"
3677 // } SEQUENCE
3678 // } SEQUENCE ()
3679);
Selene Huang31ab4042020-04-29 04:22:39 -07003680
3681string zero_masking_key =
3682 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3683string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3684
3685class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3686
3687TEST_P(ImportWrappedKeyTest, Success) {
3688 auto wrapping_key_desc = AuthorizationSetBuilder()
3689 .RsaEncryptionKey(2048, 65537)
3690 .Digest(Digest::SHA_2_256)
3691 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003692 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3693 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003694
3695 ASSERT_EQ(ErrorCode::OK,
3696 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3697 AuthorizationSetBuilder()
3698 .Digest(Digest::SHA_2_256)
3699 .Padding(PaddingMode::RSA_OAEP)));
3700
3701 string message = "Hello World!";
3702 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3703 string ciphertext = EncryptMessage(message, params);
3704 string plaintext = DecryptMessage(ciphertext, params);
3705 EXPECT_EQ(message, plaintext);
3706}
3707
David Drysdaled2cc8c22021-04-15 13:29:45 +01003708/*
3709 * ImportWrappedKeyTest.SuccessSidsIgnored
3710 *
3711 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3712 * include Tag:USER_SECURE_ID.
3713 */
3714TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3715 auto wrapping_key_desc = AuthorizationSetBuilder()
3716 .RsaEncryptionKey(2048, 65537)
3717 .Digest(Digest::SHA_2_256)
3718 .Padding(PaddingMode::RSA_OAEP)
3719 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3720 .SetDefaultValidity();
3721
3722 int64_t password_sid = 42;
3723 int64_t biometric_sid = 24;
3724 ASSERT_EQ(ErrorCode::OK,
3725 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3726 AuthorizationSetBuilder()
3727 .Digest(Digest::SHA_2_256)
3728 .Padding(PaddingMode::RSA_OAEP),
3729 password_sid, biometric_sid));
3730
3731 string message = "Hello World!";
3732 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3733 string ciphertext = EncryptMessage(message, params);
3734 string plaintext = DecryptMessage(ciphertext, params);
3735 EXPECT_EQ(message, plaintext);
3736}
3737
Selene Huang31ab4042020-04-29 04:22:39 -07003738TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3739 auto wrapping_key_desc = AuthorizationSetBuilder()
3740 .RsaEncryptionKey(2048, 65537)
3741 .Digest(Digest::SHA_2_256)
3742 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003743 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3744 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003745
3746 ASSERT_EQ(ErrorCode::OK,
3747 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3748 AuthorizationSetBuilder()
3749 .Digest(Digest::SHA_2_256)
3750 .Padding(PaddingMode::RSA_OAEP)));
3751}
3752
3753TEST_P(ImportWrappedKeyTest, WrongMask) {
3754 auto wrapping_key_desc = AuthorizationSetBuilder()
3755 .RsaEncryptionKey(2048, 65537)
3756 .Digest(Digest::SHA_2_256)
3757 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003758 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3759 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003760
3761 ASSERT_EQ(
3762 ErrorCode::VERIFICATION_FAILED,
3763 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3764 AuthorizationSetBuilder()
3765 .Digest(Digest::SHA_2_256)
3766 .Padding(PaddingMode::RSA_OAEP)));
3767}
3768
3769TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3770 auto wrapping_key_desc = AuthorizationSetBuilder()
3771 .RsaEncryptionKey(2048, 65537)
3772 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003773 .Padding(PaddingMode::RSA_OAEP)
3774 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003775
3776 ASSERT_EQ(
3777 ErrorCode::INCOMPATIBLE_PURPOSE,
3778 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3779 AuthorizationSetBuilder()
3780 .Digest(Digest::SHA_2_256)
3781 .Padding(PaddingMode::RSA_OAEP)));
3782}
3783
David Drysdaled2cc8c22021-04-15 13:29:45 +01003784TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3785 auto wrapping_key_desc = AuthorizationSetBuilder()
3786 .RsaEncryptionKey(2048, 65537)
3787 .Digest(Digest::SHA_2_256)
3788 .Padding(PaddingMode::RSA_PSS)
3789 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3790 .SetDefaultValidity();
3791
3792 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3793 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3794 AuthorizationSetBuilder()
3795 .Digest(Digest::SHA_2_256)
3796 .Padding(PaddingMode::RSA_OAEP)));
3797}
3798
3799TEST_P(ImportWrappedKeyTest, WrongDigest) {
3800 auto wrapping_key_desc = AuthorizationSetBuilder()
3801 .RsaEncryptionKey(2048, 65537)
3802 .Digest(Digest::SHA_2_512)
3803 .Padding(PaddingMode::RSA_OAEP)
3804 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3805 .SetDefaultValidity();
3806
3807 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3808 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3809 AuthorizationSetBuilder()
3810 .Digest(Digest::SHA_2_256)
3811 .Padding(PaddingMode::RSA_OAEP)));
3812}
3813
Selene Huang31ab4042020-04-29 04:22:39 -07003814INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3815
3816typedef KeyMintAidlTestBase EncryptionOperationsTest;
3817
3818/*
3819 * EncryptionOperationsTest.RsaNoPaddingSuccess
3820 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003821 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003822 */
3823TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003824 for (uint64_t exponent : {3, 65537}) {
3825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3826 .Authorization(TAG_NO_AUTH_REQUIRED)
3827 .RsaEncryptionKey(2048, exponent)
3828 .Padding(PaddingMode::NONE)
3829 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003830
David Drysdaled2cc8c22021-04-15 13:29:45 +01003831 string message = string(2048 / 8, 'a');
3832 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003833 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003834 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003835
David Drysdale2b6c3512021-05-12 13:52:03 +01003836 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003837 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003838
David Drysdaled2cc8c22021-04-15 13:29:45 +01003839 // Unpadded RSA is deterministic
3840 EXPECT_EQ(ciphertext1, ciphertext2);
3841
3842 CheckedDeleteKey();
3843 }
Selene Huang31ab4042020-04-29 04:22:39 -07003844}
3845
3846/*
3847 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3848 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003849 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003850 */
3851TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3853 .Authorization(TAG_NO_AUTH_REQUIRED)
3854 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003855 .Padding(PaddingMode::NONE)
3856 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003857
3858 string message = "1";
3859 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3860
David Drysdale2b6c3512021-05-12 13:52:03 +01003861 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003862 EXPECT_EQ(2048U / 8, ciphertext.size());
3863
3864 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3865 string plaintext = DecryptMessage(ciphertext, params);
3866
3867 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003868}
3869
3870/*
Selene Huang31ab4042020-04-29 04:22:39 -07003871 * EncryptionOperationsTest.RsaOaepSuccess
3872 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003873 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003874 */
3875TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3876 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3877
3878 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale2b6c3512021-05-12 13:52:03 +01003879 ASSERT_EQ(ErrorCode::OK,
3880 GenerateKey(AuthorizationSetBuilder()
3881 .Authorization(TAG_NO_AUTH_REQUIRED)
3882 .RsaEncryptionKey(key_size, 65537)
3883 .Padding(PaddingMode::RSA_OAEP)
3884 .Digest(digests)
3885 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3886 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003887
3888 string message = "Hello";
3889
3890 for (auto digest : digests) {
David Drysdale2b6c3512021-05-12 13:52:03 +01003891 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3892
3893 auto params = AuthorizationSetBuilder()
3894 .Digest(digest)
3895 .Padding(PaddingMode::RSA_OAEP)
3896 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3897 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003898 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3899 EXPECT_EQ(key_size / 8, ciphertext1.size());
3900
David Drysdale2b6c3512021-05-12 13:52:03 +01003901 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003902 EXPECT_EQ(key_size / 8, ciphertext2.size());
3903
3904 // OAEP randomizes padding so every result should be different (with astronomically high
3905 // probability).
3906 EXPECT_NE(ciphertext1, ciphertext2);
3907
3908 string plaintext1 = DecryptMessage(ciphertext1, params);
3909 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3910 string plaintext2 = DecryptMessage(ciphertext2, params);
3911 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3912
3913 // Decrypting corrupted ciphertext should fail.
3914 size_t offset_to_corrupt = random() % ciphertext1.size();
3915 char corrupt_byte;
3916 do {
3917 corrupt_byte = static_cast<char>(random() % 256);
3918 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3919 ciphertext1[offset_to_corrupt] = corrupt_byte;
3920
3921 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3922 string result;
3923 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3924 EXPECT_EQ(0U, result.size());
3925 }
3926}
3927
3928/*
3929 * EncryptionOperationsTest.RsaOaepInvalidDigest
3930 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003931 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003932 * without a digest.
3933 */
3934TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3935 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3936 .Authorization(TAG_NO_AUTH_REQUIRED)
3937 .RsaEncryptionKey(2048, 65537)
3938 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003939 .Digest(Digest::NONE)
3940 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003941
3942 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003943 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003944}
3945
3946/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003947 * EncryptionOperationsTest.RsaOaepInvalidPadding
3948 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003949 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003950 * with a padding value that is only suitable for signing/verifying.
3951 */
3952TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3953 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3954 .Authorization(TAG_NO_AUTH_REQUIRED)
3955 .RsaEncryptionKey(2048, 65537)
3956 .Padding(PaddingMode::RSA_PSS)
3957 .Digest(Digest::NONE)
3958 .SetDefaultValidity()));
3959
3960 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003961 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003962}
3963
3964/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003965 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003966 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003967 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003968 * with a different digest than was used to encrypt.
3969 */
3970TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3971 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3972
3973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3974 .Authorization(TAG_NO_AUTH_REQUIRED)
3975 .RsaEncryptionKey(1024, 65537)
3976 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003977 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3978 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003979 string message = "Hello World!";
David Drysdale2b6c3512021-05-12 13:52:03 +01003980 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003981 message,
3982 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3983
3984 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3985 .Digest(Digest::SHA_2_256)
3986 .Padding(PaddingMode::RSA_OAEP)));
3987 string result;
3988 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3989 EXPECT_EQ(0U, result.size());
3990}
3991
3992/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003993 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3994 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003995 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003996 * digests.
3997 */
3998TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3999 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4000
4001 size_t key_size = 2048; // Need largish key for SHA-512 test.
4002 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4003 .OaepMGFDigest(digests)
4004 .Authorization(TAG_NO_AUTH_REQUIRED)
4005 .RsaEncryptionKey(key_size, 65537)
4006 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004007 .Digest(Digest::SHA_2_256)
4008 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004009
4010 string message = "Hello";
4011
4012 for (auto digest : digests) {
4013 auto params = AuthorizationSetBuilder()
4014 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4015 .Digest(Digest::SHA_2_256)
4016 .Padding(PaddingMode::RSA_OAEP);
David Drysdale2b6c3512021-05-12 13:52:03 +01004017 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004018 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4019 EXPECT_EQ(key_size / 8, ciphertext1.size());
4020
David Drysdale2b6c3512021-05-12 13:52:03 +01004021 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004022 EXPECT_EQ(key_size / 8, ciphertext2.size());
4023
4024 // OAEP randomizes padding so every result should be different (with astronomically high
4025 // probability).
4026 EXPECT_NE(ciphertext1, ciphertext2);
4027
4028 string plaintext1 = DecryptMessage(ciphertext1, params);
4029 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4030 string plaintext2 = DecryptMessage(ciphertext2, params);
4031 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4032
4033 // Decrypting corrupted ciphertext should fail.
4034 size_t offset_to_corrupt = random() % ciphertext1.size();
4035 char corrupt_byte;
4036 do {
4037 corrupt_byte = static_cast<char>(random() % 256);
4038 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4039 ciphertext1[offset_to_corrupt] = corrupt_byte;
4040
4041 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4042 string result;
4043 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4044 EXPECT_EQ(0U, result.size());
4045 }
4046}
4047
4048/*
4049 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4050 *
David Drysdale2b6c3512021-05-12 13:52:03 +01004051 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004052 * with incompatible MGF digest.
4053 */
4054TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4055 ASSERT_EQ(ErrorCode::OK,
4056 GenerateKey(AuthorizationSetBuilder()
4057 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4058 .Authorization(TAG_NO_AUTH_REQUIRED)
4059 .RsaEncryptionKey(2048, 65537)
4060 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004061 .Digest(Digest::SHA_2_256)
4062 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004063 string message = "Hello World!";
4064
4065 auto params = AuthorizationSetBuilder()
4066 .Padding(PaddingMode::RSA_OAEP)
4067 .Digest(Digest::SHA_2_256)
4068 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale2b6c3512021-05-12 13:52:03 +01004069 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004070}
4071
4072/*
4073 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4074 *
4075 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4076 * with unsupported MGF digest.
4077 */
4078TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4079 ASSERT_EQ(ErrorCode::OK,
4080 GenerateKey(AuthorizationSetBuilder()
4081 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4082 .Authorization(TAG_NO_AUTH_REQUIRED)
4083 .RsaEncryptionKey(2048, 65537)
4084 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004085 .Digest(Digest::SHA_2_256)
4086 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004087 string message = "Hello World!";
4088
4089 auto params = AuthorizationSetBuilder()
4090 .Padding(PaddingMode::RSA_OAEP)
4091 .Digest(Digest::SHA_2_256)
4092 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01004093 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004094}
4095
4096/*
Selene Huang31ab4042020-04-29 04:22:39 -07004097 * EncryptionOperationsTest.RsaPkcs1Success
4098 *
4099 * Verifies that RSA PKCS encryption/decrypts works.
4100 */
4101TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4103 .Authorization(TAG_NO_AUTH_REQUIRED)
4104 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004105 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4106 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004107
4108 string message = "Hello World!";
4109 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale2b6c3512021-05-12 13:52:03 +01004110 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004111 EXPECT_EQ(2048U / 8, ciphertext1.size());
4112
David Drysdale2b6c3512021-05-12 13:52:03 +01004113 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004114 EXPECT_EQ(2048U / 8, ciphertext2.size());
4115
4116 // PKCS1 v1.5 randomizes padding so every result should be different.
4117 EXPECT_NE(ciphertext1, ciphertext2);
4118
4119 string plaintext = DecryptMessage(ciphertext1, params);
4120 EXPECT_EQ(message, plaintext);
4121
4122 // Decrypting corrupted ciphertext should fail.
4123 size_t offset_to_corrupt = random() % ciphertext1.size();
4124 char corrupt_byte;
4125 do {
4126 corrupt_byte = static_cast<char>(random() % 256);
4127 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4128 ciphertext1[offset_to_corrupt] = corrupt_byte;
4129
4130 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4131 string result;
4132 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4133 EXPECT_EQ(0U, result.size());
4134}
4135
4136/*
Selene Huang31ab4042020-04-29 04:22:39 -07004137 * EncryptionOperationsTest.EcdsaEncrypt
4138 *
4139 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4140 */
4141TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4143 .Authorization(TAG_NO_AUTH_REQUIRED)
4144 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004145 .Digest(Digest::NONE)
4146 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004147 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4148 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4149 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4150}
4151
4152/*
4153 * EncryptionOperationsTest.HmacEncrypt
4154 *
4155 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4156 */
4157TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4158 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4159 .Authorization(TAG_NO_AUTH_REQUIRED)
4160 .HmacKey(128)
4161 .Digest(Digest::SHA_2_256)
4162 .Padding(PaddingMode::NONE)
4163 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4164 auto params = AuthorizationSetBuilder()
4165 .Digest(Digest::SHA_2_256)
4166 .Padding(PaddingMode::NONE)
4167 .Authorization(TAG_MAC_LENGTH, 128);
4168 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4169 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4170}
4171
4172/*
4173 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4174 *
4175 * Verifies that AES ECB mode works.
4176 */
4177TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4178 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4179 .Authorization(TAG_NO_AUTH_REQUIRED)
4180 .AesEncryptionKey(128)
4181 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4182 .Padding(PaddingMode::NONE)));
4183
4184 ASSERT_GT(key_blob_.size(), 0U);
4185 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4186
4187 // Two-block message.
4188 string message = "12345678901234567890123456789012";
4189 string ciphertext1 = EncryptMessage(message, params);
4190 EXPECT_EQ(message.size(), ciphertext1.size());
4191
4192 string ciphertext2 = EncryptMessage(string(message), params);
4193 EXPECT_EQ(message.size(), ciphertext2.size());
4194
4195 // ECB is deterministic.
4196 EXPECT_EQ(ciphertext1, ciphertext2);
4197
4198 string plaintext = DecryptMessage(ciphertext1, params);
4199 EXPECT_EQ(message, plaintext);
4200}
4201
4202/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004203 * EncryptionOperationsTest.AesEcbUnknownTag
4204 *
4205 * Verifies that AES ECB operations ignore unknown tags.
4206 */
4207TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4208 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4209 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4210 KeyParameter unknown_param;
4211 unknown_param.tag = unknown_tag;
4212
4213 vector<KeyCharacteristics> key_characteristics;
4214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4215 .Authorization(TAG_NO_AUTH_REQUIRED)
4216 .AesEncryptionKey(128)
4217 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4218 .Padding(PaddingMode::NONE)
4219 .Authorization(unknown_param),
4220 &key_blob_, &key_characteristics));
4221 ASSERT_GT(key_blob_.size(), 0U);
4222
4223 // Unknown tags should not be returned in key characteristics.
4224 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4225 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4226 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4227 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4228
4229 // Encrypt without mentioning the unknown parameter.
4230 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4231 string message = "12345678901234567890123456789012";
4232 string ciphertext = EncryptMessage(message, params);
4233 EXPECT_EQ(message.size(), ciphertext.size());
4234
4235 // Decrypt including the unknown parameter.
4236 auto decrypt_params = AuthorizationSetBuilder()
4237 .BlockMode(BlockMode::ECB)
4238 .Padding(PaddingMode::NONE)
4239 .Authorization(unknown_param);
4240 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4241 EXPECT_EQ(message, plaintext);
4242}
4243
4244/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004245 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004246 *
4247 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4248 */
4249TEST_P(EncryptionOperationsTest, AesWrongMode) {
4250 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4251 .Authorization(TAG_NO_AUTH_REQUIRED)
4252 .AesEncryptionKey(128)
4253 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4254 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004255 ASSERT_GT(key_blob_.size(), 0U);
4256
Selene Huang31ab4042020-04-29 04:22:39 -07004257 EXPECT_EQ(
4258 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4259 Begin(KeyPurpose::ENCRYPT,
4260 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4261}
4262
4263/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004264 * EncryptionOperationsTest.AesWrongPadding
4265 *
4266 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4267 */
4268TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4270 .Authorization(TAG_NO_AUTH_REQUIRED)
4271 .AesEncryptionKey(128)
4272 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4273 .Padding(PaddingMode::NONE)));
4274 ASSERT_GT(key_blob_.size(), 0U);
4275
4276 EXPECT_EQ(
4277 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4278 Begin(KeyPurpose::ENCRYPT,
4279 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4280}
4281
4282/*
4283 * EncryptionOperationsTest.AesInvalidParams
4284 *
4285 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4286 */
4287TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4289 .Authorization(TAG_NO_AUTH_REQUIRED)
4290 .AesEncryptionKey(128)
4291 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4292 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4293 .Padding(PaddingMode::NONE)
4294 .Padding(PaddingMode::PKCS7)));
4295 ASSERT_GT(key_blob_.size(), 0U);
4296
4297 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4298 .BlockMode(BlockMode::CBC)
4299 .BlockMode(BlockMode::ECB)
4300 .Padding(PaddingMode::NONE));
4301 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4302 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4303
4304 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4305 .BlockMode(BlockMode::ECB)
4306 .Padding(PaddingMode::NONE)
4307 .Padding(PaddingMode::PKCS7));
4308 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4309 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4310}
4311
4312/*
Selene Huang31ab4042020-04-29 04:22:39 -07004313 * EncryptionOperationsTest.AesWrongPurpose
4314 *
4315 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4316 * specified.
4317 */
4318TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4319 auto err = GenerateKey(AuthorizationSetBuilder()
4320 .Authorization(TAG_NO_AUTH_REQUIRED)
4321 .AesKey(128)
4322 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4323 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4324 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4325 .Padding(PaddingMode::NONE));
4326 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4327 ASSERT_GT(key_blob_.size(), 0U);
4328
4329 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4330 .BlockMode(BlockMode::GCM)
4331 .Padding(PaddingMode::NONE)
4332 .Authorization(TAG_MAC_LENGTH, 128));
4333 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4334
4335 CheckedDeleteKey();
4336
4337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4338 .Authorization(TAG_NO_AUTH_REQUIRED)
4339 .AesKey(128)
4340 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4341 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4342 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4343 .Padding(PaddingMode::NONE)));
4344
4345 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4346 .BlockMode(BlockMode::GCM)
4347 .Padding(PaddingMode::NONE)
4348 .Authorization(TAG_MAC_LENGTH, 128));
4349 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4350}
4351
4352/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004353 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004354 *
4355 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4356 * multiple of the block size and no padding is specified.
4357 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004358TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4359 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4361 .Authorization(TAG_NO_AUTH_REQUIRED)
4362 .AesEncryptionKey(128)
4363 .Authorization(TAG_BLOCK_MODE, blockMode)
4364 .Padding(PaddingMode::NONE)));
4365 // Message is slightly shorter than two blocks.
4366 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004367
David Drysdaled2cc8c22021-04-15 13:29:45 +01004368 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4369 AuthorizationSet out_params;
4370 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4371 string ciphertext;
4372 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4373 EXPECT_EQ(0U, ciphertext.size());
4374
4375 CheckedDeleteKey();
4376 }
Selene Huang31ab4042020-04-29 04:22:39 -07004377}
4378
4379/*
4380 * EncryptionOperationsTest.AesEcbPkcs7Padding
4381 *
4382 * Verifies that AES PKCS7 padding works for any message length.
4383 */
4384TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4385 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4386 .Authorization(TAG_NO_AUTH_REQUIRED)
4387 .AesEncryptionKey(128)
4388 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4389 .Padding(PaddingMode::PKCS7)));
4390
4391 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4392
4393 // Try various message lengths; all should work.
4394 for (size_t i = 0; i < 32; ++i) {
4395 string message(i, 'a');
4396 string ciphertext = EncryptMessage(message, params);
4397 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4398 string plaintext = DecryptMessage(ciphertext, params);
4399 EXPECT_EQ(message, plaintext);
4400 }
4401}
4402
4403/*
4404 * EncryptionOperationsTest.AesEcbWrongPadding
4405 *
4406 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4407 * specified.
4408 */
4409TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4411 .Authorization(TAG_NO_AUTH_REQUIRED)
4412 .AesEncryptionKey(128)
4413 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4414 .Padding(PaddingMode::NONE)));
4415
4416 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4417
4418 // Try various message lengths; all should fail
4419 for (size_t i = 0; i < 32; ++i) {
4420 string message(i, 'a');
4421 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4422 }
4423}
4424
4425/*
4426 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4427 *
4428 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4429 */
4430TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4432 .Authorization(TAG_NO_AUTH_REQUIRED)
4433 .AesEncryptionKey(128)
4434 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4435 .Padding(PaddingMode::PKCS7)));
4436
4437 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4438
4439 string message = "a";
4440 string ciphertext = EncryptMessage(message, params);
4441 EXPECT_EQ(16U, ciphertext.size());
4442 EXPECT_NE(ciphertext, message);
4443 ++ciphertext[ciphertext.size() / 2];
4444
4445 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4446 string plaintext;
4447 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4448}
4449
4450vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4451 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004452 EXPECT_TRUE(iv);
4453 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004454}
4455
4456/*
4457 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4458 *
4459 * Verifies that AES CTR mode works.
4460 */
4461TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4462 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4463 .Authorization(TAG_NO_AUTH_REQUIRED)
4464 .AesEncryptionKey(128)
4465 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4466 .Padding(PaddingMode::NONE)));
4467
4468 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4469
4470 string message = "123";
4471 AuthorizationSet out_params;
4472 string ciphertext1 = EncryptMessage(message, params, &out_params);
4473 vector<uint8_t> iv1 = CopyIv(out_params);
4474 EXPECT_EQ(16U, iv1.size());
4475
4476 EXPECT_EQ(message.size(), ciphertext1.size());
4477
4478 out_params.Clear();
4479 string ciphertext2 = EncryptMessage(message, params, &out_params);
4480 vector<uint8_t> iv2 = CopyIv(out_params);
4481 EXPECT_EQ(16U, iv2.size());
4482
4483 // IVs should be random, so ciphertexts should differ.
4484 EXPECT_NE(ciphertext1, ciphertext2);
4485
4486 auto params_iv1 =
4487 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4488 auto params_iv2 =
4489 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4490
4491 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4492 EXPECT_EQ(message, plaintext);
4493 plaintext = DecryptMessage(ciphertext2, params_iv2);
4494 EXPECT_EQ(message, plaintext);
4495
4496 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4497 plaintext = DecryptMessage(ciphertext1, params_iv2);
4498 EXPECT_NE(message, plaintext);
4499 plaintext = DecryptMessage(ciphertext2, params_iv1);
4500 EXPECT_NE(message, plaintext);
4501}
4502
4503/*
4504 * EncryptionOperationsTest.AesIncremental
4505 *
4506 * Verifies that AES works, all modes, when provided data in various size increments.
4507 */
4508TEST_P(EncryptionOperationsTest, AesIncremental) {
4509 auto block_modes = {
4510 BlockMode::ECB,
4511 BlockMode::CBC,
4512 BlockMode::CTR,
4513 BlockMode::GCM,
4514 };
4515
4516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4517 .Authorization(TAG_NO_AUTH_REQUIRED)
4518 .AesEncryptionKey(128)
4519 .BlockMode(block_modes)
4520 .Padding(PaddingMode::NONE)
4521 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4522
4523 for (int increment = 1; increment <= 240; ++increment) {
4524 for (auto block_mode : block_modes) {
4525 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004526 auto params =
4527 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4528 if (block_mode == BlockMode::GCM) {
4529 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4530 }
Selene Huang31ab4042020-04-29 04:22:39 -07004531
4532 AuthorizationSet output_params;
4533 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4534
4535 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004536 string to_send;
4537 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004538 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004539 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004540 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4541 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004542
4543 switch (block_mode) {
4544 case BlockMode::GCM:
4545 EXPECT_EQ(message.size() + 16, ciphertext.size());
4546 break;
4547 case BlockMode::CTR:
4548 EXPECT_EQ(message.size(), ciphertext.size());
4549 break;
4550 case BlockMode::CBC:
4551 case BlockMode::ECB:
4552 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4553 break;
4554 }
4555
4556 auto iv = output_params.GetTagValue(TAG_NONCE);
4557 switch (block_mode) {
4558 case BlockMode::CBC:
4559 case BlockMode::GCM:
4560 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004561 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4562 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4563 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004564 break;
4565
4566 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004567 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004568 break;
4569 }
4570
4571 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4572 << "Decrypt begin() failed for block mode " << block_mode;
4573
4574 string plaintext;
4575 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004576 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004577 }
4578 ErrorCode error = Finish(to_send, &plaintext);
4579 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4580 << " and increment " << increment;
4581 if (error == ErrorCode::OK) {
4582 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4583 << block_mode << " and increment " << increment;
4584 }
4585 }
4586 }
4587}
4588
4589struct AesCtrSp80038aTestVector {
4590 const char* key;
4591 const char* nonce;
4592 const char* plaintext;
4593 const char* ciphertext;
4594};
4595
4596// These test vectors are taken from
4597// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4598static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4599 // AES-128
4600 {
4601 "2b7e151628aed2a6abf7158809cf4f3c",
4602 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4603 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4604 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4605 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4606 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4607 },
4608 // AES-192
4609 {
4610 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4611 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4612 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4613 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4614 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4615 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4616 },
4617 // AES-256
4618 {
4619 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4620 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4621 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4622 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4623 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4624 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4625 },
4626};
4627
4628/*
4629 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4630 *
4631 * Verifies AES CTR implementation against SP800-38A test vectors.
4632 */
4633TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4634 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4635 for (size_t i = 0; i < 3; i++) {
4636 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4637 const string key = hex2str(test.key);
4638 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4639 InvalidSizes.end())
4640 continue;
4641 const string nonce = hex2str(test.nonce);
4642 const string plaintext = hex2str(test.plaintext);
4643 const string ciphertext = hex2str(test.ciphertext);
4644 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4645 }
4646}
4647
4648/*
4649 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4650 *
4651 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4652 */
4653TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4655 .Authorization(TAG_NO_AUTH_REQUIRED)
4656 .AesEncryptionKey(128)
4657 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4658 .Padding(PaddingMode::PKCS7)));
4659 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4660 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4661}
4662
4663/*
4664 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4665 *
4666 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4667 */
4668TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4670 .Authorization(TAG_NO_AUTH_REQUIRED)
4671 .AesEncryptionKey(128)
4672 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4673 .Authorization(TAG_CALLER_NONCE)
4674 .Padding(PaddingMode::NONE)));
4675
4676 auto params = AuthorizationSetBuilder()
4677 .BlockMode(BlockMode::CTR)
4678 .Padding(PaddingMode::NONE)
4679 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4680 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4681
4682 params = AuthorizationSetBuilder()
4683 .BlockMode(BlockMode::CTR)
4684 .Padding(PaddingMode::NONE)
4685 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4686 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4687
4688 params = AuthorizationSetBuilder()
4689 .BlockMode(BlockMode::CTR)
4690 .Padding(PaddingMode::NONE)
4691 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4692 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4693}
4694
4695/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004696 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004697 *
4698 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4699 */
4700TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4701 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4702 .Authorization(TAG_NO_AUTH_REQUIRED)
4703 .AesEncryptionKey(128)
4704 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4705 .Padding(PaddingMode::NONE)));
4706 // Two-block message.
4707 string message = "12345678901234567890123456789012";
4708 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4709 AuthorizationSet out_params;
4710 string ciphertext1 = EncryptMessage(message, params, &out_params);
4711 vector<uint8_t> iv1 = CopyIv(out_params);
4712 EXPECT_EQ(message.size(), ciphertext1.size());
4713
4714 out_params.Clear();
4715
4716 string ciphertext2 = EncryptMessage(message, params, &out_params);
4717 vector<uint8_t> iv2 = CopyIv(out_params);
4718 EXPECT_EQ(message.size(), ciphertext2.size());
4719
4720 // IVs should be random, so ciphertexts should differ.
4721 EXPECT_NE(ciphertext1, ciphertext2);
4722
4723 params.push_back(TAG_NONCE, iv1);
4724 string plaintext = DecryptMessage(ciphertext1, params);
4725 EXPECT_EQ(message, plaintext);
4726}
4727
4728/*
4729 * EncryptionOperationsTest.AesCallerNonce
4730 *
4731 * Verifies that AES caller-provided nonces work correctly.
4732 */
4733TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4735 .Authorization(TAG_NO_AUTH_REQUIRED)
4736 .AesEncryptionKey(128)
4737 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4738 .Authorization(TAG_CALLER_NONCE)
4739 .Padding(PaddingMode::NONE)));
4740
4741 string message = "12345678901234567890123456789012";
4742
4743 // Don't specify nonce, should get a random one.
4744 AuthorizationSetBuilder params =
4745 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4746 AuthorizationSet out_params;
4747 string ciphertext = EncryptMessage(message, params, &out_params);
4748 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004749 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004750
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004751 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004752 string plaintext = DecryptMessage(ciphertext, params);
4753 EXPECT_EQ(message, plaintext);
4754
4755 // Now specify a nonce, should also work.
4756 params = AuthorizationSetBuilder()
4757 .BlockMode(BlockMode::CBC)
4758 .Padding(PaddingMode::NONE)
4759 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4760 out_params.Clear();
4761 ciphertext = EncryptMessage(message, params, &out_params);
4762
4763 // Decrypt with correct nonce.
4764 plaintext = DecryptMessage(ciphertext, params);
4765 EXPECT_EQ(message, plaintext);
4766
4767 // Try with wrong nonce.
4768 params = AuthorizationSetBuilder()
4769 .BlockMode(BlockMode::CBC)
4770 .Padding(PaddingMode::NONE)
4771 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4772 plaintext = DecryptMessage(ciphertext, params);
4773 EXPECT_NE(message, plaintext);
4774}
4775
4776/*
4777 * EncryptionOperationsTest.AesCallerNonceProhibited
4778 *
4779 * Verifies that caller-provided nonces are not permitted when not specified in the key
4780 * authorizations.
4781 */
4782TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4784 .Authorization(TAG_NO_AUTH_REQUIRED)
4785 .AesEncryptionKey(128)
4786 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4787 .Padding(PaddingMode::NONE)));
4788
4789 string message = "12345678901234567890123456789012";
4790
4791 // Don't specify nonce, should get a random one.
4792 AuthorizationSetBuilder params =
4793 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4794 AuthorizationSet out_params;
4795 string ciphertext = EncryptMessage(message, params, &out_params);
4796 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004797 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004798
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004799 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004800 string plaintext = DecryptMessage(ciphertext, params);
4801 EXPECT_EQ(message, plaintext);
4802
4803 // Now specify a nonce, should fail
4804 params = AuthorizationSetBuilder()
4805 .BlockMode(BlockMode::CBC)
4806 .Padding(PaddingMode::NONE)
4807 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4808 out_params.Clear();
4809 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4810}
4811
4812/*
4813 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4814 *
4815 * Verifies that AES GCM mode works.
4816 */
4817TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4819 .Authorization(TAG_NO_AUTH_REQUIRED)
4820 .AesEncryptionKey(128)
4821 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4822 .Padding(PaddingMode::NONE)
4823 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4824
4825 string aad = "foobar";
4826 string message = "123456789012345678901234567890123456";
4827
4828 auto begin_params = AuthorizationSetBuilder()
4829 .BlockMode(BlockMode::GCM)
4830 .Padding(PaddingMode::NONE)
4831 .Authorization(TAG_MAC_LENGTH, 128);
4832
Selene Huang31ab4042020-04-29 04:22:39 -07004833 // Encrypt
4834 AuthorizationSet begin_out_params;
4835 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4836 << "Begin encrypt";
4837 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004838 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4839 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004840 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4841
4842 // Grab nonce
4843 begin_params.push_back(begin_out_params);
4844
4845 // Decrypt.
4846 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004847 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004848 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004849 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004850 EXPECT_EQ(message.length(), plaintext.length());
4851 EXPECT_EQ(message, plaintext);
4852}
4853
4854/*
4855 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4856 *
4857 * Verifies that AES GCM mode works, even when there's a long delay
4858 * between operations.
4859 */
4860TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4862 .Authorization(TAG_NO_AUTH_REQUIRED)
4863 .AesEncryptionKey(128)
4864 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4865 .Padding(PaddingMode::NONE)
4866 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4867
4868 string aad = "foobar";
4869 string message = "123456789012345678901234567890123456";
4870
4871 auto begin_params = AuthorizationSetBuilder()
4872 .BlockMode(BlockMode::GCM)
4873 .Padding(PaddingMode::NONE)
4874 .Authorization(TAG_MAC_LENGTH, 128);
4875
Selene Huang31ab4042020-04-29 04:22:39 -07004876 // Encrypt
4877 AuthorizationSet begin_out_params;
4878 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4879 << "Begin encrypt";
4880 string ciphertext;
4881 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004882 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004883 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004884 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004885
4886 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4887
4888 // Grab nonce
4889 begin_params.push_back(begin_out_params);
4890
4891 // Decrypt.
4892 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4893 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004894 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004895 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004896 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004897 sleep(5);
4898 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4899 EXPECT_EQ(message.length(), plaintext.length());
4900 EXPECT_EQ(message, plaintext);
4901}
4902
4903/*
4904 * EncryptionOperationsTest.AesGcmDifferentNonces
4905 *
4906 * Verifies that encrypting the same data with different nonces produces different outputs.
4907 */
4908TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4910 .Authorization(TAG_NO_AUTH_REQUIRED)
4911 .AesEncryptionKey(128)
4912 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4913 .Padding(PaddingMode::NONE)
4914 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4915 .Authorization(TAG_CALLER_NONCE)));
4916
4917 string aad = "foobar";
4918 string message = "123456789012345678901234567890123456";
4919 string nonce1 = "000000000000";
4920 string nonce2 = "111111111111";
4921 string nonce3 = "222222222222";
4922
4923 string ciphertext1 =
4924 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4925 string ciphertext2 =
4926 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4927 string ciphertext3 =
4928 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4929
4930 ASSERT_NE(ciphertext1, ciphertext2);
4931 ASSERT_NE(ciphertext1, ciphertext3);
4932 ASSERT_NE(ciphertext2, ciphertext3);
4933}
4934
4935/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004936 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4937 *
4938 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4939 */
4940TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4942 .Authorization(TAG_NO_AUTH_REQUIRED)
4943 .AesEncryptionKey(128)
4944 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4945 .Padding(PaddingMode::NONE)
4946 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4947
4948 string aad = "foobar";
4949 string message = "123456789012345678901234567890123456";
4950
4951 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4952 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4953 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4954
4955 ASSERT_NE(ciphertext1, ciphertext2);
4956 ASSERT_NE(ciphertext1, ciphertext3);
4957 ASSERT_NE(ciphertext2, ciphertext3);
4958}
4959
4960/*
Selene Huang31ab4042020-04-29 04:22:39 -07004961 * EncryptionOperationsTest.AesGcmTooShortTag
4962 *
4963 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4964 */
4965TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4966 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4967 .Authorization(TAG_NO_AUTH_REQUIRED)
4968 .AesEncryptionKey(128)
4969 .BlockMode(BlockMode::GCM)
4970 .Padding(PaddingMode::NONE)
4971 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4972 string message = "123456789012345678901234567890123456";
4973 auto params = AuthorizationSetBuilder()
4974 .BlockMode(BlockMode::GCM)
4975 .Padding(PaddingMode::NONE)
4976 .Authorization(TAG_MAC_LENGTH, 96);
4977
4978 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4979}
4980
4981/*
4982 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4983 *
4984 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4985 */
4986TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4987 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4988 .Authorization(TAG_NO_AUTH_REQUIRED)
4989 .AesEncryptionKey(128)
4990 .BlockMode(BlockMode::GCM)
4991 .Padding(PaddingMode::NONE)
4992 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4993 string aad = "foobar";
4994 string message = "123456789012345678901234567890123456";
4995 auto params = AuthorizationSetBuilder()
4996 .BlockMode(BlockMode::GCM)
4997 .Padding(PaddingMode::NONE)
4998 .Authorization(TAG_MAC_LENGTH, 128);
4999
Selene Huang31ab4042020-04-29 04:22:39 -07005000 // Encrypt
5001 AuthorizationSet begin_out_params;
5002 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5003 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005004 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005005
5006 AuthorizationSet finish_out_params;
5007 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005008 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5009 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005010
5011 params = AuthorizationSetBuilder()
5012 .Authorizations(begin_out_params)
5013 .BlockMode(BlockMode::GCM)
5014 .Padding(PaddingMode::NONE)
5015 .Authorization(TAG_MAC_LENGTH, 96);
5016
5017 // Decrypt.
5018 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5019}
5020
5021/*
5022 * EncryptionOperationsTest.AesGcmCorruptKey
5023 *
5024 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5025 */
5026TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5027 const uint8_t nonce_bytes[] = {
5028 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5029 };
5030 string nonce = make_string(nonce_bytes);
5031 const uint8_t ciphertext_bytes[] = {
5032 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5033 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5034 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5035 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5036 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5037 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5038 };
5039 string ciphertext = make_string(ciphertext_bytes);
5040
5041 auto params = AuthorizationSetBuilder()
5042 .BlockMode(BlockMode::GCM)
5043 .Padding(PaddingMode::NONE)
5044 .Authorization(TAG_MAC_LENGTH, 128)
5045 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5046
5047 auto import_params = AuthorizationSetBuilder()
5048 .Authorization(TAG_NO_AUTH_REQUIRED)
5049 .AesEncryptionKey(128)
5050 .BlockMode(BlockMode::GCM)
5051 .Padding(PaddingMode::NONE)
5052 .Authorization(TAG_CALLER_NONCE)
5053 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5054
5055 // Import correct key and decrypt
5056 const uint8_t key_bytes[] = {
5057 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5058 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5059 };
5060 string key = make_string(key_bytes);
5061 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5062 string plaintext = DecryptMessage(ciphertext, params);
5063 CheckedDeleteKey();
5064
5065 // Corrupt key and attempt to decrypt
5066 key[0] = 0;
5067 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5068 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5069 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5070 CheckedDeleteKey();
5071}
5072
5073/*
5074 * EncryptionOperationsTest.AesGcmAadNoData
5075 *
5076 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5077 * encrypt.
5078 */
5079TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5081 .Authorization(TAG_NO_AUTH_REQUIRED)
5082 .AesEncryptionKey(128)
5083 .BlockMode(BlockMode::GCM)
5084 .Padding(PaddingMode::NONE)
5085 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5086
5087 string aad = "1234567890123456";
5088 auto params = AuthorizationSetBuilder()
5089 .BlockMode(BlockMode::GCM)
5090 .Padding(PaddingMode::NONE)
5091 .Authorization(TAG_MAC_LENGTH, 128);
5092
Selene Huang31ab4042020-04-29 04:22:39 -07005093 // Encrypt
5094 AuthorizationSet begin_out_params;
5095 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5096 string ciphertext;
5097 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005098 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5099 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005100 EXPECT_TRUE(finish_out_params.empty());
5101
5102 // Grab nonce
5103 params.push_back(begin_out_params);
5104
5105 // Decrypt.
5106 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005107 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005108 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005109 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005110
5111 EXPECT_TRUE(finish_out_params.empty());
5112
5113 EXPECT_EQ("", plaintext);
5114}
5115
5116/*
5117 * EncryptionOperationsTest.AesGcmMultiPartAad
5118 *
5119 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5120 * chunks.
5121 */
5122TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5123 const size_t tag_bits = 128;
5124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5125 .Authorization(TAG_NO_AUTH_REQUIRED)
5126 .AesEncryptionKey(128)
5127 .BlockMode(BlockMode::GCM)
5128 .Padding(PaddingMode::NONE)
5129 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5130
5131 string message = "123456789012345678901234567890123456";
5132 auto begin_params = AuthorizationSetBuilder()
5133 .BlockMode(BlockMode::GCM)
5134 .Padding(PaddingMode::NONE)
5135 .Authorization(TAG_MAC_LENGTH, tag_bits);
5136 AuthorizationSet begin_out_params;
5137
Selene Huang31ab4042020-04-29 04:22:39 -07005138 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5139
5140 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005141 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5142 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005143 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005144 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5145 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005146
Selene Huang31ab4042020-04-29 04:22:39 -07005147 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005148 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005149
5150 // Grab nonce.
5151 begin_params.push_back(begin_out_params);
5152
5153 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005154 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005155 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005156 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005157 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005158 EXPECT_EQ(message, plaintext);
5159}
5160
5161/*
5162 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5163 *
5164 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5165 */
5166TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5167 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5168 .Authorization(TAG_NO_AUTH_REQUIRED)
5169 .AesEncryptionKey(128)
5170 .BlockMode(BlockMode::GCM)
5171 .Padding(PaddingMode::NONE)
5172 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5173
5174 string message = "123456789012345678901234567890123456";
5175 auto begin_params = AuthorizationSetBuilder()
5176 .BlockMode(BlockMode::GCM)
5177 .Padding(PaddingMode::NONE)
5178 .Authorization(TAG_MAC_LENGTH, 128);
5179 AuthorizationSet begin_out_params;
5180
Selene Huang31ab4042020-04-29 04:22:39 -07005181 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5182
Shawn Willden92d79c02021-02-19 07:31:55 -07005183 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005184 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005185 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5186 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005187
David Drysdaled2cc8c22021-04-15 13:29:45 +01005188 // The failure should have already cancelled the operation.
5189 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5190
Shawn Willden92d79c02021-02-19 07:31:55 -07005191 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005192}
5193
5194/*
5195 * EncryptionOperationsTest.AesGcmBadAad
5196 *
5197 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5198 */
5199TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5200 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5201 .Authorization(TAG_NO_AUTH_REQUIRED)
5202 .AesEncryptionKey(128)
5203 .BlockMode(BlockMode::GCM)
5204 .Padding(PaddingMode::NONE)
5205 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5206
5207 string message = "12345678901234567890123456789012";
5208 auto begin_params = AuthorizationSetBuilder()
5209 .BlockMode(BlockMode::GCM)
5210 .Padding(PaddingMode::NONE)
5211 .Authorization(TAG_MAC_LENGTH, 128);
5212
Selene Huang31ab4042020-04-29 04:22:39 -07005213 // Encrypt
5214 AuthorizationSet begin_out_params;
5215 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005216 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005217 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005218 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005219
5220 // Grab nonce
5221 begin_params.push_back(begin_out_params);
5222
Selene Huang31ab4042020-04-29 04:22:39 -07005223 // Decrypt.
5224 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005225 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005226 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005227 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005228}
5229
5230/*
5231 * EncryptionOperationsTest.AesGcmWrongNonce
5232 *
5233 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5234 */
5235TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5237 .Authorization(TAG_NO_AUTH_REQUIRED)
5238 .AesEncryptionKey(128)
5239 .BlockMode(BlockMode::GCM)
5240 .Padding(PaddingMode::NONE)
5241 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5242
5243 string message = "12345678901234567890123456789012";
5244 auto begin_params = AuthorizationSetBuilder()
5245 .BlockMode(BlockMode::GCM)
5246 .Padding(PaddingMode::NONE)
5247 .Authorization(TAG_MAC_LENGTH, 128);
5248
Selene Huang31ab4042020-04-29 04:22:39 -07005249 // Encrypt
5250 AuthorizationSet begin_out_params;
5251 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005252 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005253 string ciphertext;
5254 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005255 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005256
5257 // Wrong nonce
5258 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5259
5260 // Decrypt.
5261 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005262 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005263 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005264 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005265
5266 // With wrong nonce, should have gotten garbage plaintext (or none).
5267 EXPECT_NE(message, plaintext);
5268}
5269
5270/*
5271 * EncryptionOperationsTest.AesGcmCorruptTag
5272 *
5273 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5274 */
5275TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5276 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5277 .Authorization(TAG_NO_AUTH_REQUIRED)
5278 .AesEncryptionKey(128)
5279 .BlockMode(BlockMode::GCM)
5280 .Padding(PaddingMode::NONE)
5281 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5282
5283 string aad = "1234567890123456";
5284 string message = "123456789012345678901234567890123456";
5285
5286 auto params = AuthorizationSetBuilder()
5287 .BlockMode(BlockMode::GCM)
5288 .Padding(PaddingMode::NONE)
5289 .Authorization(TAG_MAC_LENGTH, 128);
5290
Selene Huang31ab4042020-04-29 04:22:39 -07005291 // Encrypt
5292 AuthorizationSet begin_out_params;
5293 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005294 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005295 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005296 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005297
5298 // Corrupt tag
5299 ++(*ciphertext.rbegin());
5300
5301 // Grab nonce
5302 params.push_back(begin_out_params);
5303
5304 // Decrypt.
5305 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005306 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005307 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005308 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005309}
5310
5311/*
5312 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5313 *
5314 * Verifies that 3DES is basically functional.
5315 */
5316TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5317 auto auths = AuthorizationSetBuilder()
5318 .TripleDesEncryptionKey(168)
5319 .BlockMode(BlockMode::ECB)
5320 .Authorization(TAG_NO_AUTH_REQUIRED)
5321 .Padding(PaddingMode::NONE);
5322
5323 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5324 // Two-block message.
5325 string message = "1234567890123456";
5326 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5327 string ciphertext1 = EncryptMessage(message, inParams);
5328 EXPECT_EQ(message.size(), ciphertext1.size());
5329
5330 string ciphertext2 = EncryptMessage(string(message), inParams);
5331 EXPECT_EQ(message.size(), ciphertext2.size());
5332
5333 // ECB is deterministic.
5334 EXPECT_EQ(ciphertext1, ciphertext2);
5335
5336 string plaintext = DecryptMessage(ciphertext1, inParams);
5337 EXPECT_EQ(message, plaintext);
5338}
5339
5340/*
5341 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5342 *
5343 * Verifies that CBC keys reject ECB usage.
5344 */
5345TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5346 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5347 .TripleDesEncryptionKey(168)
5348 .BlockMode(BlockMode::CBC)
5349 .Authorization(TAG_NO_AUTH_REQUIRED)
5350 .Padding(PaddingMode::NONE)));
5351
5352 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5353 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5354}
5355
5356/*
5357 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5358 *
5359 * Tests ECB mode with PKCS#7 padding, various message sizes.
5360 */
5361TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5362 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5363 .TripleDesEncryptionKey(168)
5364 .BlockMode(BlockMode::ECB)
5365 .Authorization(TAG_NO_AUTH_REQUIRED)
5366 .Padding(PaddingMode::PKCS7)));
5367
5368 for (size_t i = 0; i < 32; ++i) {
5369 string message(i, 'a');
5370 auto inParams =
5371 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5372 string ciphertext = EncryptMessage(message, inParams);
5373 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5374 string plaintext = DecryptMessage(ciphertext, inParams);
5375 EXPECT_EQ(message, plaintext);
5376 }
5377}
5378
5379/*
5380 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5381 *
5382 * Verifies that keys configured for no padding reject PKCS7 padding
5383 */
5384TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5385 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5386 .TripleDesEncryptionKey(168)
5387 .BlockMode(BlockMode::ECB)
5388 .Authorization(TAG_NO_AUTH_REQUIRED)
5389 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005390 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5391 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005392}
5393
5394/*
5395 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5396 *
5397 * Verifies that corrupted padding is detected.
5398 */
5399TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5401 .TripleDesEncryptionKey(168)
5402 .BlockMode(BlockMode::ECB)
5403 .Authorization(TAG_NO_AUTH_REQUIRED)
5404 .Padding(PaddingMode::PKCS7)));
5405
5406 string message = "a";
5407 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5408 EXPECT_EQ(8U, ciphertext.size());
5409 EXPECT_NE(ciphertext, message);
5410 ++ciphertext[ciphertext.size() / 2];
5411
5412 AuthorizationSetBuilder begin_params;
5413 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5414 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5415 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5416 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005417 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005418 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5419}
5420
5421struct TripleDesTestVector {
5422 const char* name;
5423 const KeyPurpose purpose;
5424 const BlockMode block_mode;
5425 const PaddingMode padding_mode;
5426 const char* key;
5427 const char* iv;
5428 const char* input;
5429 const char* output;
5430};
5431
5432// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5433// of the NIST vectors are multiples of the block size.
5434static const TripleDesTestVector kTripleDesTestVectors[] = {
5435 {
5436 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5437 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5438 "", // IV
5439 "329d86bdf1bc5af4", // input
5440 "d946c2756d78633f", // output
5441 },
5442 {
5443 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5444 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5445 "", // IV
5446 "6b1540781b01ce1997adae102dbf3c5b", // input
5447 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5448 },
5449 {
5450 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5451 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5452 "", // IV
5453 "6daad94ce08acfe7", // input
5454 "660e7d32dcc90e79", // output
5455 },
5456 {
5457 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5458 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5459 "", // IV
5460 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5461 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5462 },
5463 {
5464 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5465 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5466 "43f791134c5647ba", // IV
5467 "dcc153cef81d6f24", // input
5468 "92538bd8af18d3ba", // output
5469 },
5470 {
5471 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5472 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5473 "c2e999cb6249023c", // IV
5474 "c689aee38a301bb316da75db36f110b5", // input
5475 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5476 },
5477 {
5478 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5479 PaddingMode::PKCS7,
5480 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5481 "c2e999cb6249023c", // IV
5482 "c689aee38a301bb316da75db36f110b500", // input
5483 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5484 },
5485 {
5486 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5487 PaddingMode::PKCS7,
5488 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5489 "c2e999cb6249023c", // IV
5490 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5491 "c689aee38a301bb316da75db36f110b500", // output
5492 },
5493 {
5494 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5495 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5496 "41746c7e442d3681", // IV
5497 "c53a7b0ec40600fe", // input
5498 "d4f00eb455de1034", // output
5499 },
5500 {
5501 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5502 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5503 "3982bc02c3727d45", // IV
5504 "6006f10adef52991fcc777a1238bbb65", // input
5505 "edae09288e9e3bc05746d872b48e3b29", // output
5506 },
5507};
5508
5509/*
5510 * EncryptionOperationsTest.TripleDesTestVector
5511 *
5512 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5513 */
5514TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5515 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5516 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5517 SCOPED_TRACE(test->name);
5518 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5519 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5520 hex2str(test->output));
5521 }
5522}
5523
5524/*
5525 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5526 *
5527 * Validates CBC mode functionality.
5528 */
5529TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5531 .TripleDesEncryptionKey(168)
5532 .BlockMode(BlockMode::CBC)
5533 .Authorization(TAG_NO_AUTH_REQUIRED)
5534 .Padding(PaddingMode::NONE)));
5535
5536 ASSERT_GT(key_blob_.size(), 0U);
5537
5538 // Two-block message.
5539 string message = "1234567890123456";
5540 vector<uint8_t> iv1;
5541 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5542 EXPECT_EQ(message.size(), ciphertext1.size());
5543
5544 vector<uint8_t> iv2;
5545 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5546 EXPECT_EQ(message.size(), ciphertext2.size());
5547
5548 // IVs should be random, so ciphertexts should differ.
5549 EXPECT_NE(iv1, iv2);
5550 EXPECT_NE(ciphertext1, ciphertext2);
5551
5552 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5553 EXPECT_EQ(message, plaintext);
5554}
5555
5556/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005557 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5558 *
5559 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5560 */
5561TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5563 .TripleDesEncryptionKey(168)
5564 .BlockMode(BlockMode::CBC)
5565 .Authorization(TAG_NO_AUTH_REQUIRED)
5566 .Authorization(TAG_CALLER_NONCE)
5567 .Padding(PaddingMode::NONE)));
5568 auto params = AuthorizationSetBuilder()
5569 .BlockMode(BlockMode::CBC)
5570 .Padding(PaddingMode::NONE)
5571 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5572 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5573}
5574
5575/*
Selene Huang31ab4042020-04-29 04:22:39 -07005576 * EncryptionOperationsTest.TripleDesCallerIv
5577 *
5578 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5579 */
5580TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5581 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5582 .TripleDesEncryptionKey(168)
5583 .BlockMode(BlockMode::CBC)
5584 .Authorization(TAG_NO_AUTH_REQUIRED)
5585 .Authorization(TAG_CALLER_NONCE)
5586 .Padding(PaddingMode::NONE)));
5587 string message = "1234567890123456";
5588 vector<uint8_t> iv;
5589 // Don't specify IV, should get a random one.
5590 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5591 EXPECT_EQ(message.size(), ciphertext1.size());
5592 EXPECT_EQ(8U, iv.size());
5593
5594 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5595 EXPECT_EQ(message, plaintext);
5596
5597 // Now specify an IV, should also work.
5598 iv = AidlBuf("abcdefgh");
5599 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5600
5601 // Decrypt with correct IV.
5602 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5603 EXPECT_EQ(message, plaintext);
5604
5605 // Now try with wrong IV.
5606 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5607 EXPECT_NE(message, plaintext);
5608}
5609
5610/*
5611 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5612 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005613 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005614 */
5615TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5617 .TripleDesEncryptionKey(168)
5618 .BlockMode(BlockMode::CBC)
5619 .Authorization(TAG_NO_AUTH_REQUIRED)
5620 .Padding(PaddingMode::NONE)));
5621
5622 string message = "12345678901234567890123456789012";
5623 vector<uint8_t> iv;
5624 // Don't specify nonce, should get a random one.
5625 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5626 EXPECT_EQ(message.size(), ciphertext1.size());
5627 EXPECT_EQ(8U, iv.size());
5628
5629 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5630 EXPECT_EQ(message, plaintext);
5631
5632 // Now specify a nonce, should fail.
5633 auto input_params = AuthorizationSetBuilder()
5634 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5635 .BlockMode(BlockMode::CBC)
5636 .Padding(PaddingMode::NONE);
5637 AuthorizationSet output_params;
5638 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5639 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5640}
5641
5642/*
5643 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5644 *
5645 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5646 */
5647TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5649 .TripleDesEncryptionKey(168)
5650 .BlockMode(BlockMode::ECB)
5651 .Authorization(TAG_NO_AUTH_REQUIRED)
5652 .Padding(PaddingMode::NONE)));
5653 // Two-block message.
5654 string message = "1234567890123456";
5655 auto begin_params =
5656 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5657 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5658}
5659
5660/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005661 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005662 *
5663 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5664 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005665TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5666 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5667 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5668 .TripleDesEncryptionKey(168)
5669 .BlockMode(blockMode)
5670 .Authorization(TAG_NO_AUTH_REQUIRED)
5671 .Padding(PaddingMode::NONE)));
5672 // Message is slightly shorter than two blocks.
5673 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005674
David Drysdaled2cc8c22021-04-15 13:29:45 +01005675 auto begin_params =
5676 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5677 AuthorizationSet output_params;
5678 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5679 string ciphertext;
5680 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5681
5682 CheckedDeleteKey();
5683 }
Selene Huang31ab4042020-04-29 04:22:39 -07005684}
5685
5686/*
5687 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5688 *
5689 * Verifies that PKCS7 padding works correctly in CBC mode.
5690 */
5691TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5693 .TripleDesEncryptionKey(168)
5694 .BlockMode(BlockMode::CBC)
5695 .Authorization(TAG_NO_AUTH_REQUIRED)
5696 .Padding(PaddingMode::PKCS7)));
5697
5698 // Try various message lengths; all should work.
5699 for (size_t i = 0; i < 32; ++i) {
5700 string message(i, 'a');
5701 vector<uint8_t> iv;
5702 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5703 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5704 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5705 EXPECT_EQ(message, plaintext);
5706 }
5707}
5708
5709/*
5710 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5711 *
5712 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5713 */
5714TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5715 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5716 .TripleDesEncryptionKey(168)
5717 .BlockMode(BlockMode::CBC)
5718 .Authorization(TAG_NO_AUTH_REQUIRED)
5719 .Padding(PaddingMode::NONE)));
5720
5721 // Try various message lengths; all should fail.
5722 for (size_t i = 0; i < 32; ++i) {
5723 auto begin_params =
5724 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5725 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5726 }
5727}
5728
5729/*
5730 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5731 *
5732 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5733 */
5734TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5736 .TripleDesEncryptionKey(168)
5737 .BlockMode(BlockMode::CBC)
5738 .Authorization(TAG_NO_AUTH_REQUIRED)
5739 .Padding(PaddingMode::PKCS7)));
5740
5741 string message = "a";
5742 vector<uint8_t> iv;
5743 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5744 EXPECT_EQ(8U, ciphertext.size());
5745 EXPECT_NE(ciphertext, message);
5746 ++ciphertext[ciphertext.size() / 2];
5747
5748 auto begin_params = AuthorizationSetBuilder()
5749 .BlockMode(BlockMode::CBC)
5750 .Padding(PaddingMode::PKCS7)
5751 .Authorization(TAG_NONCE, iv);
5752 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5753 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005754 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005755 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5756}
5757
5758/*
5759 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5760 *
5761 * Verifies that 3DES CBC works with many different input sizes.
5762 */
5763TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5765 .TripleDesEncryptionKey(168)
5766 .BlockMode(BlockMode::CBC)
5767 .Authorization(TAG_NO_AUTH_REQUIRED)
5768 .Padding(PaddingMode::NONE)));
5769
5770 int increment = 7;
5771 string message(240, 'a');
5772 AuthorizationSet input_params =
5773 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5774 AuthorizationSet output_params;
5775 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5776
5777 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005778 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005779 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005780 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5781 EXPECT_EQ(message.size(), ciphertext.size());
5782
5783 // Move TAG_NONCE into input_params
5784 input_params = output_params;
5785 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5786 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5787 output_params.Clear();
5788
5789 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5790 string plaintext;
5791 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005792 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005793 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5794 EXPECT_EQ(ciphertext.size(), plaintext.size());
5795 EXPECT_EQ(message, plaintext);
5796}
5797
5798INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5799
5800typedef KeyMintAidlTestBase MaxOperationsTest;
5801
5802/*
5803 * MaxOperationsTest.TestLimitAes
5804 *
5805 * Verifies that the max uses per boot tag works correctly with AES keys.
5806 */
5807TEST_P(MaxOperationsTest, TestLimitAes) {
5808 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5809
5810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5811 .Authorization(TAG_NO_AUTH_REQUIRED)
5812 .AesEncryptionKey(128)
5813 .EcbMode()
5814 .Padding(PaddingMode::NONE)
5815 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5816
5817 string message = "1234567890123456";
5818
5819 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5820
5821 EncryptMessage(message, params);
5822 EncryptMessage(message, params);
5823 EncryptMessage(message, params);
5824
5825 // Fourth time should fail.
5826 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5827}
5828
5829/*
Qi Wud22ec842020-11-26 13:27:53 +08005830 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005831 *
5832 * Verifies that the max uses per boot tag works correctly with RSA keys.
5833 */
5834TEST_P(MaxOperationsTest, TestLimitRsa) {
5835 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5836
5837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5838 .Authorization(TAG_NO_AUTH_REQUIRED)
5839 .RsaSigningKey(1024, 65537)
5840 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005841 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5842 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005843
5844 string message = "1234567890123456";
5845
5846 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5847
5848 SignMessage(message, params);
5849 SignMessage(message, params);
5850 SignMessage(message, params);
5851
5852 // Fourth time should fail.
5853 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5854}
5855
5856INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5857
Qi Wud22ec842020-11-26 13:27:53 +08005858typedef KeyMintAidlTestBase UsageCountLimitTest;
5859
5860/*
Qi Wubeefae42021-01-28 23:16:37 +08005861 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005862 *
Qi Wubeefae42021-01-28 23:16:37 +08005863 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005864 */
Qi Wubeefae42021-01-28 23:16:37 +08005865TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005866 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5867
5868 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5869 .Authorization(TAG_NO_AUTH_REQUIRED)
5870 .AesEncryptionKey(128)
5871 .EcbMode()
5872 .Padding(PaddingMode::NONE)
5873 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5874
5875 // Check the usage count limit tag appears in the authorizations.
5876 AuthorizationSet auths;
5877 for (auto& entry : key_characteristics_) {
5878 auths.push_back(AuthorizationSet(entry.authorizations));
5879 }
5880 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5881 << "key usage count limit " << 1U << " missing";
5882
5883 string message = "1234567890123456";
5884 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5885
Qi Wubeefae42021-01-28 23:16:37 +08005886 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5887 AuthorizationSet keystore_auths =
5888 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5889
Qi Wud22ec842020-11-26 13:27:53 +08005890 // First usage of AES key should work.
5891 EncryptMessage(message, params);
5892
Qi Wud22ec842020-11-26 13:27:53 +08005893 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5894 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5895 // must be invalidated from secure storage (such as RPMB partition).
5896 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5897 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005898 // Usage count limit tag is enforced by keystore, keymint does nothing.
5899 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005900 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5901 }
5902}
5903
5904/*
Qi Wubeefae42021-01-28 23:16:37 +08005905 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005906 *
Qi Wubeefae42021-01-28 23:16:37 +08005907 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005908 */
Qi Wubeefae42021-01-28 23:16:37 +08005909TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5910 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5911
5912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5913 .Authorization(TAG_NO_AUTH_REQUIRED)
5914 .AesEncryptionKey(128)
5915 .EcbMode()
5916 .Padding(PaddingMode::NONE)
5917 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5918
5919 // Check the usage count limit tag appears in the authorizations.
5920 AuthorizationSet auths;
5921 for (auto& entry : key_characteristics_) {
5922 auths.push_back(AuthorizationSet(entry.authorizations));
5923 }
5924 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5925 << "key usage count limit " << 3U << " missing";
5926
5927 string message = "1234567890123456";
5928 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5929
5930 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5931 AuthorizationSet keystore_auths =
5932 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5933
5934 EncryptMessage(message, params);
5935 EncryptMessage(message, params);
5936 EncryptMessage(message, params);
5937
5938 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5939 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5940 // must be invalidated from secure storage (such as RPMB partition).
5941 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5942 } else {
5943 // Usage count limit tag is enforced by keystore, keymint does nothing.
5944 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5945 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5946 }
5947}
5948
5949/*
5950 * UsageCountLimitTest.TestSingleUseRsa
5951 *
5952 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5953 */
5954TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005955 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5956
5957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5958 .Authorization(TAG_NO_AUTH_REQUIRED)
5959 .RsaSigningKey(1024, 65537)
5960 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005961 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5962 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005963
5964 // Check the usage count limit tag appears in the authorizations.
5965 AuthorizationSet auths;
5966 for (auto& entry : key_characteristics_) {
5967 auths.push_back(AuthorizationSet(entry.authorizations));
5968 }
5969 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5970 << "key usage count limit " << 1U << " missing";
5971
5972 string message = "1234567890123456";
5973 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5974
Qi Wubeefae42021-01-28 23:16:37 +08005975 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5976 AuthorizationSet keystore_auths =
5977 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5978
Qi Wud22ec842020-11-26 13:27:53 +08005979 // First usage of RSA key should work.
5980 SignMessage(message, params);
5981
Qi Wud22ec842020-11-26 13:27:53 +08005982 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5983 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5984 // must be invalidated from secure storage (such as RPMB partition).
5985 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5986 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005987 // Usage count limit tag is enforced by keystore, keymint does nothing.
5988 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5989 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5990 }
5991}
5992
5993/*
5994 * UsageCountLimitTest.TestLimitUseRsa
5995 *
5996 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5997 */
5998TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5999 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6000
6001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6002 .Authorization(TAG_NO_AUTH_REQUIRED)
6003 .RsaSigningKey(1024, 65537)
6004 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006005 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6006 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006007
6008 // Check the usage count limit tag appears in the authorizations.
6009 AuthorizationSet auths;
6010 for (auto& entry : key_characteristics_) {
6011 auths.push_back(AuthorizationSet(entry.authorizations));
6012 }
6013 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6014 << "key usage count limit " << 3U << " missing";
6015
6016 string message = "1234567890123456";
6017 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6018
6019 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6020 AuthorizationSet keystore_auths =
6021 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6022
6023 SignMessage(message, params);
6024 SignMessage(message, params);
6025 SignMessage(message, params);
6026
6027 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6028 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6029 // must be invalidated from secure storage (such as RPMB partition).
6030 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6031 } else {
6032 // Usage count limit tag is enforced by keystore, keymint does nothing.
6033 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006034 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6035 }
6036}
6037
Qi Wu8e727f72021-02-11 02:49:33 +08006038/*
6039 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6040 *
6041 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6042 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6043 * in hardware.
6044 */
6045TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6046 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6047
6048 auto error = GenerateKey(AuthorizationSetBuilder()
6049 .RsaSigningKey(2048, 65537)
6050 .Digest(Digest::NONE)
6051 .Padding(PaddingMode::NONE)
6052 .Authorization(TAG_NO_AUTH_REQUIRED)
6053 .Authorization(TAG_ROLLBACK_RESISTANCE)
6054 .SetDefaultValidity());
6055 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6056
6057 if (error == ErrorCode::OK) {
6058 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6059 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6060 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6061 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6062
6063 // The KeyMint should also enforce single use key in hardware when it supports rollback
6064 // resistance.
6065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6066 .Authorization(TAG_NO_AUTH_REQUIRED)
6067 .RsaSigningKey(1024, 65537)
6068 .NoDigestOrPadding()
6069 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6070 .SetDefaultValidity()));
6071
6072 // Check the usage count limit tag appears in the hardware authorizations.
6073 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6074 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6075 << "key usage count limit " << 1U << " missing";
6076
6077 string message = "1234567890123456";
6078 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6079
6080 // First usage of RSA key should work.
6081 SignMessage(message, params);
6082
6083 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6084 // must be invalidated from secure storage (such as RPMB partition).
6085 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6086 }
6087}
6088
Qi Wud22ec842020-11-26 13:27:53 +08006089INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6090
David Drysdale7de9feb2021-03-05 14:56:19 +00006091typedef KeyMintAidlTestBase GetHardwareInfoTest;
6092
6093TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6094 // Retrieving hardware info should give the same result each time.
6095 KeyMintHardwareInfo info;
6096 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6097 KeyMintHardwareInfo info2;
6098 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6099 EXPECT_EQ(info, info2);
6100}
6101
6102INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6103
Selene Huang31ab4042020-04-29 04:22:39 -07006104typedef KeyMintAidlTestBase AddEntropyTest;
6105
6106/*
6107 * AddEntropyTest.AddEntropy
6108 *
6109 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6110 * is actually added.
6111 */
6112TEST_P(AddEntropyTest, AddEntropy) {
6113 string data = "foo";
6114 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6115}
6116
6117/*
6118 * AddEntropyTest.AddEmptyEntropy
6119 *
6120 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6121 */
6122TEST_P(AddEntropyTest, AddEmptyEntropy) {
6123 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6124}
6125
6126/*
6127 * AddEntropyTest.AddLargeEntropy
6128 *
6129 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6130 */
6131TEST_P(AddEntropyTest, AddLargeEntropy) {
6132 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6133}
6134
David Drysdalebb3d85e2021-04-13 11:15:51 +01006135/*
6136 * AddEntropyTest.AddTooLargeEntropy
6137 *
6138 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6139 */
6140TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6141 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6142 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6143}
6144
Selene Huang31ab4042020-04-29 04:22:39 -07006145INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6146
Selene Huang31ab4042020-04-29 04:22:39 -07006147typedef KeyMintAidlTestBase KeyDeletionTest;
6148
6149/**
6150 * KeyDeletionTest.DeleteKey
6151 *
6152 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6153 * valid key blob.
6154 */
6155TEST_P(KeyDeletionTest, DeleteKey) {
6156 auto error = GenerateKey(AuthorizationSetBuilder()
6157 .RsaSigningKey(2048, 65537)
6158 .Digest(Digest::NONE)
6159 .Padding(PaddingMode::NONE)
6160 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006161 .Authorization(TAG_ROLLBACK_RESISTANCE)
6162 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006163 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6164
6165 // Delete must work if rollback protection is implemented
6166 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006167 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006168 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6169
6170 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6171
6172 string message = "12345678901234567890123456789012";
6173 AuthorizationSet begin_out_params;
6174 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6175 Begin(KeyPurpose::SIGN, key_blob_,
6176 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6177 &begin_out_params));
6178 AbortIfNeeded();
6179 key_blob_ = AidlBuf();
6180 }
6181}
6182
6183/**
6184 * KeyDeletionTest.DeleteInvalidKey
6185 *
6186 * This test checks that the HAL excepts invalid key blobs..
6187 */
6188TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6189 // Generate key just to check if rollback protection is implemented
6190 auto error = GenerateKey(AuthorizationSetBuilder()
6191 .RsaSigningKey(2048, 65537)
6192 .Digest(Digest::NONE)
6193 .Padding(PaddingMode::NONE)
6194 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006195 .Authorization(TAG_ROLLBACK_RESISTANCE)
6196 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006197 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6198
6199 // Delete must work if rollback protection is implemented
6200 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006201 AuthorizationSet enforced(SecLevelAuthorizations());
6202 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006203
6204 // Delete the key we don't care about the result at this point.
6205 DeleteKey();
6206
6207 // Now create an invalid key blob and delete it.
6208 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6209
6210 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6211 }
6212}
6213
6214/**
6215 * KeyDeletionTest.DeleteAllKeys
6216 *
6217 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6218 *
6219 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6220 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6221 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6222 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6223 * credentials stored in Keystore/Keymint.
6224 */
6225TEST_P(KeyDeletionTest, DeleteAllKeys) {
6226 if (!arm_deleteAllKeys) return;
6227 auto error = GenerateKey(AuthorizationSetBuilder()
6228 .RsaSigningKey(2048, 65537)
6229 .Digest(Digest::NONE)
6230 .Padding(PaddingMode::NONE)
6231 .Authorization(TAG_NO_AUTH_REQUIRED)
6232 .Authorization(TAG_ROLLBACK_RESISTANCE));
6233 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6234
6235 // Delete must work if rollback protection is implemented
6236 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006237 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006238 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6239
6240 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6241
6242 string message = "12345678901234567890123456789012";
6243 AuthorizationSet begin_out_params;
6244
6245 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6246 Begin(KeyPurpose::SIGN, key_blob_,
6247 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6248 &begin_out_params));
6249 AbortIfNeeded();
6250 key_blob_ = AidlBuf();
6251 }
6252}
6253
6254INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6255
David Drysdaled2cc8c22021-04-15 13:29:45 +01006256typedef KeyMintAidlTestBase KeyUpgradeTest;
6257
6258/**
6259 * KeyUpgradeTest.UpgradeInvalidKey
6260 *
6261 * This test checks that the HAL excepts invalid key blobs..
6262 */
6263TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6264 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6265
6266 std::vector<uint8_t> new_blob;
6267 Status result = keymint_->upgradeKey(key_blob,
6268 AuthorizationSetBuilder()
6269 .Authorization(TAG_APPLICATION_ID, "clientid")
6270 .Authorization(TAG_APPLICATION_DATA, "appdata")
6271 .vector_data(),
6272 &new_blob);
6273 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6274}
6275
6276INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6277
Selene Huang31ab4042020-04-29 04:22:39 -07006278using UpgradeKeyTest = KeyMintAidlTestBase;
6279
6280/*
6281 * UpgradeKeyTest.UpgradeKey
6282 *
6283 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6284 */
6285TEST_P(UpgradeKeyTest, UpgradeKey) {
6286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6287 .AesEncryptionKey(128)
6288 .Padding(PaddingMode::NONE)
6289 .Authorization(TAG_NO_AUTH_REQUIRED)));
6290
6291 auto result = UpgradeKey(key_blob_);
6292
6293 // Key doesn't need upgrading. Should get okay, but no new key blob.
6294 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6295}
6296
6297INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6298
6299using ClearOperationsTest = KeyMintAidlTestBase;
6300
6301/*
6302 * ClearSlotsTest.TooManyOperations
6303 *
6304 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6305 * operations are started without being finished or aborted. Also verifies
6306 * that aborting the operations clears the operations.
6307 *
6308 */
6309TEST_P(ClearOperationsTest, TooManyOperations) {
6310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6311 .Authorization(TAG_NO_AUTH_REQUIRED)
6312 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006313 .Padding(PaddingMode::NONE)
6314 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006315
6316 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6317 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006318 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006319 AuthorizationSet out_params;
6320 ErrorCode result;
6321 size_t i;
6322
6323 for (i = 0; i < max_operations; i++) {
6324 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6325 if (ErrorCode::OK != result) {
6326 break;
6327 }
6328 }
6329 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6330 // Try again just in case there's a weird overflow bug
6331 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6332 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6333 for (size_t j = 0; j < i; j++) {
6334 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6335 << "Aboort failed for i = " << j << std::endl;
6336 }
6337 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6338 AbortIfNeeded();
6339}
6340
6341INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6342
6343typedef KeyMintAidlTestBase TransportLimitTest;
6344
6345/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006346 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006347 *
6348 * Verifies that passing input data to finish succeeds as expected.
6349 */
6350TEST_P(TransportLimitTest, LargeFinishInput) {
6351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6352 .Authorization(TAG_NO_AUTH_REQUIRED)
6353 .AesEncryptionKey(128)
6354 .BlockMode(BlockMode::ECB)
6355 .Padding(PaddingMode::NONE)));
6356
6357 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6358 auto cipher_params =
6359 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6360
6361 AuthorizationSet out_params;
6362 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6363
6364 string plain_message = std::string(1 << msg_size, 'x');
6365 string encrypted_message;
6366 auto rc = Finish(plain_message, &encrypted_message);
6367
6368 EXPECT_EQ(ErrorCode::OK, rc);
6369 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6370 << "Encrypt finish returned OK, but did not consume all of the given input";
6371 cipher_params.push_back(out_params);
6372
6373 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6374
6375 string decrypted_message;
6376 rc = Finish(encrypted_message, &decrypted_message);
6377 EXPECT_EQ(ErrorCode::OK, rc);
6378 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6379 << "Decrypt finish returned OK, did not consume all of the given input";
6380 }
6381}
6382
6383INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6384
David Zeuthene0c40892021-01-08 12:54:11 -05006385typedef KeyMintAidlTestBase KeyAgreementTest;
6386
6387int CurveToOpenSslCurveName(EcCurve curve) {
6388 switch (curve) {
6389 case EcCurve::P_224:
6390 return NID_secp224r1;
6391 case EcCurve::P_256:
6392 return NID_X9_62_prime256v1;
6393 case EcCurve::P_384:
6394 return NID_secp384r1;
6395 case EcCurve::P_521:
6396 return NID_secp521r1;
6397 }
6398}
6399
6400/*
6401 * KeyAgreementTest.Ecdh
6402 *
6403 * Verifies that ECDH works for all curves
6404 */
6405TEST_P(KeyAgreementTest, Ecdh) {
6406 // Because it's possible to use this API with keys on different curves, we
6407 // check all N^2 combinations where N is the number of supported
6408 // curves.
6409 //
6410 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6411 // lot more curves we can be smart about things and just pick |otherCurve| so
6412 // it's not |curve| and that way we end up with only 2*N runs
6413 //
6414 for (auto curve : ValidCurves()) {
6415 for (auto localCurve : ValidCurves()) {
6416 // Generate EC key locally (with access to private key material)
6417 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6418 int curveName = CurveToOpenSslCurveName(localCurve);
6419 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6420 ASSERT_NE(group, nullptr);
6421 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6422 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6423 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6424 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6425
6426 // Get encoded form of the public part of the locally generated key...
6427 unsigned char* p = nullptr;
6428 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6429 ASSERT_GT(encodedPublicKeySize, 0);
6430 vector<uint8_t> encodedPublicKey(
6431 reinterpret_cast<const uint8_t*>(p),
6432 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6433 OPENSSL_free(p);
6434
6435 // Generate EC key in KeyMint (only access to public key material)
6436 vector<uint8_t> challenge = {0x41, 0x42};
6437 EXPECT_EQ(
6438 ErrorCode::OK,
6439 GenerateKey(AuthorizationSetBuilder()
6440 .Authorization(TAG_NO_AUTH_REQUIRED)
6441 .Authorization(TAG_EC_CURVE, curve)
6442 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6443 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6444 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006445 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6446 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006447 << "Failed to generate key";
6448 ASSERT_GT(cert_chain_.size(), 0);
6449 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6450 ASSERT_NE(kmKeyCert, nullptr);
6451 // Check that keyAgreement (bit 4) is set in KeyUsage
6452 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6453 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6454 ASSERT_NE(kmPkey, nullptr);
6455 if (dump_Attestations) {
6456 for (size_t n = 0; n < cert_chain_.size(); n++) {
6457 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6458 }
6459 }
6460
6461 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6462 if (curve != localCurve) {
6463 // If the keys are using different curves KeyMint should fail with
6464 // ErrorCode:INVALID_ARGUMENT. Check that.
6465 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6466 string ZabFromKeyMintStr;
6467 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6468 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6469 &ZabFromKeyMintStr));
6470
6471 } else {
6472 // Otherwise if the keys are using the same curve, it should work.
6473 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6474 string ZabFromKeyMintStr;
6475 EXPECT_EQ(ErrorCode::OK,
6476 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6477 &ZabFromKeyMintStr));
6478 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6479
6480 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6481 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6482 ASSERT_NE(ctx, nullptr);
6483 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6484 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6485 size_t ZabFromTestLen = 0;
6486 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6487 vector<uint8_t> ZabFromTest;
6488 ZabFromTest.resize(ZabFromTestLen);
6489 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6490
6491 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6492 }
6493
6494 CheckedDeleteKey();
6495 }
6496 }
6497}
6498
6499INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6500
David Drysdaled2cc8c22021-04-15 13:29:45 +01006501using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6502
6503// This is a problematic test, as it can render the device under test permanently unusable.
6504// Re-enable and run at your own risk.
6505TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6506 auto result = DestroyAttestationIds();
6507 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6508}
6509
6510INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6511
Shawn Willdend659c7c2021-02-19 14:51:51 -07006512using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006513
David Drysdale216d9922021-05-18 11:43:31 +01006514/*
6515 * EarlyBootKeyTest.CreateEarlyBootKeys
6516 *
6517 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6518 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006519TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdale216d9922021-05-18 11:43:31 +01006520 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006521 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6522 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6523
David Drysdaleeaab0f22021-05-27 12:00:53 +01006524 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6525 ASSERT_GT(keyData.blob.size(), 0U);
6526 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6527 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6528 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006529 CheckedDeleteKey(&aesKeyData.blob);
6530 CheckedDeleteKey(&hmacKeyData.blob);
6531 CheckedDeleteKey(&rsaKeyData.blob);
6532 CheckedDeleteKey(&ecdsaKeyData.blob);
6533}
6534
David Drysdale216d9922021-05-18 11:43:31 +01006535/*
David Drysdaleeaab0f22021-05-27 12:00:53 +01006536 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6537 *
6538 * Verifies that creating an early boot key with attestation succeeds.
6539 */
6540TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6541 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6542 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6543 builder->AttestationChallenge("challenge");
6544 builder->AttestationApplicationId("app_id");
6545 });
6546
6547 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6548 ASSERT_GT(keyData.blob.size(), 0U);
6549 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6550 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6551 }
6552 CheckedDeleteKey(&aesKeyData.blob);
6553 CheckedDeleteKey(&hmacKeyData.blob);
6554 CheckedDeleteKey(&rsaKeyData.blob);
6555 CheckedDeleteKey(&ecdsaKeyData.blob);
6556}
6557
6558/*
6559 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdale216d9922021-05-18 11:43:31 +01006560 *
6561 * Verifies that using early boot keys at a later stage fails.
6562 */
6563TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6565 .Authorization(TAG_NO_AUTH_REQUIRED)
6566 .Authorization(TAG_EARLY_BOOT_ONLY)
6567 .HmacKey(128)
6568 .Digest(Digest::SHA_2_256)
6569 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6570 AuthorizationSet output_params;
6571 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6572 AuthorizationSetBuilder()
6573 .Digest(Digest::SHA_2_256)
6574 .Authorization(TAG_MAC_LENGTH, 256),
6575 &output_params));
6576}
6577
6578/*
6579 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6580 *
6581 * Verifies that importing early boot keys fails.
6582 */
6583TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6584 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6585 .Authorization(TAG_NO_AUTH_REQUIRED)
6586 .Authorization(TAG_EARLY_BOOT_ONLY)
6587 .EcdsaSigningKey(256)
6588 .Digest(Digest::SHA_2_256)
6589 .SetDefaultValidity(),
6590 KeyFormat::PKCS8, ec_256_key));
6591}
6592
David Drysdaled2cc8c22021-04-15 13:29:45 +01006593// 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 +00006594// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6595// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6596// early boot, so you'll have to reboot between runs.
6597TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6598 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6599 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6600 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6601 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6602 EXPECT_TRUE(
6603 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6604 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6605 EXPECT_TRUE(
6606 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6607
6608 // Should be able to use keys, since early boot has not ended
6609 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6610 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6611 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6612 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6613
6614 // End early boot
6615 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6616 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6617
6618 // Should not be able to use already-created keys.
6619 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6620 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6621 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6622 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6623
6624 CheckedDeleteKey(&aesKeyData.blob);
6625 CheckedDeleteKey(&hmacKeyData.blob);
6626 CheckedDeleteKey(&rsaKeyData.blob);
6627 CheckedDeleteKey(&ecdsaKeyData.blob);
6628
6629 // Should not be able to create new keys
6630 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6631 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6632
6633 CheckedDeleteKey(&aesKeyData.blob);
6634 CheckedDeleteKey(&hmacKeyData.blob);
6635 CheckedDeleteKey(&rsaKeyData.blob);
6636 CheckedDeleteKey(&ecdsaKeyData.blob);
6637}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006638
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006639INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6640
Shawn Willdend659c7c2021-02-19 14:51:51 -07006641using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006642
6643// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6644// between runs... and on most test devices there are no enrolled credentials so it can't be
6645// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6646// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6647// a manual test process, which includes unlocking between runs, which is why it's included here.
6648// Well, that and the fact that it's the only test we can do without also making calls into the
6649// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6650// implications might be, so that may or may not be a solution.
6651TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6652 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6653 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6654
6655 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6656 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6657 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6658 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6659
6660 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006661 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006662 ASSERT_EQ(ErrorCode::OK, rc);
6663 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6664 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6665 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6666 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6667
6668 CheckedDeleteKey(&aesKeyData.blob);
6669 CheckedDeleteKey(&hmacKeyData.blob);
6670 CheckedDeleteKey(&rsaKeyData.blob);
6671 CheckedDeleteKey(&ecdsaKeyData.blob);
6672}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006673
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006674INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6675
Janis Danisevskis24c04702020-12-16 18:28:39 -08006676} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006677
6678int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006679 std::cout << "Testing ";
6680 auto halInstances =
6681 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6682 std::cout << "HAL instances:\n";
6683 for (auto& entry : halInstances) {
6684 std::cout << " " << entry << '\n';
6685 }
6686
Selene Huang31ab4042020-04-29 04:22:39 -07006687 ::testing::InitGoogleTest(&argc, argv);
6688 for (int i = 1; i < argc; ++i) {
6689 if (argv[i][0] == '-') {
6690 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006691 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6692 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006693 }
6694 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006695 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6696 dump_Attestations = true;
6697 } else {
6698 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006699 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006700 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6701 if (std::string(argv[i]) == "--check_patchLevels") {
6702 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6703 }
Selene Huang31ab4042020-04-29 04:22:39 -07006704 }
6705 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006706 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006707}