blob: 22988c4999ab81c261b7eb6afded2feb4b7fa570 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale92464372021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Selene Huang31ab4042020-04-29 04:22:39 -070074template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000075bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
76 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070077 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080078 if (auto p = authorizationValue(ttag, param)) {
79 return *p == expected_value;
80 }
81 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070082 });
83 return (it != set.end());
84}
85
86template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(),
89 [&](const KeyParameter& param) { return param.tag == tag; });
90 return (it != set.end());
91}
92
93constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
97 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
109
110string hex2str(string a) {
111 string b;
112 size_t num = a.size() / 2;
113 b.resize(num);
114 for (size_t i = 0; i < num; i++) {
115 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
116 }
117 return b;
118}
119
David Drysdaled2cc8c22021-04-15 13:29:45 +0100120string rsa_key = hex2str(
121 // RFC 5208 s5
122 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
123 "020100" // INTEGER length 1 value 0x00 (version)
124 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
125 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
126 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
127 "0500" // NULL (parameters)
128 // } end SEQUENCE (AlgorithmIdentifier)
129 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
130 // RFC 8017 A.1.2
131 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
132 "020100" // INTEGER length 1 value 0x00 (version)
133 "028181" // INTEGER length 0x81 value (modulus) ...
134 "00c6095409047d8634812d5a218176e4"
135 "5c41d60a75b13901f234226cffe77652"
136 "1c5a77b9e389417b71c0b6a44d13afe4"
137 "e4a2805d46c9da2935adb1ff0c1f24ea"
138 "06e62b20d776430a4d435157233c6f91"
139 "6783c30e310fcbd89b85c2d567711697"
140 "85ac12bca244abda72bfb19fc44d27c8"
141 "1e1d92de284f4061edfd99280745ea6d"
142 "25"
143 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
144 "028180" // INTEGER length 0x80 (privateExponent) value...
145 "1be0f04d9cae3718691f035338308e91"
146 "564b55899ffb5084d2460e6630257e05"
147 "b3ceab02972dfabcd6ce5f6ee2589eb6"
148 "7911ed0fac16e43a444b8c861e544a05"
149 "93365772f8baf6b22fc9e3c5f1024b06"
150 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
151 "ace7240290bef16c0b3f7f3cdd64ce3a"
152 "b5912cf6e32f39ab188358afcccd8081"
153 "0241" // INTEGER length 0x41 (prime1)
154 "00e4b49ef50f765d3b24dde01aceaaf1"
155 "30f2c76670a91a61ae08af497b4a82be"
156 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
157 "8c92bfab137fba2285227b83c342ff7c"
158 "55"
159 "0241" // INTEGER length 0x41 (prime2)
160 "00ddabb5839c4c7f6bf3d4183231f005"
161 "b31aa58affdda5c79e4cce217f6bc930"
162 "dbe563d480706c24e9ebfcab28a6cdef"
163 "d324b77e1bf7251b709092c24ff501fd"
164 "91"
165 "0240" // INTEGER length 0x40 (exponent1)
166 "23d4340eda3445d8cd26c14411da6fdc"
167 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
168 "842c1d280405bc2f6c1bea214a1d742a"
169 "b996b35b63a82a5e470fa88dbf823cdd"
170 "0240" // INTEGER length 0x40 (exponent2)
171 "1b7b57449ad30d1518249a5f56bb9829"
172 "4d4b6ac12ffc86940497a5a5837a6cf9"
173 "46262b494526d328c11e1126380fde04"
174 "c24f916dec250892db09a6d77cdba351"
175 "0240" // INTEGER length 0x40 (coefficient)
176 "7762cd8f4d050da56bd591adb515d24d"
177 "7ccd32cca0d05f866d583514bd7324d5"
178 "f33645e8ed8b4a1cb3cc4a1d67987399"
179 "f2a09f5b3fb68c88d5e5d90ac33492d6"
180 // } end SEQUENCE (PrivateKey)
181 // } end SEQUENCE (PrivateKeyInfo)
182);
Selene Huang31ab4042020-04-29 04:22:39 -0700183
Selene Huange5727e62021-04-13 22:41:20 -0700184/*
185 * DER-encoded PKCS#8 format RSA key. Generated using:
186 *
187 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
188 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100189string rsa_2048_key = hex2str(
190 // RFC 5208 s5
191 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
192 "020100" // INTEGER length 1 value 0x00 (version)
193 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
194 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
195 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
196 "0500" // NULL (parameters)
197 // } end SEQUENCE (AlgorithmIdentifier)
198 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
199 // RFC 8017 A.1.2
200 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
201 "020100" // INTEGER length 1 value 0x00 (version)
202 "02820101" // INTEGER length 0x101 value (modulus) ...
203 "00BEBC342B56D443B1299F9A6A7056E8"
204 "0A897E318476A5A18029E63B2ED739A6"
205 "1791D339F58DC763D9D14911F2EDEC38"
206 "3DEE11F6319B44510E7A3ECD9B79B973"
207 "82E49500ACF8117DC89CAF0E621F7775"
208 "6554A2FD4664BFE7AB8B59AB48340DBF"
209 "A27B93B5A81F6ECDEB02D0759307128D"
210 "F3E3BAD4055C8B840216DFAA5700670E"
211 "6C5126F0962FCB70FF308F25049164CC"
212 "F76CC2DA66A7DD9A81A714C2809D6918"
213 "6133D29D84568E892B6FFBF3199BDB14"
214 "383EE224407F190358F111A949552ABA"
215 "6714227D1BD7F6B20DD0CB88F9467B71"
216 "9339F33BFF35B3870B3F62204E4286B0"
217 "948EA348B524544B5F9838F29EE643B0"
218 "79EEF8A713B220D7806924CDF7295070"
219 "C5"
220 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
221 "02820100" // INTEGER length 0x100 (privateExponent) value...
222 "69F377F35F2F584EF075353CCD1CA997"
223 "38DB3DBC7C7FF35F9366CE176DFD1B13"
224 "5AB10030344ABF5FBECF1D4659FDEF1C"
225 "0FC430834BE1BE3911951377BB3D563A"
226 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
227 "2686C7B4B3C09A7B8354133E6F93F790"
228 "D59EAEB92E84C9A4339302CCE28FDF04"
229 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
230 "6AB706645BF074A4E4090D06FB163124"
231 "365FD5EE7A20D350E9958CC30D91326E"
232 "1B292E9EF5DB408EC42DAF737D201497"
233 "04D0A678A0FB5B5446863B099228A352"
234 "D604BA8091A164D01D5AB05397C71EAD"
235 "20BE2A08FC528FE442817809C787FEE4"
236 "AB97F97B9130D022153EDC6EB6CBE7B0"
237 "F8E3473F2E901209B5DB10F93604DB01"
238 "028181" // INTEGER length 0x81 (prime1)
239 "00E83C0998214941EA4F9293F1B77E2E"
240 "99E6CF305FAF358238E126124FEAF2EB"
241 "9724B2EA7B78E6032343821A80E55D1D"
242 "88FB12D220C3F41A56142FEC85796D19"
243 "17F1E8C774F142B67D3D6E7B7E6B4383"
244 "E94DB5929089DBB346D5BDAB40CC2D96"
245 "EE0409475E175C63BF78CFD744136740"
246 "838127EA723FF3FE7FA368C1311B4A4E"
247 "05"
248 "028181" // INTEGER length 0x81 (prime2)
249 "00D240FCC0F5D7715CDE21CB2DC86EA1"
250 "46132EA3B06F61FF2AF54BF38473F59D"
251 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
252 "B1B58C39F95E4798CCBB43E83D0119AC"
253 "F532F359CA743C85199F0286610E2009"
254 "97D7312917179AC9B67558773212EC96"
255 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
256 "94D94E066A0900B7B70E82A44FB30053"
257 "C1"
258 "028181" // INTEGER length 0x81 (exponent1)
259 "00AD15DA1CBD6A492B66851BA8C316D3"
260 "8AB700E2CFDDD926A658003513C54BAA"
261 "152B30021D667D20078F500F8AD3E7F3"
262 "945D74A891ED1A28EAD0FEEAEC8C14A8"
263 "E834CF46A13D1378C99D18940823CFDD"
264 "27EC5810D59339E0C34198AC638E09C8"
265 "7CBB1B634A9864AE9F4D5EB2D53514F6"
266 "7B4CAEC048C8AB849A02E397618F3271"
267 "35"
268 "028180" // INTEGER length 0x80 (exponent2)
269 "1FA2C1A5331880A92D8F3E281C617108"
270 "BF38244F16E352E69ED417C7153F9EC3"
271 "18F211839C643DCF8B4DD67CE2AC312E"
272 "95178D5D952F06B1BF779F4916924B70"
273 "F582A23F11304E02A5E7565AE22A35E7"
274 "4FECC8B6FDC93F92A1A37703E4CF0E63"
275 "783BD02EB716A7ECBBFA606B10B74D01"
276 "579522E7EF84D91FC522292108D902C1"
277 "028180" // INTEGER length 0x80 (coefficient)
278 "796FE3825F9DCC85DF22D58690065D93"
279 "898ACD65C087BEA8DA3A63BF4549B795"
280 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
281 "0D74F40DED8E1102C52152A31B6165F8"
282 "3A6722AECFCC35A493D7634664B888A0"
283 "8D3EB034F12EA28BFEE346E205D33482"
284 "7F778B16ED40872BD29FCB36536B6E93"
285 "FFB06778696B4A9D81BB0A9423E63DE5"
286 // } end SEQUENCE (PrivateKey)
287 // } end SEQUENCE (PrivateKeyInfo)
288);
Selene Huange5727e62021-04-13 22:41:20 -0700289
David Drysdaled2cc8c22021-04-15 13:29:45 +0100290string ec_256_key = hex2str(
291 // RFC 5208 s5
292 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
293 "020100" // INTEGER length 1 value 0 (version)
294 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
295 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
296 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
297 "0608" // OBJECT IDENTIFIER length 8 (param)
298 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
299 // } end SEQUENCE (AlgorithmIdentifier)
300 "046d" // OCTET STRING length 0x6d (privateKey) holding...
301 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
302 "020101" // INTEGER length 1 value 1 (version)
303 "0420" // OCTET STRING length 0x20 (privateKey)
304 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
305 "941eed09366bc03299986481f3a4d859"
306 "a144" // TAG [1] len 0x44 (publicKey) {
307 "03420004bf85d7720d07c25461683bc6"
308 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
309 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
310 "bcc41c6eb00083cf3376d11fd44949e0"
311 "b2183bfe"
312 // } end SEQUENCE (ECPrivateKey)
313 // } end SEQUENCE (PrivateKeyInfo)
314);
Selene Huang31ab4042020-04-29 04:22:39 -0700315
David Drysdaled2cc8c22021-04-15 13:29:45 +0100316string ec_521_key = hex2str(
317 // RFC 5208 s5
318 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
319 "020100" // INTEGER length 1 value 0 (version)
320 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
321 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
322 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
323 "0605" // OBJECT IDENTIFIER length 5 (param)
324 "2B81040023" // 1.3.132.0.35 (secp521r1)
325 // } end SEQUENCE (AlgorithmIdentifier)
326 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
327 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
328 "020101" // INTEGER length 1 value 1 (version)
329 "0442" // OCTET STRING length 0x42 (privateKey)
330 "0011458C586DB5DAA92AFAB03F4FE46A"
331 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
332 "9D18D7D08B5BCFA0E53C75B064AD51C4"
333 "49BAE0258D54B94B1E885DED08ED4FB2"
334 "5CE9"
335 "A18189" // TAG [1] len 0x89 (publicKey) {
336 "03818600040149EC11C6DF0FA122C6A9"
337 "AFD9754A4FA9513A627CA329E349535A"
338 "5629875A8ADFBE27DCB932C051986377"
339 "108D054C28C6F39B6F2C9AF81802F9F3"
340 "26B842FF2E5F3C00AB7635CFB36157FC"
341 "0882D574A10D839C1A0C049DC5E0D775"
342 "E2EE50671A208431BB45E78E70BEFE93"
343 "0DB34818EE4D5C26259F5C6B8E28A652"
344 "950F9F88D7B4B2C9D9"
345 // } end SEQUENCE (ECPrivateKey)
346 // } end SEQUENCE (PrivateKeyInfo)
347);
Selene Huang31ab4042020-04-29 04:22:39 -0700348
David Drysdaled2cc8c22021-04-15 13:29:45 +0100349string ec_256_key_rfc5915 = hex2str(
350 // RFC 5208 s5
351 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
352 "020100" // INTEGER length 1 value 0 (version)
353 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
354 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
355 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
356 "0608" // OBJECT IDENTIFIER length 8 (param)
357 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
358 // } end SEQUENCE (AlgorithmIdentifier)
359 "0479" // OCTET STRING length 0x79 (privateKey) holding...
360 // RFC 5915 s3
361 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
362 "020101" // INTEGER length 1 value 1 (version)
363 "0420" // OCTET STRING length 0x42 (privateKey)
364 "782370a8c8ce5537baadd04dcff079c8"
365 "158cfa9c67b818b38e8d21c9fa750c1d"
366 "a00a" // TAG [0] length 0xa (parameters)
367 "0608" // OBJECT IDENTIFIER length 8
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end TAG [0]
370 "a144" // TAG [1] length 0x44 (publicKey) {
371 "0342" // BIT STRING length 0x42
372 "00" // no pad bits
373 "04e2cc561ee701da0ad0ef0d176bb0c9"
374 "19d42e79c393fdc1bd6c4010d85cf2cf"
375 "8e68c905464666f98dad4f01573ba810"
376 "78b3428570a439ba3229fbc026c55068"
377 "2f"
378 // } end SEQUENCE (ECPrivateKey)
379 // } end SEQUENCE (PrivateKeyInfo)
380);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
David Drysdaled2cc8c22021-04-15 13:29:45 +0100382string ec_256_key_sec1 = hex2str(
383 // RFC 5208 s5
384 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
385 "020100" // INTEGER length 1 value 0 (version)
386 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
387 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
388 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
389 "0608" // OBJECT IDENTIFIER length 8 (param)
390 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
391 // } end SEQUENCE (AlgorithmIdentifier)
392 "046d" // OCTET STRING length 0x6d (privateKey) holding...
393 // SEC1-v2 C.4
394 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
395 "020101" // INTEGER length 1 value 0x01 (version)
396 "0420" // OCTET STRING length 0x20 (privateKey)
397 "782370a8c8ce5537baadd04dcff079c8"
398 "158cfa9c67b818b38e8d21c9fa750c1d"
399 "a144" // TAG [1] length 0x44 (publicKey) {
400 "0342" // BIT STRING length 0x42
401 "00" // no pad bits
402 "04e2cc561ee701da0ad0ef0d176bb0c9"
403 "19d42e79c393fdc1bd6c4010d85cf2cf"
404 "8e68c905464666f98dad4f01573ba810"
405 "78b3428570a439ba3229fbc026c55068"
406 "2f"
407 // } end TAG [1] (publicKey)
408 // } end SEQUENCE (PrivateKeyInfo)
409);
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411struct RSA_Delete {
412 void operator()(RSA* p) { RSA_free(p); }
413};
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415std::string make_string(const uint8_t* data, size_t length) {
416 return std::string(reinterpret_cast<const char*>(data), length);
417}
418
419template <size_t N>
420std::string make_string(const uint8_t (&a)[N]) {
421 return make_string(a, N);
422}
423
424class AidlBuf : public vector<uint8_t> {
425 typedef vector<uint8_t> super;
426
427 public:
428 AidlBuf() {}
429 AidlBuf(const super& other) : super(other) {}
430 AidlBuf(super&& other) : super(std::move(other)) {}
431 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
432
433 AidlBuf& operator=(const super& other) {
434 super::operator=(other);
435 return *this;
436 }
437
438 AidlBuf& operator=(super&& other) {
439 super::operator=(std::move(other));
440 return *this;
441 }
442
443 AidlBuf& operator=(const string& other) {
444 resize(other.size());
445 for (size_t i = 0; i < other.size(); ++i) {
446 (*this)[i] = static_cast<uint8_t>(other[i]);
447 }
448 return *this;
449 }
450
451 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
452};
453
David Drysdale4dc01072021-04-01 12:17:35 +0100454string device_suffix(const string& name) {
455 size_t pos = name.find('/');
456 if (pos == string::npos) {
457 return name;
458 }
459 return name.substr(pos + 1);
460}
461
462bool matching_rp_instance(const string& km_name,
463 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
464 string km_suffix = device_suffix(km_name);
465
466 vector<string> rp_names =
467 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
468 for (const string& rp_name : rp_names) {
469 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
470 // KeyMint instance, assume they match.
471 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
472 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
473 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
474 return true;
475 }
476 }
477 return false;
478}
479
Selene Huang31ab4042020-04-29 04:22:39 -0700480} // namespace
481
482class NewKeyGenerationTest : public KeyMintAidlTestBase {
483 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700484 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000485 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700486 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700487
Selene Huang31ab4042020-04-29 04:22:39 -0700488 // Check that some unexpected tags/values are NOT present.
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
490 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 }
492
493 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
494 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
497
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000499 }
500
501 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
502 // TODO(swillden): Distinguish which params should be in which auth list.
503 AuthorizationSet auths;
504 for (auto& entry : keyCharacteristics) {
505 auths.push_back(AuthorizationSet(entry.authorizations));
506 }
507 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
508
509 // Verify that App data, ROT and auth timeout are NOT included.
510 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
511 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700512 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
513
David Drysdaled2cc8c22021-04-15 13:29:45 +0100514 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
515 // never adds it.
516 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
517
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700519 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000520 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700521 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700522 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000523 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700524 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000525
David Drysdalebb3d85e2021-04-13 11:15:51 +0100526 if (check_patchLevels) {
527 // Should include vendor and boot patchlevels.
528 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
529 EXPECT_TRUE(vendor_pl);
530 EXPECT_EQ(*vendor_pl, vendor_patch_level());
531 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
532 EXPECT_TRUE(boot_pl);
533 }
534
David Drysdale7de9feb2021-03-05 14:56:19 +0000535 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700536 }
537};
538
539/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000540 * NewKeyGenerationTest.Aes
541 *
542 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
543 * have correct characteristics.
544 */
545TEST_P(NewKeyGenerationTest, Aes) {
546 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
547 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
548 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
549 SCOPED_TRACE(testing::Message()
550 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
551 vector<uint8_t> key_blob;
552 vector<KeyCharacteristics> key_characteristics;
553 auto builder = AuthorizationSetBuilder()
554 .AesEncryptionKey(key_size)
555 .BlockMode(block_mode)
556 .Padding(padding_mode)
557 .SetDefaultValidity();
558 if (block_mode == BlockMode::GCM) {
559 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
560 }
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
562
563 EXPECT_GT(key_blob.size(), 0U);
564 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100565 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000566
567 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
568
569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
571 << "Key size " << key_size << "missing";
572
573 CheckedDeleteKey(&key_blob);
574 }
575 }
576 }
577}
578
579/*
580 * NewKeyGenerationTest.AesInvalidSize
581 *
582 * Verifies that specifying an invalid key size for AES key generation returns
583 * UNSUPPORTED_KEY_SIZE.
584 */
585TEST_P(NewKeyGenerationTest, AesInvalidSize) {
586 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
587 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
588 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
589 SCOPED_TRACE(testing::Message()
590 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
591 vector<uint8_t> key_blob;
592 vector<KeyCharacteristics> key_characteristics;
593 auto builder = AuthorizationSetBuilder()
594 .AesEncryptionKey(key_size)
595 .BlockMode(block_mode)
596 .Padding(padding_mode)
597 .SetDefaultValidity();
598 if (block_mode == BlockMode::GCM) {
599 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
600 }
601 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
602 GenerateKey(builder, &key_blob, &key_characteristics));
603 }
604 }
605 }
606
607 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
608 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611 // No key size specified
612 auto builder = AuthorizationSetBuilder()
613 .Authorization(TAG_ALGORITHM, Algorithm::AES)
614 .BlockMode(block_mode)
615 .Padding(padding_mode)
616 .SetDefaultValidity();
617 if (block_mode == BlockMode::GCM) {
618 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
619 }
620 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
621 GenerateKey(builder, &key_blob, &key_characteristics));
622 }
623 }
624}
625
626/*
627 * NewKeyGenerationTest.AesInvalidPadding
628 *
629 * Verifies that specifying an invalid padding on AES keys gives a failure
630 * somewhere along the way.
631 */
632TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
633 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
634 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
635 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
636 SCOPED_TRACE(testing::Message()
637 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000638 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 .AesEncryptionKey(key_size)
641 .BlockMode(block_mode)
642 .Padding(padding_mode)
643 .SetDefaultValidity();
644 if (block_mode == BlockMode::GCM) {
645 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
646 }
647
Tommy Chiu3950b452021-05-03 22:01:46 +0800648 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 if (result == ErrorCode::OK) {
650 // Key creation was OK but has generated a key that cannot be used.
651 auto params =
652 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800653 if (block_mode == BlockMode::GCM) {
654 params.Authorization(TAG_MAC_LENGTH, 128);
655 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 auto result = Begin(KeyPurpose::ENCRYPT, params);
657 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100658 result == ErrorCode::INVALID_KEY_BLOB)
659 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000660 } else {
661 // The KeyMint implementation detected that the generated key
662 // is unusable.
663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
664 }
665 }
666 }
667 }
668}
669
670/*
671 * NewKeyGenerationTest.AesGcmMissingMinMac
672 *
673 * Verifies that specifying an invalid key size for AES key generation returns
674 * UNSUPPORTED_KEY_SIZE.
675 */
676TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
677 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
678 BlockMode block_mode = BlockMode::GCM;
679 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
680 SCOPED_TRACE(testing::Message()
681 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
682 vector<uint8_t> key_blob;
683 vector<KeyCharacteristics> key_characteristics;
684 // No MIN_MAC_LENGTH provided.
685 auto builder = AuthorizationSetBuilder()
686 .AesEncryptionKey(key_size)
687 .BlockMode(block_mode)
688 .Padding(padding_mode)
689 .SetDefaultValidity();
690 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
691 GenerateKey(builder, &key_blob, &key_characteristics));
692 }
693 }
694}
695
696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100697 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
698 *
699 * Verifies that specifying an invalid min MAC size for AES key generation returns
700 * UNSUPPORTED_MIN_MAC_LENGTH.
701 */
702TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
703 for (size_t min_mac_len : {88, 136}) {
704 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
705 BlockMode block_mode = BlockMode::GCM;
706 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
707 SCOPED_TRACE(testing::Message()
708 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
709 vector<uint8_t> key_blob;
710 vector<KeyCharacteristics> key_characteristics;
711 auto builder = AuthorizationSetBuilder()
712 .AesEncryptionKey(key_size)
713 .BlockMode(block_mode)
714 .Padding(padding_mode)
715 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
716 .SetDefaultValidity();
717 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
718 GenerateKey(builder, &key_blob, &key_characteristics));
719 }
720 }
721 }
722}
723
724/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000725 * NewKeyGenerationTest.TripleDes
726 *
727 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
728 * have correct characteristics.
729 */
730TEST_P(NewKeyGenerationTest, TripleDes) {
731 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
732 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
733 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
734 SCOPED_TRACE(testing::Message()
735 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
736 vector<uint8_t> key_blob;
737 vector<KeyCharacteristics> key_characteristics;
738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
739 .TripleDesEncryptionKey(key_size)
740 .BlockMode(block_mode)
741 .Padding(padding_mode)
742 .Authorization(TAG_NO_AUTH_REQUIRED)
743 .SetDefaultValidity(),
744 &key_blob, &key_characteristics));
745
746 EXPECT_GT(key_blob.size(), 0U);
747 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100748 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000749
750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
751
752 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
753 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
754 << "Key size " << key_size << "missing";
755
756 CheckedDeleteKey(&key_blob);
757 }
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.TripleDesWithAttestation
764 *
765 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
766 * have correct characteristics.
767 *
768 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
769 * put in a certificate) but which isn't an error.
770 */
771TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
772 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
773 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
774 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
775 SCOPED_TRACE(testing::Message()
776 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
777
778 auto challenge = "hello";
779 auto app_id = "foo";
780
781 vector<uint8_t> key_blob;
782 vector<KeyCharacteristics> key_characteristics;
783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
784 .TripleDesEncryptionKey(key_size)
785 .BlockMode(block_mode)
786 .Padding(padding_mode)
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AttestationChallenge(challenge)
789 .AttestationApplicationId(app_id)
790 .SetDefaultValidity(),
791 &key_blob, &key_characteristics));
792
793 EXPECT_GT(key_blob.size(), 0U);
794 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100795 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000796
797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
798
799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
800 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
801 << "Key size " << key_size << "missing";
802
803 CheckedDeleteKey(&key_blob);
804 }
805 }
806 }
807}
808
809/*
810 * NewKeyGenerationTest.TripleDesInvalidSize
811 *
812 * Verifies that specifying an invalid key size for 3-DES key generation returns
813 * UNSUPPORTED_KEY_SIZE.
814 */
815TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
816 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
817 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
818 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
819 SCOPED_TRACE(testing::Message()
820 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
821 vector<uint8_t> key_blob;
822 vector<KeyCharacteristics> key_characteristics;
823 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
824 GenerateKey(AuthorizationSetBuilder()
825 .TripleDesEncryptionKey(key_size)
826 .BlockMode(block_mode)
827 .Padding(padding_mode)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .SetDefaultValidity(),
830 &key_blob, &key_characteristics));
831 }
832 }
833 }
834
835 // Omitting the key size fails.
836 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
837 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
838 SCOPED_TRACE(testing::Message()
839 << "3DES-default-" << block_mode << "-" << padding_mode);
840 vector<uint8_t> key_blob;
841 vector<KeyCharacteristics> key_characteristics;
842 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
843 GenerateKey(AuthorizationSetBuilder()
844 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
845 .BlockMode(block_mode)
846 .Padding(padding_mode)
847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity(),
849 &key_blob, &key_characteristics));
850 }
851 }
852}
853
854/*
Selene Huang31ab4042020-04-29 04:22:39 -0700855 * NewKeyGenerationTest.Rsa
856 *
857 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
858 * have correct characteristics.
859 */
860TEST_P(NewKeyGenerationTest, Rsa) {
861 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
862 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700863 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
865 .RsaSigningKey(key_size, 65537)
866 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700869 &key_blob, &key_characteristics));
870
871 ASSERT_GT(key_blob.size(), 0U);
872 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100873 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700874
Shawn Willden7f424372021-01-10 18:06:50 -0700875 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
877 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
878 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
879 << "Key size " << key_size << "missing";
880 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
881
882 CheckedDeleteKey(&key_blob);
883 }
884}
885
886/*
Qi Wud22ec842020-11-26 13:27:53 +0800887 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100889 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
890 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891 */
892TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700893 auto challenge = "hello";
894 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700895
Selene Huang6e46f142021-04-20 19:20:11 -0700896 auto subject = "cert subj 2";
897 vector<uint8_t> subject_der(make_name_from_str(subject));
898
899 uint64_t serial_int = 66;
900 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
901
Selene Huang4f64c222021-04-13 19:54:36 -0700902 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700905 ASSERT_EQ(ErrorCode::OK,
906 GenerateKey(AuthorizationSetBuilder()
907 .RsaSigningKey(key_size, 65537)
908 .Digest(Digest::NONE)
909 .Padding(PaddingMode::NONE)
910 .AttestationChallenge(challenge)
911 .AttestationApplicationId(app_id)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
914 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
915 .SetDefaultValidity(),
916 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700917
918 ASSERT_GT(key_blob.size(), 0U);
919 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100920 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700921
922 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
923
924 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
925 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
926 << "Key size " << key_size << "missing";
927 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
928
Selene Huang6e46f142021-04-20 19:20:11 -0700929 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700930 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931 ASSERT_GT(cert_chain_.size(), 0);
932
933 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
934 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
935 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
936 sw_enforced, hw_enforced, SecLevel(),
937 cert_chain_[0].encodedCertificate));
938
939 CheckedDeleteKey(&key_blob);
940 }
941}
942
943/*
David Drysdale4dc01072021-04-01 12:17:35 +0100944 * NewKeyGenerationTest.RsaWithRpkAttestation
945 *
946 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
947 * that has been generated using an associate IRemotelyProvisionedComponent.
948 */
949TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
950 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
951 // instance.
952 std::shared_ptr<IRemotelyProvisionedComponent> rp;
953 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
954 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
955
956 // Generate a P-256 keypair to use as an attestation key.
957 MacedPublicKey macedPubKey;
958 std::vector<uint8_t> privateKeyBlob;
959 auto status =
960 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
961 ASSERT_TRUE(status.isOk());
962 vector<uint8_t> coseKeyData;
963 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
964
965 AttestationKey attestation_key;
966 attestation_key.keyBlob = std::move(privateKeyBlob);
967 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
968
969 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
970 auto challenge = "hello";
971 auto app_id = "foo";
972
973 vector<uint8_t> key_blob;
974 vector<KeyCharacteristics> key_characteristics;
975 ASSERT_EQ(ErrorCode::OK,
976 GenerateKey(AuthorizationSetBuilder()
977 .RsaSigningKey(key_size, 65537)
978 .Digest(Digest::NONE)
979 .Padding(PaddingMode::NONE)
980 .AttestationChallenge(challenge)
981 .AttestationApplicationId(app_id)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
985
986 ASSERT_GT(key_blob.size(), 0U);
987 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100988 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100989
990 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
991
992 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
993 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
994 << "Key size " << key_size << "missing";
995 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
996
997 // Attestation by itself is not valid (last entry is not self-signed).
998 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
999
1000 // The signature over the attested key should correspond to the P256 public key.
1001 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1002 ASSERT_TRUE(key_cert.get());
1003 EVP_PKEY_Ptr signing_pubkey;
1004 p256_pub_key(coseKeyData, &signing_pubkey);
1005 ASSERT_TRUE(signing_pubkey.get());
1006
1007 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1008 << "Verification of attested certificate failed "
1009 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1010
1011 CheckedDeleteKey(&key_blob);
1012 }
1013}
1014
1015/*
Selene Huang4f64c222021-04-13 19:54:36 -07001016 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1017 *
1018 * Verifies that keymint attestation for RSA encryption keys with challenge and
1019 * app id is also successful.
1020 */
1021TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1022 auto key_size = 2048;
1023 auto challenge = "hello";
1024 auto app_id = "foo";
1025
Selene Huang6e46f142021-04-20 19:20:11 -07001026 auto subject = "subj 2";
1027 vector<uint8_t> subject_der(make_name_from_str(subject));
1028
1029 uint64_t serial_int = 111166;
1030 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1031
Selene Huang4f64c222021-04-13 19:54:36 -07001032 vector<uint8_t> key_blob;
1033 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001034 ASSERT_EQ(ErrorCode::OK,
1035 GenerateKey(AuthorizationSetBuilder()
1036 .RsaEncryptionKey(key_size, 65537)
1037 .Padding(PaddingMode::NONE)
1038 .AttestationChallenge(challenge)
1039 .AttestationApplicationId(app_id)
1040 .Authorization(TAG_NO_AUTH_REQUIRED)
1041 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1042 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1043 .SetDefaultValidity(),
1044 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001045
1046 ASSERT_GT(key_blob.size(), 0U);
1047 AuthorizationSet auths;
1048 for (auto& entry : key_characteristics) {
1049 auths.push_back(AuthorizationSet(entry.authorizations));
1050 }
1051
1052 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1053 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1054
1055 // Verify that App data and ROT are NOT included.
1056 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1057 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1058
1059 // Check that some unexpected tags/values are NOT present.
1060 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1061 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1062
1063 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1064
1065 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1066 ASSERT_TRUE(os_ver);
1067 EXPECT_EQ(*os_ver, os_version());
1068
1069 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1070
1071 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1072 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1073 << "Key size " << key_size << "missing";
1074 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1075
Selene Huang6e46f142021-04-20 19:20:11 -07001076 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001077 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1078 ASSERT_GT(cert_chain_.size(), 0);
1079
1080 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1081 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1082 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1083 sw_enforced, hw_enforced, SecLevel(),
1084 cert_chain_[0].encodedCertificate));
1085
1086 CheckedDeleteKey(&key_blob);
1087}
1088
1089/*
1090 * NewKeyGenerationTest.RsaWithSelfSign
1091 *
1092 * Verifies that attesting to RSA key generation is successful, and returns
1093 * self signed certificate if no challenge is provided. And signing etc
1094 * works as expected.
1095 */
1096TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001097 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1098 vector<uint8_t> subject_der(make_name_from_str(subject));
1099
1100 uint64_t serial_int = 0;
1101 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1102
Selene Huang4f64c222021-04-13 19:54:36 -07001103 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1104 vector<uint8_t> key_blob;
1105 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001106 ASSERT_EQ(ErrorCode::OK,
1107 GenerateKey(AuthorizationSetBuilder()
1108 .RsaSigningKey(key_size, 65537)
1109 .Digest(Digest::NONE)
1110 .Padding(PaddingMode::NONE)
1111 .Authorization(TAG_NO_AUTH_REQUIRED)
1112 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1113 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1114 .SetDefaultValidity(),
1115 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001116
1117 ASSERT_GT(key_blob.size(), 0U);
1118 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001119 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001120
1121 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1122
1123 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1124 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1125 << "Key size " << key_size << "missing";
1126 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1127
Selene Huang6e46f142021-04-20 19:20:11 -07001128 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001129 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1130 ASSERT_EQ(cert_chain_.size(), 1);
1131
1132 CheckedDeleteKey(&key_blob);
1133 }
1134}
1135
1136/*
1137 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1138 *
1139 * Verifies that attesting to RSA checks for missing app ID.
1140 */
1141TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1142 auto challenge = "hello";
1143 vector<uint8_t> key_blob;
1144 vector<KeyCharacteristics> key_characteristics;
1145
1146 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1147 GenerateKey(AuthorizationSetBuilder()
1148 .RsaSigningKey(2048, 65537)
1149 .Digest(Digest::NONE)
1150 .Padding(PaddingMode::NONE)
1151 .AttestationChallenge(challenge)
1152 .Authorization(TAG_NO_AUTH_REQUIRED)
1153 .SetDefaultValidity(),
1154 &key_blob, &key_characteristics));
1155}
1156
1157/*
1158 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1159 *
1160 * Verifies that attesting to RSA ignores app id if challenge is missing.
1161 */
1162TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1163 auto key_size = 2048;
1164 auto app_id = "foo";
1165
Selene Huang6e46f142021-04-20 19:20:11 -07001166 auto subject = "cert subj 2";
1167 vector<uint8_t> subject_der(make_name_from_str(subject));
1168
1169 uint64_t serial_int = 1;
1170 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1171
Selene Huang4f64c222021-04-13 19:54:36 -07001172 vector<uint8_t> key_blob;
1173 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001174 ASSERT_EQ(ErrorCode::OK,
1175 GenerateKey(AuthorizationSetBuilder()
1176 .RsaSigningKey(key_size, 65537)
1177 .Digest(Digest::NONE)
1178 .Padding(PaddingMode::NONE)
1179 .AttestationApplicationId(app_id)
1180 .Authorization(TAG_NO_AUTH_REQUIRED)
1181 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1182 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1183 .SetDefaultValidity(),
1184 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001185
1186 ASSERT_GT(key_blob.size(), 0U);
1187 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001188 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001189
1190 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1191
1192 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1193 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1194 << "Key size " << key_size << "missing";
1195 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1196
Selene Huang6e46f142021-04-20 19:20:11 -07001197 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001198 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1199 ASSERT_EQ(cert_chain_.size(), 1);
1200
1201 CheckedDeleteKey(&key_blob);
1202}
1203
1204/*
Qi Wud22ec842020-11-26 13:27:53 +08001205 * NewKeyGenerationTest.LimitedUsageRsa
1206 *
1207 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1208 * resulting keys have correct characteristics.
1209 */
1210TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1211 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1212 vector<uint8_t> key_blob;
1213 vector<KeyCharacteristics> key_characteristics;
1214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1215 .RsaSigningKey(key_size, 65537)
1216 .Digest(Digest::NONE)
1217 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001218 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1219 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001220 &key_blob, &key_characteristics));
1221
1222 ASSERT_GT(key_blob.size(), 0U);
1223 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001224 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001225
1226 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1227
1228 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1229 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1230 << "Key size " << key_size << "missing";
1231 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1232
1233 // Check the usage count limit tag appears in the authorizations.
1234 AuthorizationSet auths;
1235 for (auto& entry : key_characteristics) {
1236 auths.push_back(AuthorizationSet(entry.authorizations));
1237 }
1238 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1239 << "key usage count limit " << 1U << " missing";
1240
1241 CheckedDeleteKey(&key_blob);
1242 }
1243}
1244
1245/*
Qi Wubeefae42021-01-28 23:16:37 +08001246 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1247 *
1248 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1249 * resulting keys have correct characteristics and attestation.
1250 */
1251TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001252 auto challenge = "hello";
1253 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001254
Selene Huang6e46f142021-04-20 19:20:11 -07001255 auto subject = "cert subj 2";
1256 vector<uint8_t> subject_der(make_name_from_str(subject));
1257
1258 uint64_t serial_int = 66;
1259 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1260
Selene Huang4f64c222021-04-13 19:54:36 -07001261 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001262 vector<uint8_t> key_blob;
1263 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001264 ASSERT_EQ(ErrorCode::OK,
1265 GenerateKey(AuthorizationSetBuilder()
1266 .RsaSigningKey(key_size, 65537)
1267 .Digest(Digest::NONE)
1268 .Padding(PaddingMode::NONE)
1269 .AttestationChallenge(challenge)
1270 .AttestationApplicationId(app_id)
1271 .Authorization(TAG_NO_AUTH_REQUIRED)
1272 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1273 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1274 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1275 .SetDefaultValidity(),
1276 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001277
1278 ASSERT_GT(key_blob.size(), 0U);
1279 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001280 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001281
1282 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1283
1284 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1285 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1286 << "Key size " << key_size << "missing";
1287 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1288
1289 // Check the usage count limit tag appears in the authorizations.
1290 AuthorizationSet auths;
1291 for (auto& entry : key_characteristics) {
1292 auths.push_back(AuthorizationSet(entry.authorizations));
1293 }
1294 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1295 << "key usage count limit " << 1U << " missing";
1296
1297 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001298 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001299 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001300 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001301
1302 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1303 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1304 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1305 sw_enforced, hw_enforced, SecLevel(),
1306 cert_chain_[0].encodedCertificate));
1307
1308 CheckedDeleteKey(&key_blob);
1309 }
1310}
1311
1312/*
Selene Huang31ab4042020-04-29 04:22:39 -07001313 * NewKeyGenerationTest.NoInvalidRsaSizes
1314 *
1315 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1316 */
1317TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1318 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1319 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001320 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001321 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1322 GenerateKey(AuthorizationSetBuilder()
1323 .RsaSigningKey(key_size, 65537)
1324 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001325 .Padding(PaddingMode::NONE)
1326 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001327 &key_blob, &key_characteristics));
1328 }
1329}
1330
1331/*
1332 * NewKeyGenerationTest.RsaNoDefaultSize
1333 *
1334 * Verifies that failing to specify a key size for RSA key generation returns
1335 * UNSUPPORTED_KEY_SIZE.
1336 */
1337TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1338 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1339 GenerateKey(AuthorizationSetBuilder()
1340 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1341 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001342 .SigningKey()
1343 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001344}
1345
1346/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001347 * NewKeyGenerationTest.RsaMissingParams
1348 *
1349 * Verifies that omitting optional tags works.
1350 */
1351TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1352 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1353 ASSERT_EQ(ErrorCode::OK,
1354 GenerateKey(
1355 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1356 CheckedDeleteKey();
1357 }
1358}
1359
1360/*
Selene Huang31ab4042020-04-29 04:22:39 -07001361 * NewKeyGenerationTest.Ecdsa
1362 *
1363 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1364 * have correct characteristics.
1365 */
1366TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001367 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001368 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001369 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001371 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001372 .Digest(Digest::NONE)
1373 .SetDefaultValidity(),
1374 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001375 ASSERT_GT(key_blob.size(), 0U);
1376 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001377 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001378
Shawn Willden7f424372021-01-10 18:06:50 -07001379 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001380
1381 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001382 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001383
1384 CheckedDeleteKey(&key_blob);
1385 }
1386}
1387
1388/*
Selene Huang4f64c222021-04-13 19:54:36 -07001389 * NewKeyGenerationTest.EcdsaAttestation
1390 *
1391 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1392 * an attestation will be generated.
1393 */
1394TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1395 auto challenge = "hello";
1396 auto app_id = "foo";
1397
Selene Huang6e46f142021-04-20 19:20:11 -07001398 auto subject = "cert subj 2";
1399 vector<uint8_t> subject_der(make_name_from_str(subject));
1400
1401 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1402 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1403
David Drysdale308916b2021-06-08 15:46:11 +01001404 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001405 vector<uint8_t> key_blob;
1406 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001407 ASSERT_EQ(ErrorCode::OK,
1408 GenerateKey(AuthorizationSetBuilder()
1409 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001410 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001411 .Digest(Digest::NONE)
1412 .AttestationChallenge(challenge)
1413 .AttestationApplicationId(app_id)
1414 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1415 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1416 .SetDefaultValidity(),
1417 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001418 ASSERT_GT(key_blob.size(), 0U);
1419 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001420 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001421
1422 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1423
1424 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001425 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001426
1427 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1428 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001429 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001430
1431 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1432 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1433 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1434 sw_enforced, hw_enforced, SecLevel(),
1435 cert_chain_[0].encodedCertificate));
1436
1437 CheckedDeleteKey(&key_blob);
1438 }
1439}
1440
1441/*
David Drysdale92464372021-05-14 16:46:59 +01001442 * NewKeyGenerationTest.EcdsaAttestationTags
1443 *
1444 * Verifies that creation of an attested ECDSA key includes various tags in the
1445 * attestation extension.
1446 */
1447TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1448 auto challenge = "hello";
1449 auto app_id = "foo";
1450 auto subject = "cert subj 2";
1451 vector<uint8_t> subject_der(make_name_from_str(subject));
1452 uint64_t serial_int = 0x1010;
1453 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1454 const AuthorizationSetBuilder base_builder =
1455 AuthorizationSetBuilder()
1456 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001457 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001458 .Digest(Digest::NONE)
1459 .AttestationChallenge(challenge)
1460 .AttestationApplicationId(app_id)
1461 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1462 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1463 .SetDefaultValidity();
1464
1465 // Various tags that map to fields in the attestation extension ASN.1 schema.
1466 auto extra_tags = AuthorizationSetBuilder()
1467 .Authorization(TAG_ROLLBACK_RESISTANCE)
1468 .Authorization(TAG_EARLY_BOOT_ONLY)
1469 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1470 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1471 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1472 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1473 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1474 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1475 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1476 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1477 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1478 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1479 for (const KeyParameter& tag : extra_tags) {
1480 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1481 vector<uint8_t> key_blob;
1482 vector<KeyCharacteristics> key_characteristics;
1483 AuthorizationSetBuilder builder = base_builder;
1484 builder.push_back(tag);
1485 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1486 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1487 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1488 continue;
1489 }
Seth Moore3dbdaa92021-07-12 14:18:28 -07001490 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1491 // Tag not required to be supported by all KeyMint implementations.
David Drysdale92464372021-05-14 16:46:59 +01001492 continue;
1493 }
1494 ASSERT_EQ(result, ErrorCode::OK);
1495 ASSERT_GT(key_blob.size(), 0U);
1496
1497 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1498 ASSERT_GT(cert_chain_.size(), 0);
1499 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1500
1501 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1502 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Moore3dbdaa92021-07-12 14:18:28 -07001503 // Some tags are optional, so don't require them to be in the enforcements.
1504 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale92464372021-05-14 16:46:59 +01001505 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1506 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1507 }
1508
1509 // Verifying the attestation record will check for the specific tag because
1510 // it's included in the authorizations.
1511 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1512 SecLevel(), cert_chain_[0].encodedCertificate));
1513
1514 CheckedDeleteKey(&key_blob);
1515 }
1516
1517 // Device attestation IDs should be rejected for normal attestation requests; these fields
1518 // are only used for device unique attestation.
1519 auto invalid_tags = AuthorizationSetBuilder()
1520 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1521 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1522 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1523 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1524 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1525 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1526 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1527 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1528 for (const KeyParameter& tag : invalid_tags) {
1529 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1530 vector<uint8_t> key_blob;
1531 vector<KeyCharacteristics> key_characteristics;
1532 AuthorizationSetBuilder builder =
1533 AuthorizationSetBuilder()
1534 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001535 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001536 .Digest(Digest::NONE)
1537 .AttestationChallenge(challenge)
1538 .AttestationApplicationId(app_id)
1539 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1540 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1541 .SetDefaultValidity();
1542 builder.push_back(tag);
1543 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1544 GenerateKey(builder, &key_blob, &key_characteristics));
1545 }
1546}
1547
1548/*
1549 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1550 *
1551 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1552 */
1553TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1554 auto challenge = "hello";
1555 auto attest_app_id = "foo";
1556 auto subject = "cert subj 2";
1557 vector<uint8_t> subject_der(make_name_from_str(subject));
1558 uint64_t serial_int = 0x1010;
1559 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1560
1561 // Earlier versions of the attestation extension schema included a slot:
1562 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1563 // This should never have been included, and should never be filled in.
1564 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1565 // to confirm that this field never makes it into the attestation extension.
1566 vector<uint8_t> key_blob;
1567 vector<KeyCharacteristics> key_characteristics;
1568 auto result = GenerateKey(AuthorizationSetBuilder()
1569 .Authorization(TAG_NO_AUTH_REQUIRED)
1570 .EcdsaSigningKey(EcCurve::P_256)
1571 .Digest(Digest::NONE)
1572 .AttestationChallenge(challenge)
1573 .AttestationApplicationId(attest_app_id)
1574 .Authorization(TAG_APPLICATION_ID, "client_id")
1575 .Authorization(TAG_APPLICATION_DATA, "appdata")
1576 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1577 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1578 .SetDefaultValidity(),
1579 &key_blob, &key_characteristics);
1580 ASSERT_EQ(result, ErrorCode::OK);
1581 ASSERT_GT(key_blob.size(), 0U);
1582
1583 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1584 ASSERT_GT(cert_chain_.size(), 0);
1585 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1586
1587 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1588 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1589 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1590 SecLevel(), cert_chain_[0].encodedCertificate));
1591
1592 // Check that the app id is not in the cert.
1593 string app_id = "clientid";
1594 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1595 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1596 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1597 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1598 cert_chain_[0].encodedCertificate.end());
1599
1600 CheckedDeleteKey(&key_blob);
1601}
1602
1603/*
Selene Huang4f64c222021-04-13 19:54:36 -07001604 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1605 *
1606 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1607 * the key will generate a self signed attestation.
1608 */
1609TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001610 auto subject = "cert subj 2";
1611 vector<uint8_t> subject_der(make_name_from_str(subject));
1612
1613 uint64_t serial_int = 0x123456FFF1234;
1614 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1615
David Drysdale308916b2021-06-08 15:46:11 +01001616 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001617 vector<uint8_t> key_blob;
1618 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001619 ASSERT_EQ(ErrorCode::OK,
1620 GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001621 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001622 .Digest(Digest::NONE)
1623 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1624 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1625 .SetDefaultValidity(),
1626 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001627 ASSERT_GT(key_blob.size(), 0U);
1628 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001629 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001630
1631 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1632
1633 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001634 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001635
1636 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001637 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001638 ASSERT_EQ(cert_chain_.size(), 1);
1639
1640 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1641 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1642
1643 CheckedDeleteKey(&key_blob);
1644 }
1645}
1646
1647/*
1648 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1649 *
1650 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1651 * app id must also be provided or else it will fail.
1652 */
1653TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1654 auto challenge = "hello";
1655 vector<uint8_t> key_blob;
1656 vector<KeyCharacteristics> key_characteristics;
1657
1658 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1659 GenerateKey(AuthorizationSetBuilder()
1660 .EcdsaSigningKey(EcCurve::P_256)
1661 .Digest(Digest::NONE)
1662 .AttestationChallenge(challenge)
1663 .SetDefaultValidity(),
1664 &key_blob, &key_characteristics));
1665}
1666
1667/*
1668 * NewKeyGenerationTest.EcdsaIgnoreAppId
1669 *
1670 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1671 * any appid will be ignored, and keymint will generate a self sign certificate.
1672 */
1673TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1674 auto app_id = "foo";
1675
David Drysdale308916b2021-06-08 15:46:11 +01001676 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001677 vector<uint8_t> key_blob;
1678 vector<KeyCharacteristics> key_characteristics;
1679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001680 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001681 .Digest(Digest::NONE)
1682 .AttestationApplicationId(app_id)
1683 .SetDefaultValidity(),
1684 &key_blob, &key_characteristics));
1685
1686 ASSERT_GT(key_blob.size(), 0U);
1687 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001688 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001689
1690 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1691
1692 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001693 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001694
1695 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1696 ASSERT_EQ(cert_chain_.size(), 1);
1697
1698 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1699 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1700
1701 CheckedDeleteKey(&key_blob);
1702 }
1703}
1704
1705/*
1706 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1707 *
1708 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1709 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1710 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1711 * to specify how many following bytes will be used to encode the length.
1712 */
1713TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1714 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001715 std::vector<uint32_t> app_id_lengths{143, 258};
1716
1717 for (uint32_t length : app_id_lengths) {
1718 const string app_id(length, 'a');
1719 vector<uint8_t> key_blob;
1720 vector<KeyCharacteristics> key_characteristics;
1721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1722 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001723 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001724 .Digest(Digest::NONE)
1725 .AttestationChallenge(challenge)
1726 .AttestationApplicationId(app_id)
1727 .SetDefaultValidity(),
1728 &key_blob, &key_characteristics));
1729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001731 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001732
1733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001737
1738 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1739 ASSERT_GT(cert_chain_.size(), 0);
1740
1741 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1742 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1743 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1744 sw_enforced, hw_enforced, SecLevel(),
1745 cert_chain_[0].encodedCertificate));
1746
1747 CheckedDeleteKey(&key_blob);
1748 }
1749}
1750
1751/*
Qi Wud22ec842020-11-26 13:27:53 +08001752 * NewKeyGenerationTest.LimitedUsageEcdsa
1753 *
1754 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1755 * resulting keys have correct characteristics.
1756 */
1757TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001758 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001759 vector<uint8_t> key_blob;
1760 vector<KeyCharacteristics> key_characteristics;
1761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001762 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001763 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001764 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1765 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001766 &key_blob, &key_characteristics));
1767
1768 ASSERT_GT(key_blob.size(), 0U);
1769 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001770 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001771
1772 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1773
1774 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001775 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001776
1777 // Check the usage count limit tag appears in the authorizations.
1778 AuthorizationSet auths;
1779 for (auto& entry : key_characteristics) {
1780 auths.push_back(AuthorizationSet(entry.authorizations));
1781 }
1782 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1783 << "key usage count limit " << 1U << " missing";
1784
1785 CheckedDeleteKey(&key_blob);
1786 }
1787}
1788
1789/*
Selene Huang31ab4042020-04-29 04:22:39 -07001790 * NewKeyGenerationTest.EcdsaDefaultSize
1791 *
David Drysdale308916b2021-06-08 15:46:11 +01001792 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001793 * UNSUPPORTED_KEY_SIZE.
1794 */
1795TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1796 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1797 GenerateKey(AuthorizationSetBuilder()
1798 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1799 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001800 .Digest(Digest::NONE)
1801 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001802}
1803
1804/*
1805 * NewKeyGenerationTest.EcdsaInvalidSize
1806 *
1807 * Verifies that specifying an invalid key size for EC key generation returns
1808 * UNSUPPORTED_KEY_SIZE.
1809 */
1810TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdale308916b2021-06-08 15:46:11 +01001811 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001812 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001813 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001814 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001815 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001816 .Digest(Digest::NONE)
1817 .SetDefaultValidity(),
1818 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001819 }
1820
David Drysdale308916b2021-06-08 15:46:11 +01001821 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1822 GenerateKey(AuthorizationSetBuilder()
1823 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1824 .Authorization(TAG_KEY_SIZE, 190)
1825 .SigningKey()
1826 .Digest(Digest::NONE)
1827 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001828}
1829
1830/*
1831 * NewKeyGenerationTest.EcdsaMismatchKeySize
1832 *
1833 * Verifies that specifying mismatched key size and curve for EC key generation returns
1834 * INVALID_ARGUMENT.
1835 */
1836TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1837 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1838
David Drysdale308916b2021-06-08 15:46:11 +01001839 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleca76a752021-08-18 16:45:50 +01001840 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdale308916b2021-06-08 15:46:11 +01001841 .Authorization(TAG_KEY_SIZE, 224)
1842 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleca76a752021-08-18 16:45:50 +01001843 .SigningKey()
David Drysdale308916b2021-06-08 15:46:11 +01001844 .Digest(Digest::NONE)
1845 .SetDefaultValidity());
David Drysdaleca76a752021-08-18 16:45:50 +01001846 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001847}
1848
1849/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001850 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001851 *
1852 * Verifies that keymint does not support any curve designated as unsupported.
1853 */
1854TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1855 Digest digest;
1856 if (SecLevel() == SecurityLevel::STRONGBOX) {
1857 digest = Digest::SHA_2_256;
1858 } else {
1859 digest = Digest::SHA_2_512;
1860 }
1861 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001862 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1863 .EcdsaSigningKey(curve)
1864 .Digest(digest)
1865 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001866 << "Failed to generate key on curve: " << curve;
1867 CheckedDeleteKey();
1868 }
1869}
1870
1871/*
1872 * NewKeyGenerationTest.Hmac
1873 *
1874 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1875 * characteristics.
1876 */
1877TEST_P(NewKeyGenerationTest, Hmac) {
1878 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1879 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001880 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001881 constexpr size_t key_size = 128;
1882 ASSERT_EQ(ErrorCode::OK,
1883 GenerateKey(
1884 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1885 TAG_MIN_MAC_LENGTH, 128),
1886 &key_blob, &key_characteristics));
1887
1888 ASSERT_GT(key_blob.size(), 0U);
1889 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001890 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001891
Shawn Willden7f424372021-01-10 18:06:50 -07001892 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1893 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1894 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1895 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001896
1897 CheckedDeleteKey(&key_blob);
1898 }
1899}
1900
1901/*
Selene Huang4f64c222021-04-13 19:54:36 -07001902 * NewKeyGenerationTest.HmacNoAttestation
1903 *
1904 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1905 * and app id are provided.
1906 */
1907TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1908 auto challenge = "hello";
1909 auto app_id = "foo";
1910
1911 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1912 vector<uint8_t> key_blob;
1913 vector<KeyCharacteristics> key_characteristics;
1914 constexpr size_t key_size = 128;
1915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1916 .HmacKey(key_size)
1917 .Digest(digest)
1918 .AttestationChallenge(challenge)
1919 .AttestationApplicationId(app_id)
1920 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1921 &key_blob, &key_characteristics));
1922
1923 ASSERT_GT(key_blob.size(), 0U);
1924 ASSERT_EQ(cert_chain_.size(), 0);
1925 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001926 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001927
1928 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1929 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1930 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1931 << "Key size " << key_size << "missing";
1932
1933 CheckedDeleteKey(&key_blob);
1934 }
1935}
1936
1937/*
Qi Wud22ec842020-11-26 13:27:53 +08001938 * NewKeyGenerationTest.LimitedUsageHmac
1939 *
1940 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1941 * resulting keys have correct characteristics.
1942 */
1943TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1944 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1945 vector<uint8_t> key_blob;
1946 vector<KeyCharacteristics> key_characteristics;
1947 constexpr size_t key_size = 128;
1948 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1949 .HmacKey(key_size)
1950 .Digest(digest)
1951 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1952 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1953 &key_blob, &key_characteristics));
1954
1955 ASSERT_GT(key_blob.size(), 0U);
1956 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001957 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001958
1959 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1960 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1961 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1962 << "Key size " << key_size << "missing";
1963
1964 // Check the usage count limit tag appears in the authorizations.
1965 AuthorizationSet auths;
1966 for (auto& entry : key_characteristics) {
1967 auths.push_back(AuthorizationSet(entry.authorizations));
1968 }
1969 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1970 << "key usage count limit " << 1U << " missing";
1971
1972 CheckedDeleteKey(&key_blob);
1973 }
1974}
1975
1976/*
Selene Huang31ab4042020-04-29 04:22:39 -07001977 * NewKeyGenerationTest.HmacCheckKeySizes
1978 *
1979 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1980 */
1981TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1982 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1983 if (key_size < 64 || key_size % 8 != 0) {
1984 // To keep this test from being very slow, we only test a random fraction of
1985 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1986 // them, we expect to run ~40 of them in each run.
1987 if (key_size % 8 == 0 || random() % 10 == 0) {
1988 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1989 GenerateKey(AuthorizationSetBuilder()
1990 .HmacKey(key_size)
1991 .Digest(Digest::SHA_2_256)
1992 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1993 << "HMAC key size " << key_size << " invalid";
1994 }
1995 } else {
1996 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1997 .HmacKey(key_size)
1998 .Digest(Digest::SHA_2_256)
1999 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2000 << "Failed to generate HMAC key of size " << key_size;
2001 CheckedDeleteKey();
2002 }
2003 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002004 if (SecLevel() == SecurityLevel::STRONGBOX) {
2005 // STRONGBOX devices must not support keys larger than 512 bits.
2006 size_t key_size = 520;
2007 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2008 GenerateKey(AuthorizationSetBuilder()
2009 .HmacKey(key_size)
2010 .Digest(Digest::SHA_2_256)
2011 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2012 << "HMAC key size " << key_size << " unexpectedly valid";
2013 }
Selene Huang31ab4042020-04-29 04:22:39 -07002014}
2015
2016/*
2017 * NewKeyGenerationTest.HmacCheckMinMacLengths
2018 *
2019 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2020 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2021 * specific MAC length that failed, so reproducing a failed run will be easy.
2022 */
2023TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2024 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2025 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2026 // To keep this test from being very long, we only test a random fraction of
2027 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2028 // we expect to run ~17 of them in each run.
2029 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2030 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2031 GenerateKey(AuthorizationSetBuilder()
2032 .HmacKey(128)
2033 .Digest(Digest::SHA_2_256)
2034 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2035 << "HMAC min mac length " << min_mac_length << " invalid.";
2036 }
2037 } else {
2038 EXPECT_EQ(ErrorCode::OK,
2039 GenerateKey(AuthorizationSetBuilder()
2040 .HmacKey(128)
2041 .Digest(Digest::SHA_2_256)
2042 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2043 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2044 CheckedDeleteKey();
2045 }
2046 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002047
2048 // Minimum MAC length must be no more than 512 bits.
2049 size_t min_mac_length = 520;
2050 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2051 GenerateKey(AuthorizationSetBuilder()
2052 .HmacKey(128)
2053 .Digest(Digest::SHA_2_256)
2054 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2055 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002056}
2057
2058/*
2059 * NewKeyGenerationTest.HmacMultipleDigests
2060 *
2061 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2062 */
2063TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2064 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2065
2066 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2067 GenerateKey(AuthorizationSetBuilder()
2068 .HmacKey(128)
2069 .Digest(Digest::SHA1)
2070 .Digest(Digest::SHA_2_256)
2071 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2072}
2073
2074/*
2075 * NewKeyGenerationTest.HmacDigestNone
2076 *
2077 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2078 */
2079TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2080 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2081 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2082 128)));
2083
2084 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2085 GenerateKey(AuthorizationSetBuilder()
2086 .HmacKey(128)
2087 .Digest(Digest::NONE)
2088 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2089}
2090
Selene Huang4f64c222021-04-13 19:54:36 -07002091/*
2092 * NewKeyGenerationTest.AesNoAttestation
2093 *
2094 * Verifies that attestation parameters to AES keys are ignored and generateKey
2095 * will succeed.
2096 */
2097TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2098 auto challenge = "hello";
2099 auto app_id = "foo";
2100
2101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2102 .Authorization(TAG_NO_AUTH_REQUIRED)
2103 .AesEncryptionKey(128)
2104 .EcbMode()
2105 .Padding(PaddingMode::PKCS7)
2106 .AttestationChallenge(challenge)
2107 .AttestationApplicationId(app_id)));
2108
2109 ASSERT_EQ(cert_chain_.size(), 0);
2110}
2111
2112/*
2113 * NewKeyGenerationTest.TripleDesNoAttestation
2114 *
2115 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2116 * will be successful. No attestation should be generated.
2117 */
2118TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2119 auto challenge = "hello";
2120 auto app_id = "foo";
2121
2122 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2123 .TripleDesEncryptionKey(168)
2124 .BlockMode(BlockMode::ECB)
2125 .Authorization(TAG_NO_AUTH_REQUIRED)
2126 .Padding(PaddingMode::NONE)
2127 .AttestationChallenge(challenge)
2128 .AttestationApplicationId(app_id)));
2129 ASSERT_EQ(cert_chain_.size(), 0);
2130}
2131
Selene Huang31ab4042020-04-29 04:22:39 -07002132INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2133
2134typedef KeyMintAidlTestBase SigningOperationsTest;
2135
2136/*
2137 * SigningOperationsTest.RsaSuccess
2138 *
2139 * Verifies that raw RSA signature operations succeed.
2140 */
2141TEST_P(SigningOperationsTest, RsaSuccess) {
2142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2143 .RsaSigningKey(2048, 65537)
2144 .Digest(Digest::NONE)
2145 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002146 .Authorization(TAG_NO_AUTH_REQUIRED)
2147 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002148 string message = "12345678901234567890123456789012";
2149 string signature = SignMessage(
2150 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdalefe42aa32021-05-06 08:10:58 +01002151 LocalVerifyMessage(message, signature,
2152 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2153}
2154
2155/*
2156 * SigningOperationsTest.RsaAllPaddingsAndDigests
2157 *
2158 * Verifies RSA signature/verification for all padding modes and digests.
2159 */
2160TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2161 auto authorizations = AuthorizationSetBuilder()
2162 .Authorization(TAG_NO_AUTH_REQUIRED)
2163 .RsaSigningKey(2048, 65537)
2164 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2165 .Padding(PaddingMode::NONE)
2166 .Padding(PaddingMode::RSA_PSS)
2167 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2168 .SetDefaultValidity();
2169
2170 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2171
2172 string message(128, 'a');
2173 string corrupt_message(message);
2174 ++corrupt_message[corrupt_message.size() / 2];
2175
2176 for (auto padding :
2177 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2178 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2179 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2180 // Digesting only makes sense with padding.
2181 continue;
2182 }
2183
2184 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2185 // PSS requires digesting.
2186 continue;
2187 }
2188
2189 string signature =
2190 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2191 LocalVerifyMessage(message, signature,
2192 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2193 }
2194 }
Selene Huang31ab4042020-04-29 04:22:39 -07002195}
2196
2197/*
2198 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2199 *
Shawn Willden7f424372021-01-10 18:06:50 -07002200 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002201 */
2202TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2204 .Authorization(TAG_NO_AUTH_REQUIRED)
2205 .RsaSigningKey(2048, 65537)
2206 .Digest(Digest::NONE)
2207 .Padding(PaddingMode::NONE)
2208 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002209 .Authorization(TAG_APPLICATION_DATA, "appdata")
2210 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002211
2212 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2213
Selene Huang31ab4042020-04-29 04:22:39 -07002214 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2215 Begin(KeyPurpose::SIGN,
2216 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2217 AbortIfNeeded();
2218 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2219 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2220 .Digest(Digest::NONE)
2221 .Padding(PaddingMode::NONE)
2222 .Authorization(TAG_APPLICATION_ID, "clientid")));
2223 AbortIfNeeded();
2224 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2225 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2226 .Digest(Digest::NONE)
2227 .Padding(PaddingMode::NONE)
2228 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2229 AbortIfNeeded();
2230 EXPECT_EQ(ErrorCode::OK,
2231 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2232 .Digest(Digest::NONE)
2233 .Padding(PaddingMode::NONE)
2234 .Authorization(TAG_APPLICATION_DATA, "appdata")
2235 .Authorization(TAG_APPLICATION_ID, "clientid")));
2236 AbortIfNeeded();
2237}
2238
2239/*
2240 * SigningOperationsTest.RsaPssSha256Success
2241 *
2242 * Verifies that RSA-PSS signature operations succeed.
2243 */
2244TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2246 .RsaSigningKey(2048, 65537)
2247 .Digest(Digest::SHA_2_256)
2248 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002249 .Authorization(TAG_NO_AUTH_REQUIRED)
2250 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002251 // Use large message, which won't work without digesting.
2252 string message(1024, 'a');
2253 string signature = SignMessage(
2254 message,
2255 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2256}
2257
2258/*
2259 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2260 *
2261 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2262 * supports only unpadded operations.
2263 */
2264TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2265 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2266 .RsaSigningKey(2048, 65537)
2267 .Digest(Digest::NONE)
2268 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002269 .Padding(PaddingMode::NONE)
2270 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002271 string message = "12345678901234567890123456789012";
2272 string signature;
2273
2274 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2275 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2276 .Digest(Digest::NONE)
2277 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2278}
2279
2280/*
2281 * SigningOperationsTest.NoUserConfirmation
2282 *
2283 * Verifies that keymint rejects signing operations for keys with
2284 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2285 * presented.
2286 */
2287TEST_P(SigningOperationsTest, NoUserConfirmation) {
2288 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002289 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2290 .RsaSigningKey(1024, 65537)
2291 .Digest(Digest::NONE)
2292 .Padding(PaddingMode::NONE)
2293 .Authorization(TAG_NO_AUTH_REQUIRED)
2294 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2295 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002296
2297 const string message = "12345678901234567890123456789012";
2298 EXPECT_EQ(ErrorCode::OK,
2299 Begin(KeyPurpose::SIGN,
2300 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2301 string signature;
2302 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2303}
2304
2305/*
2306 * SigningOperationsTest.RsaPkcs1Sha256Success
2307 *
2308 * Verifies that digested RSA-PKCS1 signature operations succeed.
2309 */
2310TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2311 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2312 .RsaSigningKey(2048, 65537)
2313 .Digest(Digest::SHA_2_256)
2314 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002315 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2316 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002317 string message(1024, 'a');
2318 string signature = SignMessage(message, AuthorizationSetBuilder()
2319 .Digest(Digest::SHA_2_256)
2320 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2321}
2322
2323/*
2324 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2325 *
2326 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2327 */
2328TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2330 .RsaSigningKey(2048, 65537)
2331 .Digest(Digest::NONE)
2332 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002333 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2334 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002335 string message(53, 'a');
2336 string signature = SignMessage(message, AuthorizationSetBuilder()
2337 .Digest(Digest::NONE)
2338 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2339}
2340
2341/*
2342 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2343 *
2344 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2345 * given a too-long message.
2346 */
2347TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2348 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2349 .RsaSigningKey(2048, 65537)
2350 .Digest(Digest::NONE)
2351 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002352 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2353 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002354 string message(257, 'a');
2355
2356 EXPECT_EQ(ErrorCode::OK,
2357 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2358 .Digest(Digest::NONE)
2359 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2360 string signature;
2361 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2362}
2363
2364/*
2365 * SigningOperationsTest.RsaPssSha512TooSmallKey
2366 *
2367 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2368 * used with a key that is too small for the message.
2369 *
2370 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2371 * keymint specification requires that salt_size == digest_size, so the message will be
2372 * digest_size * 2 +
2373 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2374 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2375 * for a 1024-bit key.
2376 */
2377TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2378 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2380 .RsaSigningKey(1024, 65537)
2381 .Digest(Digest::SHA_2_512)
2382 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002383 .Padding(PaddingMode::RSA_PSS)
2384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002385 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2386 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2387 .Digest(Digest::SHA_2_512)
2388 .Padding(PaddingMode::RSA_PSS)));
2389}
2390
2391/*
2392 * SigningOperationsTest.RsaNoPaddingTooLong
2393 *
2394 * Verifies that raw RSA signature operations fail with the correct error code when
2395 * given a too-long message.
2396 */
2397TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2399 .RsaSigningKey(2048, 65537)
2400 .Digest(Digest::NONE)
2401 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002402 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2403 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002404 // One byte too long
2405 string message(2048 / 8 + 1, 'a');
2406 ASSERT_EQ(ErrorCode::OK,
2407 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2408 .Digest(Digest::NONE)
2409 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2410 string result;
2411 ErrorCode finish_error_code = Finish(message, &result);
2412 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2413 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2414
2415 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2416 message = string(128 * 1024, 'a');
2417 ASSERT_EQ(ErrorCode::OK,
2418 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2419 .Digest(Digest::NONE)
2420 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2421 finish_error_code = Finish(message, &result);
2422 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2423 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2424}
2425
2426/*
2427 * SigningOperationsTest.RsaAbort
2428 *
2429 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2430 * test, but the behavior should be algorithm and purpose-independent.
2431 */
2432TEST_P(SigningOperationsTest, RsaAbort) {
2433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2434 .RsaSigningKey(2048, 65537)
2435 .Digest(Digest::NONE)
2436 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002437 .Padding(PaddingMode::NONE)
2438 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002439
2440 ASSERT_EQ(ErrorCode::OK,
2441 Begin(KeyPurpose::SIGN,
2442 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2443 EXPECT_EQ(ErrorCode::OK, Abort());
2444
2445 // Another abort should fail
2446 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2447
2448 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002449 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002450}
2451
2452/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002453 * SigningOperationsTest.RsaNonUniqueParams
2454 *
2455 * Verifies that an operation with multiple padding modes is rejected.
2456 */
2457TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2459 .RsaSigningKey(2048, 65537)
2460 .Digest(Digest::NONE)
2461 .Digest(Digest::SHA1)
2462 .Authorization(TAG_NO_AUTH_REQUIRED)
2463 .Padding(PaddingMode::NONE)
2464 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2465 .SetDefaultValidity()));
2466
2467 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2468 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2469 .Digest(Digest::NONE)
2470 .Padding(PaddingMode::NONE)
2471 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2472
Tommy Chiu3b56cbc2021-05-11 18:36:50 +08002473 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2474 .Digest(Digest::NONE)
2475 .Digest(Digest::SHA1)
2476 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2477 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002478
2479 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2480 Begin(KeyPurpose::SIGN,
2481 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2482}
2483
2484/*
Selene Huang31ab4042020-04-29 04:22:39 -07002485 * SigningOperationsTest.RsaUnsupportedPadding
2486 *
2487 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2488 * with a padding mode inappropriate for RSA.
2489 */
2490TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2491 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2492 .RsaSigningKey(2048, 65537)
2493 .Authorization(TAG_NO_AUTH_REQUIRED)
2494 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002495 .Padding(PaddingMode::PKCS7)
2496 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002497 ASSERT_EQ(
2498 ErrorCode::UNSUPPORTED_PADDING_MODE,
2499 Begin(KeyPurpose::SIGN,
2500 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002501 CheckedDeleteKey();
2502
2503 ASSERT_EQ(ErrorCode::OK,
2504 GenerateKey(
2505 AuthorizationSetBuilder()
2506 .RsaSigningKey(2048, 65537)
2507 .Authorization(TAG_NO_AUTH_REQUIRED)
2508 .Digest(Digest::SHA_2_256 /* supported digest */)
2509 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2510 .SetDefaultValidity()));
2511 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2512 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2513 .Digest(Digest::SHA_2_256)
2514 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002515}
2516
2517/*
2518 * SigningOperationsTest.RsaPssNoDigest
2519 *
2520 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2521 */
2522TEST_P(SigningOperationsTest, RsaNoDigest) {
2523 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2524 .RsaSigningKey(2048, 65537)
2525 .Authorization(TAG_NO_AUTH_REQUIRED)
2526 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002527 .Padding(PaddingMode::RSA_PSS)
2528 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002529 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2530 Begin(KeyPurpose::SIGN,
2531 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2532
2533 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2534 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2535}
2536
2537/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002538 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002539 *
2540 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2541 * supported in some cases (as validated in other tests), but a mode must be specified.
2542 */
2543TEST_P(SigningOperationsTest, RsaNoPadding) {
2544 // Padding must be specified
2545 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2546 .RsaKey(2048, 65537)
2547 .Authorization(TAG_NO_AUTH_REQUIRED)
2548 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002549 .Digest(Digest::NONE)
2550 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002551 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2552 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2553}
2554
2555/*
2556 * SigningOperationsTest.RsaShortMessage
2557 *
2558 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2559 */
2560TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2562 .Authorization(TAG_NO_AUTH_REQUIRED)
2563 .RsaSigningKey(2048, 65537)
2564 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002565 .Padding(PaddingMode::NONE)
2566 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002567
2568 // Barely shorter
2569 string message(2048 / 8 - 1, 'a');
2570 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2571
2572 // Much shorter
2573 message = "a";
2574 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2575}
2576
2577/*
2578 * SigningOperationsTest.RsaSignWithEncryptionKey
2579 *
2580 * Verifies that RSA encryption keys cannot be used to sign.
2581 */
2582TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2584 .Authorization(TAG_NO_AUTH_REQUIRED)
2585 .RsaEncryptionKey(2048, 65537)
2586 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002587 .Padding(PaddingMode::NONE)
2588 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002589 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2590 Begin(KeyPurpose::SIGN,
2591 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2592}
2593
2594/*
2595 * SigningOperationsTest.RsaSignTooLargeMessage
2596 *
2597 * Verifies that attempting a raw signature of a message which is the same length as the key,
2598 * but numerically larger than the public modulus, fails with the correct error.
2599 */
2600TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2601 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2602 .Authorization(TAG_NO_AUTH_REQUIRED)
2603 .RsaSigningKey(2048, 65537)
2604 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002605 .Padding(PaddingMode::NONE)
2606 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002607
2608 // Largest possible message will always be larger than the public modulus.
2609 string message(2048 / 8, static_cast<char>(0xff));
2610 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2611 .Authorization(TAG_NO_AUTH_REQUIRED)
2612 .Digest(Digest::NONE)
2613 .Padding(PaddingMode::NONE)));
2614 string signature;
2615 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2616}
2617
2618/*
David Drysdalefe42aa32021-05-06 08:10:58 +01002619 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2620 *
2621 * Verifies ECDSA signature/verification for all digests and curves.
2622 */
2623TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2624 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2625
2626 string message = "1234567890";
2627 string corrupt_message = "2234567890";
2628 for (auto curve : ValidCurves()) {
2629 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2630 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2631 .Authorization(TAG_NO_AUTH_REQUIRED)
2632 .EcdsaSigningKey(curve)
2633 .Digest(digests)
2634 .SetDefaultValidity());
2635 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2636 if (error != ErrorCode::OK) {
2637 continue;
2638 }
2639
2640 for (auto digest : digests) {
2641 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2642 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2643 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2644 }
2645
2646 auto rc = DeleteKey();
2647 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2648 }
2649}
2650
2651/*
Selene Huang31ab4042020-04-29 04:22:39 -07002652 * SigningOperationsTest.EcdsaAllCurves
2653 *
2654 * Verifies that ECDSA operations succeed with all possible curves.
2655 */
2656TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2657 for (auto curve : ValidCurves()) {
2658 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2659 .Authorization(TAG_NO_AUTH_REQUIRED)
2660 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002661 .Digest(Digest::SHA_2_256)
2662 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002663 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2664 if (error != ErrorCode::OK) continue;
2665
2666 string message(1024, 'a');
2667 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2668 CheckedDeleteKey();
2669 }
2670}
2671
2672/*
2673 * SigningOperationsTest.EcdsaNoDigestHugeData
2674 *
2675 * Verifies that ECDSA operations support very large messages, even without digesting. This
2676 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2677 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2678 * the framework.
2679 */
2680TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2681 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2682 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002683 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002684 .Digest(Digest::NONE)
2685 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002686 string message(1 * 1024, 'a');
2687 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2688}
2689
2690/*
2691 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2692 *
2693 * Verifies that using an EC key requires the correct app ID/data.
2694 */
2695TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2696 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2697 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002698 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002699 .Digest(Digest::NONE)
2700 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002701 .Authorization(TAG_APPLICATION_DATA, "appdata")
2702 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002703
2704 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2705
Selene Huang31ab4042020-04-29 04:22:39 -07002706 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2707 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2708 AbortIfNeeded();
2709 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2710 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2711 .Digest(Digest::NONE)
2712 .Authorization(TAG_APPLICATION_ID, "clientid")));
2713 AbortIfNeeded();
2714 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2715 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2716 .Digest(Digest::NONE)
2717 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2718 AbortIfNeeded();
2719 EXPECT_EQ(ErrorCode::OK,
2720 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2721 .Digest(Digest::NONE)
2722 .Authorization(TAG_APPLICATION_DATA, "appdata")
2723 .Authorization(TAG_APPLICATION_ID, "clientid")));
2724 AbortIfNeeded();
2725}
2726
2727/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002728 * SigningOperationsTest.EcdsaIncompatibleDigest
2729 *
2730 * Verifies that using an EC key requires compatible digest.
2731 */
2732TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2734 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002735 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002736 .Digest(Digest::NONE)
2737 .Digest(Digest::SHA1)
2738 .SetDefaultValidity()));
2739 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2740 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2741 AbortIfNeeded();
2742}
2743
2744/*
Selene Huang31ab4042020-04-29 04:22:39 -07002745 * SigningOperationsTest.AesEcbSign
2746 *
2747 * Verifies that attempts to use AES keys to sign fail in the correct way.
2748 */
2749TEST_P(SigningOperationsTest, AesEcbSign) {
2750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2751 .Authorization(TAG_NO_AUTH_REQUIRED)
2752 .SigningKey()
2753 .AesEncryptionKey(128)
2754 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2755
2756 AuthorizationSet out_params;
2757 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2758 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2759 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2760 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2761}
2762
2763/*
2764 * SigningOperationsTest.HmacAllDigests
2765 *
2766 * Verifies that HMAC works with all digests.
2767 */
2768TEST_P(SigningOperationsTest, HmacAllDigests) {
2769 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2771 .Authorization(TAG_NO_AUTH_REQUIRED)
2772 .HmacKey(128)
2773 .Digest(digest)
2774 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2775 << "Failed to create HMAC key with digest " << digest;
2776 string message = "12345678901234567890123456789012";
2777 string signature = MacMessage(message, digest, 160);
2778 EXPECT_EQ(160U / 8U, signature.size())
2779 << "Failed to sign with HMAC key with digest " << digest;
2780 CheckedDeleteKey();
2781 }
2782}
2783
2784/*
2785 * SigningOperationsTest.HmacSha256TooLargeMacLength
2786 *
2787 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2788 * digest size.
2789 */
2790TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2792 .Authorization(TAG_NO_AUTH_REQUIRED)
2793 .HmacKey(128)
2794 .Digest(Digest::SHA_2_256)
2795 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2796 AuthorizationSet output_params;
2797 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2798 AuthorizationSetBuilder()
2799 .Digest(Digest::SHA_2_256)
2800 .Authorization(TAG_MAC_LENGTH, 264),
2801 &output_params));
2802}
2803
2804/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002805 * SigningOperationsTest.HmacSha256InvalidMacLength
2806 *
2807 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2808 * not a multiple of 8.
2809 */
2810TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2812 .Authorization(TAG_NO_AUTH_REQUIRED)
2813 .HmacKey(128)
2814 .Digest(Digest::SHA_2_256)
2815 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2816 AuthorizationSet output_params;
2817 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2818 AuthorizationSetBuilder()
2819 .Digest(Digest::SHA_2_256)
2820 .Authorization(TAG_MAC_LENGTH, 161),
2821 &output_params));
2822}
2823
2824/*
Selene Huang31ab4042020-04-29 04:22:39 -07002825 * SigningOperationsTest.HmacSha256TooSmallMacLength
2826 *
2827 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2828 * specified minimum MAC length.
2829 */
2830TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2831 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2832 .Authorization(TAG_NO_AUTH_REQUIRED)
2833 .HmacKey(128)
2834 .Digest(Digest::SHA_2_256)
2835 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2836 AuthorizationSet output_params;
2837 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2838 AuthorizationSetBuilder()
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MAC_LENGTH, 120),
2841 &output_params));
2842}
2843
2844/*
2845 * SigningOperationsTest.HmacRfc4231TestCase3
2846 *
2847 * Validates against the test vectors from RFC 4231 test case 3.
2848 */
2849TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2850 string key(20, 0xaa);
2851 string message(50, 0xdd);
2852 uint8_t sha_224_expected[] = {
2853 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2854 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2855 };
2856 uint8_t sha_256_expected[] = {
2857 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2858 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2859 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2860 };
2861 uint8_t sha_384_expected[] = {
2862 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2863 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2864 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2865 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2866 };
2867 uint8_t sha_512_expected[] = {
2868 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2869 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2870 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2871 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2872 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2873 };
2874
2875 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2876 if (SecLevel() != SecurityLevel::STRONGBOX) {
2877 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2878 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2879 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2880 }
2881}
2882
2883/*
2884 * SigningOperationsTest.HmacRfc4231TestCase5
2885 *
2886 * Validates against the test vectors from RFC 4231 test case 5.
2887 */
2888TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2889 string key(20, 0x0c);
2890 string message = "Test With Truncation";
2891
2892 uint8_t sha_224_expected[] = {
2893 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2894 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2895 };
2896 uint8_t sha_256_expected[] = {
2897 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2898 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2899 };
2900 uint8_t sha_384_expected[] = {
2901 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2902 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2903 };
2904 uint8_t sha_512_expected[] = {
2905 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2906 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2907 };
2908
2909 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2910 if (SecLevel() != SecurityLevel::STRONGBOX) {
2911 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2912 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2913 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2914 }
2915}
2916
2917INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2918
2919typedef KeyMintAidlTestBase VerificationOperationsTest;
2920
2921/*
Selene Huang31ab4042020-04-29 04:22:39 -07002922 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2923 *
2924 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2925 */
2926TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2927 string key_material = "HelloThisIsAKey";
2928
2929 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002930 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002931 EXPECT_EQ(ErrorCode::OK,
2932 ImportKey(AuthorizationSetBuilder()
2933 .Authorization(TAG_NO_AUTH_REQUIRED)
2934 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2935 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2936 .Digest(Digest::SHA_2_256)
2937 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2938 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2939 EXPECT_EQ(ErrorCode::OK,
2940 ImportKey(AuthorizationSetBuilder()
2941 .Authorization(TAG_NO_AUTH_REQUIRED)
2942 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2943 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2944 .Digest(Digest::SHA_2_256)
2945 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2946 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2947
2948 string message = "This is a message.";
2949 string signature = SignMessage(
2950 signing_key, message,
2951 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2952
2953 // Signing key should not work.
2954 AuthorizationSet out_params;
2955 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2956 Begin(KeyPurpose::VERIFY, signing_key,
2957 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2958
2959 // Verification key should work.
2960 VerifyMessage(verification_key, message, signature,
2961 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2962
2963 CheckedDeleteKey(&signing_key);
2964 CheckedDeleteKey(&verification_key);
2965}
2966
2967INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2968
2969typedef KeyMintAidlTestBase ExportKeyTest;
2970
2971/*
2972 * ExportKeyTest.RsaUnsupportedKeyFormat
2973 *
2974 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2975 */
2976// TODO(seleneh) add ExportKey to GenerateKey
2977// check result
2978
2979class ImportKeyTest : public KeyMintAidlTestBase {
2980 public:
2981 template <TagType tag_type, Tag tag, typename ValueT>
2982 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2983 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002984 for (auto& entry : key_characteristics_) {
2985 if (entry.securityLevel == SecLevel()) {
2986 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2987 << "Tag " << tag << " with value " << expected
2988 << " not found at security level" << entry.securityLevel;
2989 } else {
2990 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2991 << "Tag " << tag << " found at security level " << entry.securityLevel;
2992 }
Selene Huang31ab4042020-04-29 04:22:39 -07002993 }
2994 }
2995
2996 void CheckOrigin() {
2997 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002998 // Origin isn't a crypto param, but it always lives with them.
2999 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003000 }
3001};
3002
3003/*
3004 * ImportKeyTest.RsaSuccess
3005 *
3006 * Verifies that importing and using an RSA key pair works correctly.
3007 */
3008TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003009 uint32_t key_size;
3010 string key;
3011
3012 if (SecLevel() == SecurityLevel::STRONGBOX) {
3013 key_size = 2048;
3014 key = rsa_2048_key;
3015 } else {
3016 key_size = 1024;
3017 key = rsa_key;
3018 }
3019
Selene Huang31ab4042020-04-29 04:22:39 -07003020 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3021 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003022 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003023 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003024 .Padding(PaddingMode::RSA_PSS)
3025 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003026 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003027
3028 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003029 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003030 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3031 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3032 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3033 CheckOrigin();
3034
3035 string message(1024 / 8, 'a');
3036 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3037 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003038 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003039}
3040
3041/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003042 * ImportKeyTest.RsaSuccessWithoutParams
3043 *
3044 * Verifies that importing and using an RSA key pair without specifying parameters
3045 * works correctly.
3046 */
3047TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3048 uint32_t key_size;
3049 string key;
3050
3051 if (SecLevel() == SecurityLevel::STRONGBOX) {
3052 key_size = 2048;
3053 key = rsa_2048_key;
3054 } else {
3055 key_size = 1024;
3056 key = rsa_key;
3057 }
3058
3059 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3060 .Authorization(TAG_NO_AUTH_REQUIRED)
3061 .SigningKey()
3062 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3063 .Digest(Digest::SHA_2_256)
3064 .Padding(PaddingMode::RSA_PSS)
3065 .SetDefaultValidity(),
3066 KeyFormat::PKCS8, key));
3067
3068 // Key size and public exponent are determined from the imported key material.
3069 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3070 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3071
3072 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3073 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3074 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3075 CheckOrigin();
3076
3077 string message(1024 / 8, 'a');
3078 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3079 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003080 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003081}
3082
3083/*
Selene Huang31ab4042020-04-29 04:22:39 -07003084 * ImportKeyTest.RsaKeySizeMismatch
3085 *
3086 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3087 * correct way.
3088 */
3089TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3090 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3091 ImportKey(AuthorizationSetBuilder()
3092 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3093 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003094 .Padding(PaddingMode::NONE)
3095 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003096 KeyFormat::PKCS8, rsa_key));
3097}
3098
3099/*
3100 * ImportKeyTest.RsaPublicExponentMismatch
3101 *
3102 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3103 * fails in the correct way.
3104 */
3105TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3106 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3107 ImportKey(AuthorizationSetBuilder()
3108 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3109 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003110 .Padding(PaddingMode::NONE)
3111 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003112 KeyFormat::PKCS8, rsa_key));
3113}
3114
3115/*
3116 * ImportKeyTest.EcdsaSuccess
3117 *
3118 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3119 */
3120TEST_P(ImportKeyTest, EcdsaSuccess) {
3121 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3122 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003123 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003124 .Digest(Digest::SHA_2_256)
3125 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003126 KeyFormat::PKCS8, ec_256_key));
3127
3128 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003129 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3130 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3131
3132 CheckOrigin();
3133
3134 string message(32, 'a');
3135 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3136 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003137 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003138}
3139
3140/*
3141 * ImportKeyTest.EcdsaP256RFC5915Success
3142 *
3143 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3144 * correctly.
3145 */
3146TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3147 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3148 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003149 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003150 .Digest(Digest::SHA_2_256)
3151 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003152 KeyFormat::PKCS8, ec_256_key_rfc5915));
3153
3154 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003155 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3156 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3157
3158 CheckOrigin();
3159
3160 string message(32, 'a');
3161 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3162 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003163 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003164}
3165
3166/*
3167 * ImportKeyTest.EcdsaP256SEC1Success
3168 *
3169 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3170 */
3171TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3172 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3173 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003174 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003175 .Digest(Digest::SHA_2_256)
3176 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003177 KeyFormat::PKCS8, ec_256_key_sec1));
3178
3179 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003180 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3181 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3182
3183 CheckOrigin();
3184
3185 string message(32, 'a');
3186 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3187 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003188 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003189}
3190
3191/*
3192 * ImportKeyTest.Ecdsa521Success
3193 *
3194 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3195 */
3196TEST_P(ImportKeyTest, Ecdsa521Success) {
3197 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3198 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3199 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003200 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003201 .Digest(Digest::SHA_2_256)
3202 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003203 KeyFormat::PKCS8, ec_521_key));
3204
3205 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003206 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3207 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3208 CheckOrigin();
3209
3210 string message(32, 'a');
3211 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3212 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003213 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003214}
3215
3216/*
Selene Huang31ab4042020-04-29 04:22:39 -07003217 * ImportKeyTest.EcdsaCurveMismatch
3218 *
3219 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3220 * the correct way.
3221 */
3222TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3223 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3224 ImportKey(AuthorizationSetBuilder()
3225 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003226 .Digest(Digest::NONE)
3227 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003228 KeyFormat::PKCS8, ec_256_key));
3229}
3230
3231/*
3232 * ImportKeyTest.AesSuccess
3233 *
3234 * Verifies that importing and using an AES key works.
3235 */
3236TEST_P(ImportKeyTest, AesSuccess) {
3237 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3238 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .AesEncryptionKey(key.size() * 8)
3241 .EcbMode()
3242 .Padding(PaddingMode::PKCS7),
3243 KeyFormat::RAW, key));
3244
3245 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3246 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3247 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3248 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3249 CheckOrigin();
3250
3251 string message = "Hello World!";
3252 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3253 string ciphertext = EncryptMessage(message, params);
3254 string plaintext = DecryptMessage(ciphertext, params);
3255 EXPECT_EQ(message, plaintext);
3256}
3257
3258/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003259 * ImportKeyTest.AesFailure
3260 *
3261 * Verifies that importing an invalid AES key fails.
3262 */
3263TEST_P(ImportKeyTest, AesFailure) {
3264 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3265 uint32_t bitlen = key.size() * 8;
3266 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003267 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003268 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003269 .Authorization(TAG_NO_AUTH_REQUIRED)
3270 .AesEncryptionKey(key_size)
3271 .EcbMode()
3272 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003273 KeyFormat::RAW, key);
3274 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003275 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3276 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003277 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003278
3279 // Explicit key size matches that of the provided key, but it's not a valid size.
3280 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3281 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3282 ImportKey(AuthorizationSetBuilder()
3283 .Authorization(TAG_NO_AUTH_REQUIRED)
3284 .AesEncryptionKey(long_key.size() * 8)
3285 .EcbMode()
3286 .Padding(PaddingMode::PKCS7),
3287 KeyFormat::RAW, long_key));
3288 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3289 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3290 ImportKey(AuthorizationSetBuilder()
3291 .Authorization(TAG_NO_AUTH_REQUIRED)
3292 .AesEncryptionKey(short_key.size() * 8)
3293 .EcbMode()
3294 .Padding(PaddingMode::PKCS7),
3295 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003296}
3297
3298/*
3299 * ImportKeyTest.TripleDesSuccess
3300 *
3301 * Verifies that importing and using a 3DES key works.
3302 */
3303TEST_P(ImportKeyTest, TripleDesSuccess) {
3304 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3305 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3306 .Authorization(TAG_NO_AUTH_REQUIRED)
3307 .TripleDesEncryptionKey(168)
3308 .EcbMode()
3309 .Padding(PaddingMode::PKCS7),
3310 KeyFormat::RAW, key));
3311
3312 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3313 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3314 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3315 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3316 CheckOrigin();
3317
3318 string message = "Hello World!";
3319 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3320 string ciphertext = EncryptMessage(message, params);
3321 string plaintext = DecryptMessage(ciphertext, params);
3322 EXPECT_EQ(message, plaintext);
3323}
3324
3325/*
3326 * ImportKeyTest.TripleDesFailure
3327 *
3328 * Verifies that importing an invalid 3DES key fails.
3329 */
3330TEST_P(ImportKeyTest, TripleDesFailure) {
3331 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003332 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003333 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003334 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003335 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003336 .Authorization(TAG_NO_AUTH_REQUIRED)
3337 .TripleDesEncryptionKey(key_size)
3338 .EcbMode()
3339 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003340 KeyFormat::RAW, key);
3341 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003342 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3343 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003344 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003345 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003346 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003347 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3348 ImportKey(AuthorizationSetBuilder()
3349 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003350 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003351 .EcbMode()
3352 .Padding(PaddingMode::PKCS7),
3353 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003354 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003355 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3356 ImportKey(AuthorizationSetBuilder()
3357 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003358 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003359 .EcbMode()
3360 .Padding(PaddingMode::PKCS7),
3361 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003362}
3363
3364/*
3365 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003366 *
3367 * Verifies that importing and using an HMAC key works.
3368 */
3369TEST_P(ImportKeyTest, HmacKeySuccess) {
3370 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3371 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3372 .Authorization(TAG_NO_AUTH_REQUIRED)
3373 .HmacKey(key.size() * 8)
3374 .Digest(Digest::SHA_2_256)
3375 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3376 KeyFormat::RAW, key));
3377
3378 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3379 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3380 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3381 CheckOrigin();
3382
3383 string message = "Hello World!";
3384 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3385 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3386}
3387
3388INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3389
3390auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003391 // IKeyMintDevice.aidl
3392 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3393 "020100" // INTEGER length 1 value 0x00 (version)
3394 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3395 "934bf94e2aa28a3f83c9f79297250262"
3396 "fbe3276b5a1c91159bbfa3ef8957aac8"
3397 "4b59b30b455a79c2973480823d8b3863"
3398 "c3deef4a8e243590268d80e18751a0e1"
3399 "30f67ce6a1ace9f79b95e097474febc9"
3400 "81195b1d13a69086c0863f66a7b7fdb4"
3401 "8792227b1ac5e2489febdf087ab54864"
3402 "83033a6f001ca5d1ec1e27f5c30f4cec"
3403 "2642074a39ae68aee552e196627a8e3d"
3404 "867e67a8c01b11e75f13cca0a97ab668"
3405 "b50cda07a8ecb7cd8e3dd7009c963653"
3406 "4f6f239cffe1fc8daa466f78b676c711"
3407 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3408 "99b801597d5220e307eaa5bee507fb94"
3409 "d1fa69f9e519b2de315bac92c36f2ea1"
3410 "fa1df4478c0ddedeae8c70e0233cd098"
3411 "040c" // OCTET STRING length 0x0c (initializationVector)
3412 "d796b02c370f1fa4cc0124f1"
3413 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3414 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3415 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3416 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3417 "3106" // SET length 0x06
3418 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3419 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3420 // } end SET
3421 // } end [1]
3422 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3423 "020120" // INTEGER length 1 value 0x20 (AES)
3424 // } end [2]
3425 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3426 "02020100" // INTEGER length 2 value 0x100
3427 // } end [3]
3428 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3429 "3103" // SET length 0x03 {
3430 "020101" // INTEGER length 1 value 0x01 (ECB)
3431 // } end SET
3432 // } end [4]
3433 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3434 "3103" // SET length 0x03 {
3435 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3436 // } end SET
3437 // } end [5]
3438 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3439 // (noAuthRequired)
3440 "0500" // NULL
3441 // } end [503]
3442 // } end SEQUENCE (AuthorizationList)
3443 // } end SEQUENCE (KeyDescription)
3444 "0420" // OCTET STRING length 0x20 (encryptedKey)
3445 "ccd540855f833a5e1480bfd2d36faf3a"
3446 "eee15df5beabe2691bc82dde2a7aa910"
3447 "0410" // OCTET STRING length 0x10 (tag)
3448 "64c9f689c60ff6223ab6e6999e0eb6e5"
3449 // } SEQUENCE (SecureKeyWrapper)
3450);
Selene Huang31ab4042020-04-29 04:22:39 -07003451
3452auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003453 // IKeyMintDevice.aidl
3454 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3455 "020100" // INTEGER length 1 value 0x00 (version)
3456 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3457 "aad93ed5924f283b4bb5526fbe7a1412"
3458 "f9d9749ec30db9062b29e574a8546f33"
3459 "c88732452f5b8e6a391ee76c39ed1712"
3460 "c61d8df6213dec1cffbc17a8c6d04c7b"
3461 "30893d8daa9b2015213e219468215532"
3462 "07f8f9931c4caba23ed3bee28b36947e"
3463 "47f10e0a5c3dc51c988a628daad3e5e1"
3464 "f4005e79c2d5a96c284b4b8d7e4948f3"
3465 "31e5b85dd5a236f85579f3ea1d1b8484"
3466 "87470bdb0ab4f81a12bee42c99fe0df4"
3467 "bee3759453e69ad1d68a809ce06b949f"
3468 "7694a990429b2fe81e066ff43e56a216"
3469 "02db70757922a4bcc23ab89f1e35da77"
3470 "586775f423e519c2ea394caf48a28d0c"
3471 "8020f1dcf6b3a68ec246f615ae96dae9"
3472 "a079b1f6eb959033c1af5c125fd94168"
3473 "040c" // OCTET STRING length 0x0c (initializationVector)
3474 "6d9721d08589581ab49204a3"
3475 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3476 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3477 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3478 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3479 "3106" // SET length 0x06
3480 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3481 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3482 // } end SET
3483 // } end [1]
3484 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3485 "020120" // INTEGER length 1 value 0x20 (AES)
3486 // } end [2]
3487 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3488 "02020100" // INTEGER length 2 value 0x100
3489 // } end [3]
3490 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3491 "3103" // SET length 0x03 {
3492 "020101" // INTEGER length 1 value 0x01 (ECB)
3493 // } end SET
3494 // } end [4]
3495 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3496 "3103" // SET length 0x03 {
3497 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3498 // } end SET
3499 // } end [5]
3500 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3501 // (noAuthRequired)
3502 "0500" // NULL
3503 // } end [503]
3504 // } end SEQUENCE (AuthorizationList)
3505 // } end SEQUENCE (KeyDescription)
3506 "0420" // OCTET STRING length 0x20 (encryptedKey)
3507 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3508 "c20d1f99a9a024a76f35c8e2cab9b68d"
3509 "0410" // OCTET STRING length 0x10 (tag)
3510 "2560c70109ae67c030f00b98b512a670"
3511 // } SEQUENCE (SecureKeyWrapper)
3512);
Selene Huang31ab4042020-04-29 04:22:39 -07003513
3514auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003515 // RFC 5208 s5
3516 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3517 "020100" // INTEGER length 1 value 0x00 (version)
3518 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3519 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3520 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3521 "0500" // NULL (parameters)
3522 // } SEQUENCE (AlgorithmIdentifier)
3523 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3524 // RFC 8017 A.1.2
3525 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3526 "020100" // INTEGER length 1 value 0x00 (version)
3527 "02820101" // INTEGER length 0x0101 (modulus) value...
3528 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3529 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3530 "7b06e673a837313d56b1c725150a3fef" // 0x30
3531 "86acbddc41bb759c2854eae32d35841e" // 0x40
3532 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3533 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3534 "312d7bd5921ffaea1347c157406fef71" // 0x70
3535 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3536 "f4645c11f5c1374c3886427411c44979" // 0x90
3537 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3538 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3539 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3540 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3541 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3542 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3543 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3544 "55" // 0x101
3545 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3546 "02820100" // INTEGER length 0x100 (privateExponent) value...
3547 "431447b6251908112b1ee76f99f3711a" // 0x10
3548 "52b6630960046c2de70de188d833f8b8" // 0x20
3549 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3550 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3551 "e710b630a03adc683b5d2c43080e52be" // 0x50
3552 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3553 "822bccff087d63c940ba8a45f670feb2" // 0x70
3554 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3555 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3556 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3557 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3558 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3559 "52659d5a5ba05b663737a8696281865b" // 0xd0
3560 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3561 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3562 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3563 "028181" // INTEGER length 0x81 (prime1) value...
3564 "00de392e18d682c829266cc3454e1d61" // 0x10
3565 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3566 "ff841be5bac82a164c5970007047b8c5" // 0x30
3567 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3568 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3569 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3570 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3571 "9e91346130748a6e3c124f9149d71c74" // 0x80
3572 "35"
3573 "028181" // INTEGER length 0x81 (prime2) value...
3574 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3575 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3576 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3577 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3578 "9ed39a2d934c880440aed8832f984316" // 0x50
3579 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3580 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3581 "b880677c068e1be936e81288815252a8" // 0x80
3582 "a1"
3583 "028180" // INTEGER length 0x80 (exponent1) value...
3584 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3585 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3586 "5a063212a4f105a3764743e53281988a" // 0x30
3587 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3588 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3589 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3590 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3591 "4719d6e2b9439823719cd08bcd031781" // 0x80
3592 "028181" // INTEGER length 0x81 (exponent2) value...
3593 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3594 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3595 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3596 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3597 "1254186af30b22c10582a8a43e34fe94" // 0x50
3598 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3599 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3600 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3601 "61"
3602 "028181" // INTEGER length 0x81 (coefficient) value...
3603 "00c931617c77829dfb1270502be9195c" // 0x10
3604 "8f2830885f57dba869536811e6864236" // 0x20
3605 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3606 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3607 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3608 "959356210723287b0affcc9f727044d4" // 0x60
3609 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3610 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3611 "22"
3612 // } SEQUENCE
3613 // } SEQUENCE ()
3614);
Selene Huang31ab4042020-04-29 04:22:39 -07003615
3616string zero_masking_key =
3617 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3618string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3619
3620class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3621
3622TEST_P(ImportWrappedKeyTest, Success) {
3623 auto wrapping_key_desc = AuthorizationSetBuilder()
3624 .RsaEncryptionKey(2048, 65537)
3625 .Digest(Digest::SHA_2_256)
3626 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003627 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3628 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003629
3630 ASSERT_EQ(ErrorCode::OK,
3631 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3632 AuthorizationSetBuilder()
3633 .Digest(Digest::SHA_2_256)
3634 .Padding(PaddingMode::RSA_OAEP)));
3635
3636 string message = "Hello World!";
3637 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3638 string ciphertext = EncryptMessage(message, params);
3639 string plaintext = DecryptMessage(ciphertext, params);
3640 EXPECT_EQ(message, plaintext);
3641}
3642
David Drysdaled2cc8c22021-04-15 13:29:45 +01003643/*
3644 * ImportWrappedKeyTest.SuccessSidsIgnored
3645 *
3646 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3647 * include Tag:USER_SECURE_ID.
3648 */
3649TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3650 auto wrapping_key_desc = AuthorizationSetBuilder()
3651 .RsaEncryptionKey(2048, 65537)
3652 .Digest(Digest::SHA_2_256)
3653 .Padding(PaddingMode::RSA_OAEP)
3654 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3655 .SetDefaultValidity();
3656
3657 int64_t password_sid = 42;
3658 int64_t biometric_sid = 24;
3659 ASSERT_EQ(ErrorCode::OK,
3660 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3661 AuthorizationSetBuilder()
3662 .Digest(Digest::SHA_2_256)
3663 .Padding(PaddingMode::RSA_OAEP),
3664 password_sid, biometric_sid));
3665
3666 string message = "Hello World!";
3667 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3668 string ciphertext = EncryptMessage(message, params);
3669 string plaintext = DecryptMessage(ciphertext, params);
3670 EXPECT_EQ(message, plaintext);
3671}
3672
Selene Huang31ab4042020-04-29 04:22:39 -07003673TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3674 auto wrapping_key_desc = AuthorizationSetBuilder()
3675 .RsaEncryptionKey(2048, 65537)
3676 .Digest(Digest::SHA_2_256)
3677 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003678 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3679 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003680
3681 ASSERT_EQ(ErrorCode::OK,
3682 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3683 AuthorizationSetBuilder()
3684 .Digest(Digest::SHA_2_256)
3685 .Padding(PaddingMode::RSA_OAEP)));
3686}
3687
3688TEST_P(ImportWrappedKeyTest, WrongMask) {
3689 auto wrapping_key_desc = AuthorizationSetBuilder()
3690 .RsaEncryptionKey(2048, 65537)
3691 .Digest(Digest::SHA_2_256)
3692 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003693 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3694 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003695
3696 ASSERT_EQ(
3697 ErrorCode::VERIFICATION_FAILED,
3698 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3699 AuthorizationSetBuilder()
3700 .Digest(Digest::SHA_2_256)
3701 .Padding(PaddingMode::RSA_OAEP)));
3702}
3703
3704TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3705 auto wrapping_key_desc = AuthorizationSetBuilder()
3706 .RsaEncryptionKey(2048, 65537)
3707 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003708 .Padding(PaddingMode::RSA_OAEP)
3709 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003710
3711 ASSERT_EQ(
3712 ErrorCode::INCOMPATIBLE_PURPOSE,
3713 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3714 AuthorizationSetBuilder()
3715 .Digest(Digest::SHA_2_256)
3716 .Padding(PaddingMode::RSA_OAEP)));
3717}
3718
David Drysdaled2cc8c22021-04-15 13:29:45 +01003719TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3720 auto wrapping_key_desc = AuthorizationSetBuilder()
3721 .RsaEncryptionKey(2048, 65537)
3722 .Digest(Digest::SHA_2_256)
3723 .Padding(PaddingMode::RSA_PSS)
3724 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3725 .SetDefaultValidity();
3726
3727 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3728 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3729 AuthorizationSetBuilder()
3730 .Digest(Digest::SHA_2_256)
3731 .Padding(PaddingMode::RSA_OAEP)));
3732}
3733
3734TEST_P(ImportWrappedKeyTest, WrongDigest) {
3735 auto wrapping_key_desc = AuthorizationSetBuilder()
3736 .RsaEncryptionKey(2048, 65537)
3737 .Digest(Digest::SHA_2_512)
3738 .Padding(PaddingMode::RSA_OAEP)
3739 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3740 .SetDefaultValidity();
3741
3742 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3743 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3744 AuthorizationSetBuilder()
3745 .Digest(Digest::SHA_2_256)
3746 .Padding(PaddingMode::RSA_OAEP)));
3747}
3748
Selene Huang31ab4042020-04-29 04:22:39 -07003749INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3750
3751typedef KeyMintAidlTestBase EncryptionOperationsTest;
3752
3753/*
3754 * EncryptionOperationsTest.RsaNoPaddingSuccess
3755 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003756 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003757 */
3758TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003759 for (uint64_t exponent : {3, 65537}) {
3760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3761 .Authorization(TAG_NO_AUTH_REQUIRED)
3762 .RsaEncryptionKey(2048, exponent)
3763 .Padding(PaddingMode::NONE)
3764 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003765
David Drysdaled2cc8c22021-04-15 13:29:45 +01003766 string message = string(2048 / 8, 'a');
3767 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003768 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003769 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003770
David Drysdale2b6c3512021-05-12 13:52:03 +01003771 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003772 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003773
David Drysdaled2cc8c22021-04-15 13:29:45 +01003774 // Unpadded RSA is deterministic
3775 EXPECT_EQ(ciphertext1, ciphertext2);
3776
3777 CheckedDeleteKey();
3778 }
Selene Huang31ab4042020-04-29 04:22:39 -07003779}
3780
3781/*
3782 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3783 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003784 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003785 */
3786TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3788 .Authorization(TAG_NO_AUTH_REQUIRED)
3789 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003790 .Padding(PaddingMode::NONE)
3791 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003792
3793 string message = "1";
3794 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3795
David Drysdale2b6c3512021-05-12 13:52:03 +01003796 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003797 EXPECT_EQ(2048U / 8, ciphertext.size());
3798
3799 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3800 string plaintext = DecryptMessage(ciphertext, params);
3801
3802 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003803}
3804
3805/*
Selene Huang31ab4042020-04-29 04:22:39 -07003806 * EncryptionOperationsTest.RsaOaepSuccess
3807 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003808 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003809 */
3810TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3811 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3812
3813 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale2b6c3512021-05-12 13:52:03 +01003814 ASSERT_EQ(ErrorCode::OK,
3815 GenerateKey(AuthorizationSetBuilder()
3816 .Authorization(TAG_NO_AUTH_REQUIRED)
3817 .RsaEncryptionKey(key_size, 65537)
3818 .Padding(PaddingMode::RSA_OAEP)
3819 .Digest(digests)
3820 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3821 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003822
3823 string message = "Hello";
3824
3825 for (auto digest : digests) {
David Drysdale2b6c3512021-05-12 13:52:03 +01003826 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3827
3828 auto params = AuthorizationSetBuilder()
3829 .Digest(digest)
3830 .Padding(PaddingMode::RSA_OAEP)
3831 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3832 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003833 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3834 EXPECT_EQ(key_size / 8, ciphertext1.size());
3835
David Drysdale2b6c3512021-05-12 13:52:03 +01003836 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003837 EXPECT_EQ(key_size / 8, ciphertext2.size());
3838
3839 // OAEP randomizes padding so every result should be different (with astronomically high
3840 // probability).
3841 EXPECT_NE(ciphertext1, ciphertext2);
3842
3843 string plaintext1 = DecryptMessage(ciphertext1, params);
3844 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3845 string plaintext2 = DecryptMessage(ciphertext2, params);
3846 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3847
3848 // Decrypting corrupted ciphertext should fail.
3849 size_t offset_to_corrupt = random() % ciphertext1.size();
3850 char corrupt_byte;
3851 do {
3852 corrupt_byte = static_cast<char>(random() % 256);
3853 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3854 ciphertext1[offset_to_corrupt] = corrupt_byte;
3855
3856 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3857 string result;
3858 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3859 EXPECT_EQ(0U, result.size());
3860 }
3861}
3862
3863/*
3864 * EncryptionOperationsTest.RsaOaepInvalidDigest
3865 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003866 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003867 * without a digest.
3868 */
3869TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3870 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3871 .Authorization(TAG_NO_AUTH_REQUIRED)
3872 .RsaEncryptionKey(2048, 65537)
3873 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003874 .Digest(Digest::NONE)
3875 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003876
3877 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003878 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003879}
3880
3881/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003882 * EncryptionOperationsTest.RsaOaepInvalidPadding
3883 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003884 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003885 * with a padding value that is only suitable for signing/verifying.
3886 */
3887TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3889 .Authorization(TAG_NO_AUTH_REQUIRED)
3890 .RsaEncryptionKey(2048, 65537)
3891 .Padding(PaddingMode::RSA_PSS)
3892 .Digest(Digest::NONE)
3893 .SetDefaultValidity()));
3894
3895 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003896 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003897}
3898
3899/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003900 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003901 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003902 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003903 * with a different digest than was used to encrypt.
3904 */
3905TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3906 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3907
3908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3909 .Authorization(TAG_NO_AUTH_REQUIRED)
3910 .RsaEncryptionKey(1024, 65537)
3911 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003912 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3913 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003914 string message = "Hello World!";
David Drysdale2b6c3512021-05-12 13:52:03 +01003915 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003916 message,
3917 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3918
3919 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3920 .Digest(Digest::SHA_2_256)
3921 .Padding(PaddingMode::RSA_OAEP)));
3922 string result;
3923 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3924 EXPECT_EQ(0U, result.size());
3925}
3926
3927/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003928 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3929 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003930 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003931 * digests.
3932 */
3933TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3934 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3935
3936 size_t key_size = 2048; // Need largish key for SHA-512 test.
3937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3938 .OaepMGFDigest(digests)
3939 .Authorization(TAG_NO_AUTH_REQUIRED)
3940 .RsaEncryptionKey(key_size, 65537)
3941 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003942 .Digest(Digest::SHA_2_256)
3943 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003944
3945 string message = "Hello";
3946
3947 for (auto digest : digests) {
3948 auto params = AuthorizationSetBuilder()
3949 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3950 .Digest(Digest::SHA_2_256)
3951 .Padding(PaddingMode::RSA_OAEP);
David Drysdale2b6c3512021-05-12 13:52:03 +01003952 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003953 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3954 EXPECT_EQ(key_size / 8, ciphertext1.size());
3955
David Drysdale2b6c3512021-05-12 13:52:03 +01003956 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003957 EXPECT_EQ(key_size / 8, ciphertext2.size());
3958
3959 // OAEP randomizes padding so every result should be different (with astronomically high
3960 // probability).
3961 EXPECT_NE(ciphertext1, ciphertext2);
3962
3963 string plaintext1 = DecryptMessage(ciphertext1, params);
3964 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3965 string plaintext2 = DecryptMessage(ciphertext2, params);
3966 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3967
3968 // Decrypting corrupted ciphertext should fail.
3969 size_t offset_to_corrupt = random() % ciphertext1.size();
3970 char corrupt_byte;
3971 do {
3972 corrupt_byte = static_cast<char>(random() % 256);
3973 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3974 ciphertext1[offset_to_corrupt] = corrupt_byte;
3975
3976 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3977 string result;
3978 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3979 EXPECT_EQ(0U, result.size());
3980 }
3981}
3982
3983/*
3984 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3985 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003986 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003987 * with incompatible MGF digest.
3988 */
3989TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3990 ASSERT_EQ(ErrorCode::OK,
3991 GenerateKey(AuthorizationSetBuilder()
3992 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3993 .Authorization(TAG_NO_AUTH_REQUIRED)
3994 .RsaEncryptionKey(2048, 65537)
3995 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003996 .Digest(Digest::SHA_2_256)
3997 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003998 string message = "Hello World!";
3999
4000 auto params = AuthorizationSetBuilder()
4001 .Padding(PaddingMode::RSA_OAEP)
4002 .Digest(Digest::SHA_2_256)
4003 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale2b6c3512021-05-12 13:52:03 +01004004 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004005}
4006
4007/*
4008 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4009 *
4010 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4011 * with unsupported MGF digest.
4012 */
4013TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4014 ASSERT_EQ(ErrorCode::OK,
4015 GenerateKey(AuthorizationSetBuilder()
4016 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4017 .Authorization(TAG_NO_AUTH_REQUIRED)
4018 .RsaEncryptionKey(2048, 65537)
4019 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004020 .Digest(Digest::SHA_2_256)
4021 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004022 string message = "Hello World!";
4023
4024 auto params = AuthorizationSetBuilder()
4025 .Padding(PaddingMode::RSA_OAEP)
4026 .Digest(Digest::SHA_2_256)
4027 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01004028 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004029}
4030
4031/*
Selene Huang31ab4042020-04-29 04:22:39 -07004032 * EncryptionOperationsTest.RsaPkcs1Success
4033 *
4034 * Verifies that RSA PKCS encryption/decrypts works.
4035 */
4036TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4038 .Authorization(TAG_NO_AUTH_REQUIRED)
4039 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004040 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4041 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004042
4043 string message = "Hello World!";
4044 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale2b6c3512021-05-12 13:52:03 +01004045 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004046 EXPECT_EQ(2048U / 8, ciphertext1.size());
4047
David Drysdale2b6c3512021-05-12 13:52:03 +01004048 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004049 EXPECT_EQ(2048U / 8, ciphertext2.size());
4050
4051 // PKCS1 v1.5 randomizes padding so every result should be different.
4052 EXPECT_NE(ciphertext1, ciphertext2);
4053
4054 string plaintext = DecryptMessage(ciphertext1, params);
4055 EXPECT_EQ(message, plaintext);
4056
4057 // Decrypting corrupted ciphertext should fail.
4058 size_t offset_to_corrupt = random() % ciphertext1.size();
4059 char corrupt_byte;
4060 do {
4061 corrupt_byte = static_cast<char>(random() % 256);
4062 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4063 ciphertext1[offset_to_corrupt] = corrupt_byte;
4064
4065 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4066 string result;
4067 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4068 EXPECT_EQ(0U, result.size());
4069}
4070
4071/*
Selene Huang31ab4042020-04-29 04:22:39 -07004072 * EncryptionOperationsTest.EcdsaEncrypt
4073 *
4074 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4075 */
4076TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4078 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01004079 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004080 .Digest(Digest::NONE)
4081 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004082 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4083 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4084 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4085}
4086
4087/*
4088 * EncryptionOperationsTest.HmacEncrypt
4089 *
4090 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4091 */
4092TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4094 .Authorization(TAG_NO_AUTH_REQUIRED)
4095 .HmacKey(128)
4096 .Digest(Digest::SHA_2_256)
4097 .Padding(PaddingMode::NONE)
4098 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4099 auto params = AuthorizationSetBuilder()
4100 .Digest(Digest::SHA_2_256)
4101 .Padding(PaddingMode::NONE)
4102 .Authorization(TAG_MAC_LENGTH, 128);
4103 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4104 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4105}
4106
4107/*
4108 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4109 *
4110 * Verifies that AES ECB mode works.
4111 */
4112TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4114 .Authorization(TAG_NO_AUTH_REQUIRED)
4115 .AesEncryptionKey(128)
4116 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4117 .Padding(PaddingMode::NONE)));
4118
4119 ASSERT_GT(key_blob_.size(), 0U);
4120 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4121
4122 // Two-block message.
4123 string message = "12345678901234567890123456789012";
4124 string ciphertext1 = EncryptMessage(message, params);
4125 EXPECT_EQ(message.size(), ciphertext1.size());
4126
4127 string ciphertext2 = EncryptMessage(string(message), params);
4128 EXPECT_EQ(message.size(), ciphertext2.size());
4129
4130 // ECB is deterministic.
4131 EXPECT_EQ(ciphertext1, ciphertext2);
4132
4133 string plaintext = DecryptMessage(ciphertext1, params);
4134 EXPECT_EQ(message, plaintext);
4135}
4136
4137/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004138 * EncryptionOperationsTest.AesEcbUnknownTag
4139 *
4140 * Verifies that AES ECB operations ignore unknown tags.
4141 */
4142TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4143 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4144 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4145 KeyParameter unknown_param;
4146 unknown_param.tag = unknown_tag;
4147
4148 vector<KeyCharacteristics> key_characteristics;
4149 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4150 .Authorization(TAG_NO_AUTH_REQUIRED)
4151 .AesEncryptionKey(128)
4152 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4153 .Padding(PaddingMode::NONE)
4154 .Authorization(unknown_param),
4155 &key_blob_, &key_characteristics));
4156 ASSERT_GT(key_blob_.size(), 0U);
4157
4158 // Unknown tags should not be returned in key characteristics.
4159 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4160 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4161 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4162 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4163
4164 // Encrypt without mentioning the unknown parameter.
4165 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4166 string message = "12345678901234567890123456789012";
4167 string ciphertext = EncryptMessage(message, params);
4168 EXPECT_EQ(message.size(), ciphertext.size());
4169
4170 // Decrypt including the unknown parameter.
4171 auto decrypt_params = AuthorizationSetBuilder()
4172 .BlockMode(BlockMode::ECB)
4173 .Padding(PaddingMode::NONE)
4174 .Authorization(unknown_param);
4175 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4176 EXPECT_EQ(message, plaintext);
4177}
4178
4179/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004180 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004181 *
4182 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4183 */
4184TEST_P(EncryptionOperationsTest, AesWrongMode) {
4185 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4186 .Authorization(TAG_NO_AUTH_REQUIRED)
4187 .AesEncryptionKey(128)
4188 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4189 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004190 ASSERT_GT(key_blob_.size(), 0U);
4191
Selene Huang31ab4042020-04-29 04:22:39 -07004192 EXPECT_EQ(
4193 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4194 Begin(KeyPurpose::ENCRYPT,
4195 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4196}
4197
4198/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004199 * EncryptionOperationsTest.AesWrongPadding
4200 *
4201 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4202 */
4203TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4204 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4205 .Authorization(TAG_NO_AUTH_REQUIRED)
4206 .AesEncryptionKey(128)
4207 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4208 .Padding(PaddingMode::NONE)));
4209 ASSERT_GT(key_blob_.size(), 0U);
4210
4211 EXPECT_EQ(
4212 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4213 Begin(KeyPurpose::ENCRYPT,
4214 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4215}
4216
4217/*
4218 * EncryptionOperationsTest.AesInvalidParams
4219 *
4220 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4221 */
4222TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4224 .Authorization(TAG_NO_AUTH_REQUIRED)
4225 .AesEncryptionKey(128)
4226 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4227 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4228 .Padding(PaddingMode::NONE)
4229 .Padding(PaddingMode::PKCS7)));
4230 ASSERT_GT(key_blob_.size(), 0U);
4231
4232 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4233 .BlockMode(BlockMode::CBC)
4234 .BlockMode(BlockMode::ECB)
4235 .Padding(PaddingMode::NONE));
4236 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4237 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4238
4239 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4240 .BlockMode(BlockMode::ECB)
4241 .Padding(PaddingMode::NONE)
4242 .Padding(PaddingMode::PKCS7));
4243 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4244 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4245}
4246
4247/*
Selene Huang31ab4042020-04-29 04:22:39 -07004248 * EncryptionOperationsTest.AesWrongPurpose
4249 *
4250 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4251 * specified.
4252 */
4253TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4254 auto err = GenerateKey(AuthorizationSetBuilder()
4255 .Authorization(TAG_NO_AUTH_REQUIRED)
4256 .AesKey(128)
4257 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4258 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4259 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4260 .Padding(PaddingMode::NONE));
4261 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4262 ASSERT_GT(key_blob_.size(), 0U);
4263
4264 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4265 .BlockMode(BlockMode::GCM)
4266 .Padding(PaddingMode::NONE)
4267 .Authorization(TAG_MAC_LENGTH, 128));
4268 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4269
4270 CheckedDeleteKey();
4271
4272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4273 .Authorization(TAG_NO_AUTH_REQUIRED)
4274 .AesKey(128)
4275 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4276 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4277 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4278 .Padding(PaddingMode::NONE)));
4279
4280 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4281 .BlockMode(BlockMode::GCM)
4282 .Padding(PaddingMode::NONE)
4283 .Authorization(TAG_MAC_LENGTH, 128));
4284 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4285}
4286
4287/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004288 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004289 *
4290 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4291 * multiple of the block size and no padding is specified.
4292 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004293TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4294 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4296 .Authorization(TAG_NO_AUTH_REQUIRED)
4297 .AesEncryptionKey(128)
4298 .Authorization(TAG_BLOCK_MODE, blockMode)
4299 .Padding(PaddingMode::NONE)));
4300 // Message is slightly shorter than two blocks.
4301 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004302
David Drysdaled2cc8c22021-04-15 13:29:45 +01004303 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4304 AuthorizationSet out_params;
4305 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4306 string ciphertext;
4307 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4308 EXPECT_EQ(0U, ciphertext.size());
4309
4310 CheckedDeleteKey();
4311 }
Selene Huang31ab4042020-04-29 04:22:39 -07004312}
4313
4314/*
4315 * EncryptionOperationsTest.AesEcbPkcs7Padding
4316 *
4317 * Verifies that AES PKCS7 padding works for any message length.
4318 */
4319TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4321 .Authorization(TAG_NO_AUTH_REQUIRED)
4322 .AesEncryptionKey(128)
4323 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4324 .Padding(PaddingMode::PKCS7)));
4325
4326 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4327
4328 // Try various message lengths; all should work.
4329 for (size_t i = 0; i < 32; ++i) {
4330 string message(i, 'a');
4331 string ciphertext = EncryptMessage(message, params);
4332 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4333 string plaintext = DecryptMessage(ciphertext, params);
4334 EXPECT_EQ(message, plaintext);
4335 }
4336}
4337
4338/*
4339 * EncryptionOperationsTest.AesEcbWrongPadding
4340 *
4341 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4342 * specified.
4343 */
4344TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4345 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4346 .Authorization(TAG_NO_AUTH_REQUIRED)
4347 .AesEncryptionKey(128)
4348 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4349 .Padding(PaddingMode::NONE)));
4350
4351 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4352
4353 // Try various message lengths; all should fail
4354 for (size_t i = 0; i < 32; ++i) {
4355 string message(i, 'a');
4356 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4357 }
4358}
4359
4360/*
4361 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4362 *
4363 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4364 */
4365TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4366 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4367 .Authorization(TAG_NO_AUTH_REQUIRED)
4368 .AesEncryptionKey(128)
4369 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4370 .Padding(PaddingMode::PKCS7)));
4371
4372 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4373
4374 string message = "a";
4375 string ciphertext = EncryptMessage(message, params);
4376 EXPECT_EQ(16U, ciphertext.size());
4377 EXPECT_NE(ciphertext, message);
4378 ++ciphertext[ciphertext.size() / 2];
4379
4380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4381 string plaintext;
4382 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4383}
4384
4385vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4386 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004387 EXPECT_TRUE(iv);
4388 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004389}
4390
4391/*
4392 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4393 *
4394 * Verifies that AES CTR mode works.
4395 */
4396TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4398 .Authorization(TAG_NO_AUTH_REQUIRED)
4399 .AesEncryptionKey(128)
4400 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4401 .Padding(PaddingMode::NONE)));
4402
4403 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4404
4405 string message = "123";
4406 AuthorizationSet out_params;
4407 string ciphertext1 = EncryptMessage(message, params, &out_params);
4408 vector<uint8_t> iv1 = CopyIv(out_params);
4409 EXPECT_EQ(16U, iv1.size());
4410
4411 EXPECT_EQ(message.size(), ciphertext1.size());
4412
4413 out_params.Clear();
4414 string ciphertext2 = EncryptMessage(message, params, &out_params);
4415 vector<uint8_t> iv2 = CopyIv(out_params);
4416 EXPECT_EQ(16U, iv2.size());
4417
4418 // IVs should be random, so ciphertexts should differ.
4419 EXPECT_NE(ciphertext1, ciphertext2);
4420
4421 auto params_iv1 =
4422 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4423 auto params_iv2 =
4424 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4425
4426 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4427 EXPECT_EQ(message, plaintext);
4428 plaintext = DecryptMessage(ciphertext2, params_iv2);
4429 EXPECT_EQ(message, plaintext);
4430
4431 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4432 plaintext = DecryptMessage(ciphertext1, params_iv2);
4433 EXPECT_NE(message, plaintext);
4434 plaintext = DecryptMessage(ciphertext2, params_iv1);
4435 EXPECT_NE(message, plaintext);
4436}
4437
4438/*
4439 * EncryptionOperationsTest.AesIncremental
4440 *
4441 * Verifies that AES works, all modes, when provided data in various size increments.
4442 */
4443TEST_P(EncryptionOperationsTest, AesIncremental) {
4444 auto block_modes = {
4445 BlockMode::ECB,
4446 BlockMode::CBC,
4447 BlockMode::CTR,
4448 BlockMode::GCM,
4449 };
4450
4451 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4452 .Authorization(TAG_NO_AUTH_REQUIRED)
4453 .AesEncryptionKey(128)
4454 .BlockMode(block_modes)
4455 .Padding(PaddingMode::NONE)
4456 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4457
4458 for (int increment = 1; increment <= 240; ++increment) {
4459 for (auto block_mode : block_modes) {
4460 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004461 auto params =
4462 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4463 if (block_mode == BlockMode::GCM) {
4464 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4465 }
Selene Huang31ab4042020-04-29 04:22:39 -07004466
4467 AuthorizationSet output_params;
4468 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4469
4470 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004471 string to_send;
4472 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004473 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004474 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004475 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4476 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004477
4478 switch (block_mode) {
4479 case BlockMode::GCM:
4480 EXPECT_EQ(message.size() + 16, ciphertext.size());
4481 break;
4482 case BlockMode::CTR:
4483 EXPECT_EQ(message.size(), ciphertext.size());
4484 break;
4485 case BlockMode::CBC:
4486 case BlockMode::ECB:
4487 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4488 break;
4489 }
4490
4491 auto iv = output_params.GetTagValue(TAG_NONCE);
4492 switch (block_mode) {
4493 case BlockMode::CBC:
4494 case BlockMode::GCM:
4495 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004496 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4497 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4498 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004499 break;
4500
4501 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004502 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004503 break;
4504 }
4505
4506 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4507 << "Decrypt begin() failed for block mode " << block_mode;
4508
4509 string plaintext;
4510 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004511 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004512 }
4513 ErrorCode error = Finish(to_send, &plaintext);
4514 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4515 << " and increment " << increment;
4516 if (error == ErrorCode::OK) {
4517 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4518 << block_mode << " and increment " << increment;
4519 }
4520 }
4521 }
4522}
4523
4524struct AesCtrSp80038aTestVector {
4525 const char* key;
4526 const char* nonce;
4527 const char* plaintext;
4528 const char* ciphertext;
4529};
4530
4531// These test vectors are taken from
4532// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4533static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4534 // AES-128
4535 {
4536 "2b7e151628aed2a6abf7158809cf4f3c",
4537 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4538 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4539 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4540 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4541 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4542 },
4543 // AES-192
4544 {
4545 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4546 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4547 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4548 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4549 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4550 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4551 },
4552 // AES-256
4553 {
4554 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4555 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4556 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4557 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4558 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4559 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4560 },
4561};
4562
4563/*
4564 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4565 *
4566 * Verifies AES CTR implementation against SP800-38A test vectors.
4567 */
4568TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4569 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4570 for (size_t i = 0; i < 3; i++) {
4571 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4572 const string key = hex2str(test.key);
4573 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4574 InvalidSizes.end())
4575 continue;
4576 const string nonce = hex2str(test.nonce);
4577 const string plaintext = hex2str(test.plaintext);
4578 const string ciphertext = hex2str(test.ciphertext);
4579 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4580 }
4581}
4582
4583/*
4584 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4585 *
4586 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4587 */
4588TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4590 .Authorization(TAG_NO_AUTH_REQUIRED)
4591 .AesEncryptionKey(128)
4592 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4593 .Padding(PaddingMode::PKCS7)));
4594 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4595 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4596}
4597
4598/*
4599 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4600 *
4601 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4602 */
4603TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4605 .Authorization(TAG_NO_AUTH_REQUIRED)
4606 .AesEncryptionKey(128)
4607 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4608 .Authorization(TAG_CALLER_NONCE)
4609 .Padding(PaddingMode::NONE)));
4610
4611 auto params = AuthorizationSetBuilder()
4612 .BlockMode(BlockMode::CTR)
4613 .Padding(PaddingMode::NONE)
4614 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4615 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4616
4617 params = AuthorizationSetBuilder()
4618 .BlockMode(BlockMode::CTR)
4619 .Padding(PaddingMode::NONE)
4620 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4621 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4622
4623 params = AuthorizationSetBuilder()
4624 .BlockMode(BlockMode::CTR)
4625 .Padding(PaddingMode::NONE)
4626 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4627 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4628}
4629
4630/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004631 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004632 *
4633 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4634 */
4635TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4636 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4637 .Authorization(TAG_NO_AUTH_REQUIRED)
4638 .AesEncryptionKey(128)
4639 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4640 .Padding(PaddingMode::NONE)));
4641 // Two-block message.
4642 string message = "12345678901234567890123456789012";
4643 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4644 AuthorizationSet out_params;
4645 string ciphertext1 = EncryptMessage(message, params, &out_params);
4646 vector<uint8_t> iv1 = CopyIv(out_params);
4647 EXPECT_EQ(message.size(), ciphertext1.size());
4648
4649 out_params.Clear();
4650
4651 string ciphertext2 = EncryptMessage(message, params, &out_params);
4652 vector<uint8_t> iv2 = CopyIv(out_params);
4653 EXPECT_EQ(message.size(), ciphertext2.size());
4654
4655 // IVs should be random, so ciphertexts should differ.
4656 EXPECT_NE(ciphertext1, ciphertext2);
4657
4658 params.push_back(TAG_NONCE, iv1);
4659 string plaintext = DecryptMessage(ciphertext1, params);
4660 EXPECT_EQ(message, plaintext);
4661}
4662
4663/*
4664 * EncryptionOperationsTest.AesCallerNonce
4665 *
4666 * Verifies that AES caller-provided nonces work correctly.
4667 */
4668TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4670 .Authorization(TAG_NO_AUTH_REQUIRED)
4671 .AesEncryptionKey(128)
4672 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4673 .Authorization(TAG_CALLER_NONCE)
4674 .Padding(PaddingMode::NONE)));
4675
4676 string message = "12345678901234567890123456789012";
4677
4678 // Don't specify nonce, should get a random one.
4679 AuthorizationSetBuilder params =
4680 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4681 AuthorizationSet out_params;
4682 string ciphertext = EncryptMessage(message, params, &out_params);
4683 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004684 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004685
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004686 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004687 string plaintext = DecryptMessage(ciphertext, params);
4688 EXPECT_EQ(message, plaintext);
4689
4690 // Now specify a nonce, should also work.
4691 params = AuthorizationSetBuilder()
4692 .BlockMode(BlockMode::CBC)
4693 .Padding(PaddingMode::NONE)
4694 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4695 out_params.Clear();
4696 ciphertext = EncryptMessage(message, params, &out_params);
4697
4698 // Decrypt with correct nonce.
4699 plaintext = DecryptMessage(ciphertext, params);
4700 EXPECT_EQ(message, plaintext);
4701
4702 // Try with wrong nonce.
4703 params = AuthorizationSetBuilder()
4704 .BlockMode(BlockMode::CBC)
4705 .Padding(PaddingMode::NONE)
4706 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4707 plaintext = DecryptMessage(ciphertext, params);
4708 EXPECT_NE(message, plaintext);
4709}
4710
4711/*
4712 * EncryptionOperationsTest.AesCallerNonceProhibited
4713 *
4714 * Verifies that caller-provided nonces are not permitted when not specified in the key
4715 * authorizations.
4716 */
4717TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4719 .Authorization(TAG_NO_AUTH_REQUIRED)
4720 .AesEncryptionKey(128)
4721 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4722 .Padding(PaddingMode::NONE)));
4723
4724 string message = "12345678901234567890123456789012";
4725
4726 // Don't specify nonce, should get a random one.
4727 AuthorizationSetBuilder params =
4728 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4729 AuthorizationSet out_params;
4730 string ciphertext = EncryptMessage(message, params, &out_params);
4731 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004732 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004733
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004734 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004735 string plaintext = DecryptMessage(ciphertext, params);
4736 EXPECT_EQ(message, plaintext);
4737
4738 // Now specify a nonce, should fail
4739 params = AuthorizationSetBuilder()
4740 .BlockMode(BlockMode::CBC)
4741 .Padding(PaddingMode::NONE)
4742 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4743 out_params.Clear();
4744 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4745}
4746
4747/*
4748 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4749 *
4750 * Verifies that AES GCM mode works.
4751 */
4752TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4754 .Authorization(TAG_NO_AUTH_REQUIRED)
4755 .AesEncryptionKey(128)
4756 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4757 .Padding(PaddingMode::NONE)
4758 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4759
4760 string aad = "foobar";
4761 string message = "123456789012345678901234567890123456";
4762
4763 auto begin_params = AuthorizationSetBuilder()
4764 .BlockMode(BlockMode::GCM)
4765 .Padding(PaddingMode::NONE)
4766 .Authorization(TAG_MAC_LENGTH, 128);
4767
Selene Huang31ab4042020-04-29 04:22:39 -07004768 // Encrypt
4769 AuthorizationSet begin_out_params;
4770 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4771 << "Begin encrypt";
4772 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004773 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4774 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004775 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4776
4777 // Grab nonce
4778 begin_params.push_back(begin_out_params);
4779
4780 // Decrypt.
4781 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004782 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004783 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004784 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004785 EXPECT_EQ(message.length(), plaintext.length());
4786 EXPECT_EQ(message, plaintext);
4787}
4788
4789/*
4790 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4791 *
4792 * Verifies that AES GCM mode works, even when there's a long delay
4793 * between operations.
4794 */
4795TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4797 .Authorization(TAG_NO_AUTH_REQUIRED)
4798 .AesEncryptionKey(128)
4799 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4800 .Padding(PaddingMode::NONE)
4801 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4802
4803 string aad = "foobar";
4804 string message = "123456789012345678901234567890123456";
4805
4806 auto begin_params = AuthorizationSetBuilder()
4807 .BlockMode(BlockMode::GCM)
4808 .Padding(PaddingMode::NONE)
4809 .Authorization(TAG_MAC_LENGTH, 128);
4810
Selene Huang31ab4042020-04-29 04:22:39 -07004811 // Encrypt
4812 AuthorizationSet begin_out_params;
4813 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4814 << "Begin encrypt";
4815 string ciphertext;
4816 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004817 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004818 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004819 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004820
4821 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4822
4823 // Grab nonce
4824 begin_params.push_back(begin_out_params);
4825
4826 // Decrypt.
4827 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4828 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004829 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004830 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004831 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004832 sleep(5);
4833 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4834 EXPECT_EQ(message.length(), plaintext.length());
4835 EXPECT_EQ(message, plaintext);
4836}
4837
4838/*
4839 * EncryptionOperationsTest.AesGcmDifferentNonces
4840 *
4841 * Verifies that encrypting the same data with different nonces produces different outputs.
4842 */
4843TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4845 .Authorization(TAG_NO_AUTH_REQUIRED)
4846 .AesEncryptionKey(128)
4847 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4848 .Padding(PaddingMode::NONE)
4849 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4850 .Authorization(TAG_CALLER_NONCE)));
4851
4852 string aad = "foobar";
4853 string message = "123456789012345678901234567890123456";
4854 string nonce1 = "000000000000";
4855 string nonce2 = "111111111111";
4856 string nonce3 = "222222222222";
4857
4858 string ciphertext1 =
4859 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4860 string ciphertext2 =
4861 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4862 string ciphertext3 =
4863 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4864
4865 ASSERT_NE(ciphertext1, ciphertext2);
4866 ASSERT_NE(ciphertext1, ciphertext3);
4867 ASSERT_NE(ciphertext2, ciphertext3);
4868}
4869
4870/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004871 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4872 *
4873 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4874 */
4875TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4877 .Authorization(TAG_NO_AUTH_REQUIRED)
4878 .AesEncryptionKey(128)
4879 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4880 .Padding(PaddingMode::NONE)
4881 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4882
4883 string aad = "foobar";
4884 string message = "123456789012345678901234567890123456";
4885
4886 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4887 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4888 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4889
4890 ASSERT_NE(ciphertext1, ciphertext2);
4891 ASSERT_NE(ciphertext1, ciphertext3);
4892 ASSERT_NE(ciphertext2, ciphertext3);
4893}
4894
4895/*
Selene Huang31ab4042020-04-29 04:22:39 -07004896 * EncryptionOperationsTest.AesGcmTooShortTag
4897 *
4898 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4899 */
4900TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4901 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4902 .Authorization(TAG_NO_AUTH_REQUIRED)
4903 .AesEncryptionKey(128)
4904 .BlockMode(BlockMode::GCM)
4905 .Padding(PaddingMode::NONE)
4906 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4907 string message = "123456789012345678901234567890123456";
4908 auto params = AuthorizationSetBuilder()
4909 .BlockMode(BlockMode::GCM)
4910 .Padding(PaddingMode::NONE)
4911 .Authorization(TAG_MAC_LENGTH, 96);
4912
4913 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4914}
4915
4916/*
4917 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4918 *
4919 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4920 */
4921TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4923 .Authorization(TAG_NO_AUTH_REQUIRED)
4924 .AesEncryptionKey(128)
4925 .BlockMode(BlockMode::GCM)
4926 .Padding(PaddingMode::NONE)
4927 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4928 string aad = "foobar";
4929 string message = "123456789012345678901234567890123456";
4930 auto params = AuthorizationSetBuilder()
4931 .BlockMode(BlockMode::GCM)
4932 .Padding(PaddingMode::NONE)
4933 .Authorization(TAG_MAC_LENGTH, 128);
4934
Selene Huang31ab4042020-04-29 04:22:39 -07004935 // Encrypt
4936 AuthorizationSet begin_out_params;
4937 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4938 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004939 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004940
4941 AuthorizationSet finish_out_params;
4942 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004943 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4944 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004945
4946 params = AuthorizationSetBuilder()
4947 .Authorizations(begin_out_params)
4948 .BlockMode(BlockMode::GCM)
4949 .Padding(PaddingMode::NONE)
4950 .Authorization(TAG_MAC_LENGTH, 96);
4951
4952 // Decrypt.
4953 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4954}
4955
4956/*
4957 * EncryptionOperationsTest.AesGcmCorruptKey
4958 *
4959 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4960 */
4961TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4962 const uint8_t nonce_bytes[] = {
4963 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4964 };
4965 string nonce = make_string(nonce_bytes);
4966 const uint8_t ciphertext_bytes[] = {
4967 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4968 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4969 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4970 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4971 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4972 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4973 };
4974 string ciphertext = make_string(ciphertext_bytes);
4975
4976 auto params = AuthorizationSetBuilder()
4977 .BlockMode(BlockMode::GCM)
4978 .Padding(PaddingMode::NONE)
4979 .Authorization(TAG_MAC_LENGTH, 128)
4980 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4981
4982 auto import_params = AuthorizationSetBuilder()
4983 .Authorization(TAG_NO_AUTH_REQUIRED)
4984 .AesEncryptionKey(128)
4985 .BlockMode(BlockMode::GCM)
4986 .Padding(PaddingMode::NONE)
4987 .Authorization(TAG_CALLER_NONCE)
4988 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4989
4990 // Import correct key and decrypt
4991 const uint8_t key_bytes[] = {
4992 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4993 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4994 };
4995 string key = make_string(key_bytes);
4996 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4997 string plaintext = DecryptMessage(ciphertext, params);
4998 CheckedDeleteKey();
4999
5000 // Corrupt key and attempt to decrypt
5001 key[0] = 0;
5002 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5003 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5004 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5005 CheckedDeleteKey();
5006}
5007
5008/*
5009 * EncryptionOperationsTest.AesGcmAadNoData
5010 *
5011 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5012 * encrypt.
5013 */
5014TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5015 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5016 .Authorization(TAG_NO_AUTH_REQUIRED)
5017 .AesEncryptionKey(128)
5018 .BlockMode(BlockMode::GCM)
5019 .Padding(PaddingMode::NONE)
5020 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5021
5022 string aad = "1234567890123456";
5023 auto params = AuthorizationSetBuilder()
5024 .BlockMode(BlockMode::GCM)
5025 .Padding(PaddingMode::NONE)
5026 .Authorization(TAG_MAC_LENGTH, 128);
5027
Selene Huang31ab4042020-04-29 04:22:39 -07005028 // Encrypt
5029 AuthorizationSet begin_out_params;
5030 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5031 string ciphertext;
5032 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005033 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5034 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005035 EXPECT_TRUE(finish_out_params.empty());
5036
5037 // Grab nonce
5038 params.push_back(begin_out_params);
5039
5040 // Decrypt.
5041 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005042 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005043 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005044 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005045
5046 EXPECT_TRUE(finish_out_params.empty());
5047
5048 EXPECT_EQ("", plaintext);
5049}
5050
5051/*
5052 * EncryptionOperationsTest.AesGcmMultiPartAad
5053 *
5054 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5055 * chunks.
5056 */
5057TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5058 const size_t tag_bits = 128;
5059 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5060 .Authorization(TAG_NO_AUTH_REQUIRED)
5061 .AesEncryptionKey(128)
5062 .BlockMode(BlockMode::GCM)
5063 .Padding(PaddingMode::NONE)
5064 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5065
5066 string message = "123456789012345678901234567890123456";
5067 auto begin_params = AuthorizationSetBuilder()
5068 .BlockMode(BlockMode::GCM)
5069 .Padding(PaddingMode::NONE)
5070 .Authorization(TAG_MAC_LENGTH, tag_bits);
5071 AuthorizationSet begin_out_params;
5072
Selene Huang31ab4042020-04-29 04:22:39 -07005073 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5074
5075 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005076 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5077 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005078 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005079 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5080 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005081
Selene Huang31ab4042020-04-29 04:22:39 -07005082 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005083 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005084
5085 // Grab nonce.
5086 begin_params.push_back(begin_out_params);
5087
5088 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005089 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005090 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005091 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005092 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005093 EXPECT_EQ(message, plaintext);
5094}
5095
5096/*
5097 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5098 *
5099 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5100 */
5101TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5103 .Authorization(TAG_NO_AUTH_REQUIRED)
5104 .AesEncryptionKey(128)
5105 .BlockMode(BlockMode::GCM)
5106 .Padding(PaddingMode::NONE)
5107 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5108
5109 string message = "123456789012345678901234567890123456";
5110 auto begin_params = AuthorizationSetBuilder()
5111 .BlockMode(BlockMode::GCM)
5112 .Padding(PaddingMode::NONE)
5113 .Authorization(TAG_MAC_LENGTH, 128);
5114 AuthorizationSet begin_out_params;
5115
Selene Huang31ab4042020-04-29 04:22:39 -07005116 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5117
Shawn Willden92d79c02021-02-19 07:31:55 -07005118 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005119 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005120 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5121 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005122
David Drysdaled2cc8c22021-04-15 13:29:45 +01005123 // The failure should have already cancelled the operation.
5124 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5125
Shawn Willden92d79c02021-02-19 07:31:55 -07005126 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005127}
5128
5129/*
5130 * EncryptionOperationsTest.AesGcmBadAad
5131 *
5132 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5133 */
5134TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5136 .Authorization(TAG_NO_AUTH_REQUIRED)
5137 .AesEncryptionKey(128)
5138 .BlockMode(BlockMode::GCM)
5139 .Padding(PaddingMode::NONE)
5140 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5141
5142 string message = "12345678901234567890123456789012";
5143 auto begin_params = AuthorizationSetBuilder()
5144 .BlockMode(BlockMode::GCM)
5145 .Padding(PaddingMode::NONE)
5146 .Authorization(TAG_MAC_LENGTH, 128);
5147
Selene Huang31ab4042020-04-29 04:22:39 -07005148 // Encrypt
5149 AuthorizationSet begin_out_params;
5150 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005151 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005152 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005153 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005154
5155 // Grab nonce
5156 begin_params.push_back(begin_out_params);
5157
Selene Huang31ab4042020-04-29 04:22:39 -07005158 // Decrypt.
5159 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005160 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005161 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005162 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005163}
5164
5165/*
5166 * EncryptionOperationsTest.AesGcmWrongNonce
5167 *
5168 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5169 */
5170TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5171 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5172 .Authorization(TAG_NO_AUTH_REQUIRED)
5173 .AesEncryptionKey(128)
5174 .BlockMode(BlockMode::GCM)
5175 .Padding(PaddingMode::NONE)
5176 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5177
5178 string message = "12345678901234567890123456789012";
5179 auto begin_params = AuthorizationSetBuilder()
5180 .BlockMode(BlockMode::GCM)
5181 .Padding(PaddingMode::NONE)
5182 .Authorization(TAG_MAC_LENGTH, 128);
5183
Selene Huang31ab4042020-04-29 04:22:39 -07005184 // Encrypt
5185 AuthorizationSet begin_out_params;
5186 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005187 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005188 string ciphertext;
5189 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005190 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005191
5192 // Wrong nonce
5193 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5194
5195 // Decrypt.
5196 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005197 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005198 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005199 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005200
5201 // With wrong nonce, should have gotten garbage plaintext (or none).
5202 EXPECT_NE(message, plaintext);
5203}
5204
5205/*
5206 * EncryptionOperationsTest.AesGcmCorruptTag
5207 *
5208 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5209 */
5210TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5211 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5212 .Authorization(TAG_NO_AUTH_REQUIRED)
5213 .AesEncryptionKey(128)
5214 .BlockMode(BlockMode::GCM)
5215 .Padding(PaddingMode::NONE)
5216 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5217
5218 string aad = "1234567890123456";
5219 string message = "123456789012345678901234567890123456";
5220
5221 auto params = AuthorizationSetBuilder()
5222 .BlockMode(BlockMode::GCM)
5223 .Padding(PaddingMode::NONE)
5224 .Authorization(TAG_MAC_LENGTH, 128);
5225
Selene Huang31ab4042020-04-29 04:22:39 -07005226 // Encrypt
5227 AuthorizationSet begin_out_params;
5228 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005229 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005230 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005231 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005232
5233 // Corrupt tag
5234 ++(*ciphertext.rbegin());
5235
5236 // Grab nonce
5237 params.push_back(begin_out_params);
5238
5239 // Decrypt.
5240 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005241 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005242 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005243 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005244}
5245
5246/*
5247 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5248 *
5249 * Verifies that 3DES is basically functional.
5250 */
5251TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5252 auto auths = AuthorizationSetBuilder()
5253 .TripleDesEncryptionKey(168)
5254 .BlockMode(BlockMode::ECB)
5255 .Authorization(TAG_NO_AUTH_REQUIRED)
5256 .Padding(PaddingMode::NONE);
5257
5258 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5259 // Two-block message.
5260 string message = "1234567890123456";
5261 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5262 string ciphertext1 = EncryptMessage(message, inParams);
5263 EXPECT_EQ(message.size(), ciphertext1.size());
5264
5265 string ciphertext2 = EncryptMessage(string(message), inParams);
5266 EXPECT_EQ(message.size(), ciphertext2.size());
5267
5268 // ECB is deterministic.
5269 EXPECT_EQ(ciphertext1, ciphertext2);
5270
5271 string plaintext = DecryptMessage(ciphertext1, inParams);
5272 EXPECT_EQ(message, plaintext);
5273}
5274
5275/*
5276 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5277 *
5278 * Verifies that CBC keys reject ECB usage.
5279 */
5280TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5282 .TripleDesEncryptionKey(168)
5283 .BlockMode(BlockMode::CBC)
5284 .Authorization(TAG_NO_AUTH_REQUIRED)
5285 .Padding(PaddingMode::NONE)));
5286
5287 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5288 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5289}
5290
5291/*
5292 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5293 *
5294 * Tests ECB mode with PKCS#7 padding, various message sizes.
5295 */
5296TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5298 .TripleDesEncryptionKey(168)
5299 .BlockMode(BlockMode::ECB)
5300 .Authorization(TAG_NO_AUTH_REQUIRED)
5301 .Padding(PaddingMode::PKCS7)));
5302
5303 for (size_t i = 0; i < 32; ++i) {
5304 string message(i, 'a');
5305 auto inParams =
5306 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5307 string ciphertext = EncryptMessage(message, inParams);
5308 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5309 string plaintext = DecryptMessage(ciphertext, inParams);
5310 EXPECT_EQ(message, plaintext);
5311 }
5312}
5313
5314/*
5315 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5316 *
5317 * Verifies that keys configured for no padding reject PKCS7 padding
5318 */
5319TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5321 .TripleDesEncryptionKey(168)
5322 .BlockMode(BlockMode::ECB)
5323 .Authorization(TAG_NO_AUTH_REQUIRED)
5324 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005325 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5326 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005327}
5328
5329/*
5330 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5331 *
5332 * Verifies that corrupted padding is detected.
5333 */
5334TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5336 .TripleDesEncryptionKey(168)
5337 .BlockMode(BlockMode::ECB)
5338 .Authorization(TAG_NO_AUTH_REQUIRED)
5339 .Padding(PaddingMode::PKCS7)));
5340
5341 string message = "a";
5342 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5343 EXPECT_EQ(8U, ciphertext.size());
5344 EXPECT_NE(ciphertext, message);
5345 ++ciphertext[ciphertext.size() / 2];
5346
5347 AuthorizationSetBuilder begin_params;
5348 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5349 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5350 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5351 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005352 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005353 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5354}
5355
5356struct TripleDesTestVector {
5357 const char* name;
5358 const KeyPurpose purpose;
5359 const BlockMode block_mode;
5360 const PaddingMode padding_mode;
5361 const char* key;
5362 const char* iv;
5363 const char* input;
5364 const char* output;
5365};
5366
5367// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5368// of the NIST vectors are multiples of the block size.
5369static const TripleDesTestVector kTripleDesTestVectors[] = {
5370 {
5371 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5372 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5373 "", // IV
5374 "329d86bdf1bc5af4", // input
5375 "d946c2756d78633f", // output
5376 },
5377 {
5378 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5379 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5380 "", // IV
5381 "6b1540781b01ce1997adae102dbf3c5b", // input
5382 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5383 },
5384 {
5385 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5386 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5387 "", // IV
5388 "6daad94ce08acfe7", // input
5389 "660e7d32dcc90e79", // output
5390 },
5391 {
5392 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5393 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5394 "", // IV
5395 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5396 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5397 },
5398 {
5399 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5400 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5401 "43f791134c5647ba", // IV
5402 "dcc153cef81d6f24", // input
5403 "92538bd8af18d3ba", // output
5404 },
5405 {
5406 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5407 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5408 "c2e999cb6249023c", // IV
5409 "c689aee38a301bb316da75db36f110b5", // input
5410 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5411 },
5412 {
5413 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5414 PaddingMode::PKCS7,
5415 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5416 "c2e999cb6249023c", // IV
5417 "c689aee38a301bb316da75db36f110b500", // input
5418 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5419 },
5420 {
5421 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5422 PaddingMode::PKCS7,
5423 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5424 "c2e999cb6249023c", // IV
5425 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5426 "c689aee38a301bb316da75db36f110b500", // output
5427 },
5428 {
5429 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5430 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5431 "41746c7e442d3681", // IV
5432 "c53a7b0ec40600fe", // input
5433 "d4f00eb455de1034", // output
5434 },
5435 {
5436 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5437 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5438 "3982bc02c3727d45", // IV
5439 "6006f10adef52991fcc777a1238bbb65", // input
5440 "edae09288e9e3bc05746d872b48e3b29", // output
5441 },
5442};
5443
5444/*
5445 * EncryptionOperationsTest.TripleDesTestVector
5446 *
5447 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5448 */
5449TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5450 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5451 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5452 SCOPED_TRACE(test->name);
5453 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5454 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5455 hex2str(test->output));
5456 }
5457}
5458
5459/*
5460 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5461 *
5462 * Validates CBC mode functionality.
5463 */
5464TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .TripleDesEncryptionKey(168)
5467 .BlockMode(BlockMode::CBC)
5468 .Authorization(TAG_NO_AUTH_REQUIRED)
5469 .Padding(PaddingMode::NONE)));
5470
5471 ASSERT_GT(key_blob_.size(), 0U);
5472
5473 // Two-block message.
5474 string message = "1234567890123456";
5475 vector<uint8_t> iv1;
5476 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5477 EXPECT_EQ(message.size(), ciphertext1.size());
5478
5479 vector<uint8_t> iv2;
5480 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5481 EXPECT_EQ(message.size(), ciphertext2.size());
5482
5483 // IVs should be random, so ciphertexts should differ.
5484 EXPECT_NE(iv1, iv2);
5485 EXPECT_NE(ciphertext1, ciphertext2);
5486
5487 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5488 EXPECT_EQ(message, plaintext);
5489}
5490
5491/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005492 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5493 *
5494 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5495 */
5496TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5498 .TripleDesEncryptionKey(168)
5499 .BlockMode(BlockMode::CBC)
5500 .Authorization(TAG_NO_AUTH_REQUIRED)
5501 .Authorization(TAG_CALLER_NONCE)
5502 .Padding(PaddingMode::NONE)));
5503 auto params = AuthorizationSetBuilder()
5504 .BlockMode(BlockMode::CBC)
5505 .Padding(PaddingMode::NONE)
5506 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5507 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5508}
5509
5510/*
Selene Huang31ab4042020-04-29 04:22:39 -07005511 * EncryptionOperationsTest.TripleDesCallerIv
5512 *
5513 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5514 */
5515TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5517 .TripleDesEncryptionKey(168)
5518 .BlockMode(BlockMode::CBC)
5519 .Authorization(TAG_NO_AUTH_REQUIRED)
5520 .Authorization(TAG_CALLER_NONCE)
5521 .Padding(PaddingMode::NONE)));
5522 string message = "1234567890123456";
5523 vector<uint8_t> iv;
5524 // Don't specify IV, should get a random one.
5525 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5526 EXPECT_EQ(message.size(), ciphertext1.size());
5527 EXPECT_EQ(8U, iv.size());
5528
5529 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5530 EXPECT_EQ(message, plaintext);
5531
5532 // Now specify an IV, should also work.
5533 iv = AidlBuf("abcdefgh");
5534 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5535
5536 // Decrypt with correct IV.
5537 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5538 EXPECT_EQ(message, plaintext);
5539
5540 // Now try with wrong IV.
5541 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5542 EXPECT_NE(message, plaintext);
5543}
5544
5545/*
5546 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5547 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005548 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005549 */
5550TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5552 .TripleDesEncryptionKey(168)
5553 .BlockMode(BlockMode::CBC)
5554 .Authorization(TAG_NO_AUTH_REQUIRED)
5555 .Padding(PaddingMode::NONE)));
5556
5557 string message = "12345678901234567890123456789012";
5558 vector<uint8_t> iv;
5559 // Don't specify nonce, should get a random one.
5560 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5561 EXPECT_EQ(message.size(), ciphertext1.size());
5562 EXPECT_EQ(8U, iv.size());
5563
5564 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5565 EXPECT_EQ(message, plaintext);
5566
5567 // Now specify a nonce, should fail.
5568 auto input_params = AuthorizationSetBuilder()
5569 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5570 .BlockMode(BlockMode::CBC)
5571 .Padding(PaddingMode::NONE);
5572 AuthorizationSet output_params;
5573 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5574 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5575}
5576
5577/*
5578 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5579 *
5580 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5581 */
5582TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5584 .TripleDesEncryptionKey(168)
5585 .BlockMode(BlockMode::ECB)
5586 .Authorization(TAG_NO_AUTH_REQUIRED)
5587 .Padding(PaddingMode::NONE)));
5588 // Two-block message.
5589 string message = "1234567890123456";
5590 auto begin_params =
5591 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5592 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5593}
5594
5595/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005596 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005597 *
5598 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5599 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005600TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5601 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5603 .TripleDesEncryptionKey(168)
5604 .BlockMode(blockMode)
5605 .Authorization(TAG_NO_AUTH_REQUIRED)
5606 .Padding(PaddingMode::NONE)));
5607 // Message is slightly shorter than two blocks.
5608 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005609
David Drysdaled2cc8c22021-04-15 13:29:45 +01005610 auto begin_params =
5611 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5612 AuthorizationSet output_params;
5613 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5614 string ciphertext;
5615 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5616
5617 CheckedDeleteKey();
5618 }
Selene Huang31ab4042020-04-29 04:22:39 -07005619}
5620
5621/*
5622 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5623 *
5624 * Verifies that PKCS7 padding works correctly in CBC mode.
5625 */
5626TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5627 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5628 .TripleDesEncryptionKey(168)
5629 .BlockMode(BlockMode::CBC)
5630 .Authorization(TAG_NO_AUTH_REQUIRED)
5631 .Padding(PaddingMode::PKCS7)));
5632
5633 // Try various message lengths; all should work.
5634 for (size_t i = 0; i < 32; ++i) {
5635 string message(i, 'a');
5636 vector<uint8_t> iv;
5637 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5638 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5639 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5640 EXPECT_EQ(message, plaintext);
5641 }
5642}
5643
5644/*
5645 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5646 *
5647 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5648 */
5649TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5651 .TripleDesEncryptionKey(168)
5652 .BlockMode(BlockMode::CBC)
5653 .Authorization(TAG_NO_AUTH_REQUIRED)
5654 .Padding(PaddingMode::NONE)));
5655
5656 // Try various message lengths; all should fail.
5657 for (size_t i = 0; i < 32; ++i) {
5658 auto begin_params =
5659 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5660 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5661 }
5662}
5663
5664/*
5665 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5666 *
5667 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5668 */
5669TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5671 .TripleDesEncryptionKey(168)
5672 .BlockMode(BlockMode::CBC)
5673 .Authorization(TAG_NO_AUTH_REQUIRED)
5674 .Padding(PaddingMode::PKCS7)));
5675
5676 string message = "a";
5677 vector<uint8_t> iv;
5678 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5679 EXPECT_EQ(8U, ciphertext.size());
5680 EXPECT_NE(ciphertext, message);
5681 ++ciphertext[ciphertext.size() / 2];
5682
5683 auto begin_params = AuthorizationSetBuilder()
5684 .BlockMode(BlockMode::CBC)
5685 .Padding(PaddingMode::PKCS7)
5686 .Authorization(TAG_NONCE, iv);
5687 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5688 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005689 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005690 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5691}
5692
5693/*
5694 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5695 *
5696 * Verifies that 3DES CBC works with many different input sizes.
5697 */
5698TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5700 .TripleDesEncryptionKey(168)
5701 .BlockMode(BlockMode::CBC)
5702 .Authorization(TAG_NO_AUTH_REQUIRED)
5703 .Padding(PaddingMode::NONE)));
5704
5705 int increment = 7;
5706 string message(240, 'a');
5707 AuthorizationSet input_params =
5708 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5709 AuthorizationSet output_params;
5710 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5711
5712 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005713 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005714 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005715 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5716 EXPECT_EQ(message.size(), ciphertext.size());
5717
5718 // Move TAG_NONCE into input_params
5719 input_params = output_params;
5720 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5721 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5722 output_params.Clear();
5723
5724 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5725 string plaintext;
5726 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005727 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005728 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5729 EXPECT_EQ(ciphertext.size(), plaintext.size());
5730 EXPECT_EQ(message, plaintext);
5731}
5732
5733INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5734
5735typedef KeyMintAidlTestBase MaxOperationsTest;
5736
5737/*
5738 * MaxOperationsTest.TestLimitAes
5739 *
5740 * Verifies that the max uses per boot tag works correctly with AES keys.
5741 */
5742TEST_P(MaxOperationsTest, TestLimitAes) {
5743 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5744
5745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5746 .Authorization(TAG_NO_AUTH_REQUIRED)
5747 .AesEncryptionKey(128)
5748 .EcbMode()
5749 .Padding(PaddingMode::NONE)
5750 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5751
5752 string message = "1234567890123456";
5753
5754 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5755
5756 EncryptMessage(message, params);
5757 EncryptMessage(message, params);
5758 EncryptMessage(message, params);
5759
5760 // Fourth time should fail.
5761 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5762}
5763
5764/*
Qi Wud22ec842020-11-26 13:27:53 +08005765 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005766 *
5767 * Verifies that the max uses per boot tag works correctly with RSA keys.
5768 */
5769TEST_P(MaxOperationsTest, TestLimitRsa) {
5770 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5771
5772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5773 .Authorization(TAG_NO_AUTH_REQUIRED)
5774 .RsaSigningKey(1024, 65537)
5775 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005776 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5777 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005778
5779 string message = "1234567890123456";
5780
5781 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5782
5783 SignMessage(message, params);
5784 SignMessage(message, params);
5785 SignMessage(message, params);
5786
5787 // Fourth time should fail.
5788 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5789}
5790
5791INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5792
Qi Wud22ec842020-11-26 13:27:53 +08005793typedef KeyMintAidlTestBase UsageCountLimitTest;
5794
5795/*
Qi Wubeefae42021-01-28 23:16:37 +08005796 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005797 *
Qi Wubeefae42021-01-28 23:16:37 +08005798 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005799 */
Qi Wubeefae42021-01-28 23:16:37 +08005800TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005801 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5802
5803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5804 .Authorization(TAG_NO_AUTH_REQUIRED)
5805 .AesEncryptionKey(128)
5806 .EcbMode()
5807 .Padding(PaddingMode::NONE)
5808 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5809
5810 // Check the usage count limit tag appears in the authorizations.
5811 AuthorizationSet auths;
5812 for (auto& entry : key_characteristics_) {
5813 auths.push_back(AuthorizationSet(entry.authorizations));
5814 }
5815 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5816 << "key usage count limit " << 1U << " missing";
5817
5818 string message = "1234567890123456";
5819 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5820
Qi Wubeefae42021-01-28 23:16:37 +08005821 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5822 AuthorizationSet keystore_auths =
5823 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5824
Qi Wud22ec842020-11-26 13:27:53 +08005825 // First usage of AES key should work.
5826 EncryptMessage(message, params);
5827
Qi Wud22ec842020-11-26 13:27:53 +08005828 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5829 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5830 // must be invalidated from secure storage (such as RPMB partition).
5831 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5832 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005833 // Usage count limit tag is enforced by keystore, keymint does nothing.
5834 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005835 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5836 }
5837}
5838
5839/*
Qi Wubeefae42021-01-28 23:16:37 +08005840 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005841 *
Qi Wubeefae42021-01-28 23:16:37 +08005842 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005843 */
Qi Wubeefae42021-01-28 23:16:37 +08005844TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5845 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5846
5847 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5848 .Authorization(TAG_NO_AUTH_REQUIRED)
5849 .AesEncryptionKey(128)
5850 .EcbMode()
5851 .Padding(PaddingMode::NONE)
5852 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5853
5854 // Check the usage count limit tag appears in the authorizations.
5855 AuthorizationSet auths;
5856 for (auto& entry : key_characteristics_) {
5857 auths.push_back(AuthorizationSet(entry.authorizations));
5858 }
5859 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5860 << "key usage count limit " << 3U << " missing";
5861
5862 string message = "1234567890123456";
5863 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5864
5865 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5866 AuthorizationSet keystore_auths =
5867 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5868
5869 EncryptMessage(message, params);
5870 EncryptMessage(message, params);
5871 EncryptMessage(message, params);
5872
5873 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5874 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5875 // must be invalidated from secure storage (such as RPMB partition).
5876 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5877 } else {
5878 // Usage count limit tag is enforced by keystore, keymint does nothing.
5879 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5880 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5881 }
5882}
5883
5884/*
5885 * UsageCountLimitTest.TestSingleUseRsa
5886 *
5887 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5888 */
5889TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005890 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5891
5892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5893 .Authorization(TAG_NO_AUTH_REQUIRED)
5894 .RsaSigningKey(1024, 65537)
5895 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005896 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5897 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005898
5899 // Check the usage count limit tag appears in the authorizations.
5900 AuthorizationSet auths;
5901 for (auto& entry : key_characteristics_) {
5902 auths.push_back(AuthorizationSet(entry.authorizations));
5903 }
5904 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5905 << "key usage count limit " << 1U << " missing";
5906
5907 string message = "1234567890123456";
5908 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5909
Qi Wubeefae42021-01-28 23:16:37 +08005910 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5911 AuthorizationSet keystore_auths =
5912 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5913
Qi Wud22ec842020-11-26 13:27:53 +08005914 // First usage of RSA key should work.
5915 SignMessage(message, params);
5916
Qi Wud22ec842020-11-26 13:27:53 +08005917 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5918 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5919 // must be invalidated from secure storage (such as RPMB partition).
5920 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5921 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005922 // Usage count limit tag is enforced by keystore, keymint does nothing.
5923 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5924 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5925 }
5926}
5927
5928/*
5929 * UsageCountLimitTest.TestLimitUseRsa
5930 *
5931 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5932 */
5933TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5934 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5935
5936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5937 .Authorization(TAG_NO_AUTH_REQUIRED)
5938 .RsaSigningKey(1024, 65537)
5939 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005940 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5941 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005942
5943 // Check the usage count limit tag appears in the authorizations.
5944 AuthorizationSet auths;
5945 for (auto& entry : key_characteristics_) {
5946 auths.push_back(AuthorizationSet(entry.authorizations));
5947 }
5948 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5949 << "key usage count limit " << 3U << " missing";
5950
5951 string message = "1234567890123456";
5952 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5953
5954 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5955 AuthorizationSet keystore_auths =
5956 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5957
5958 SignMessage(message, params);
5959 SignMessage(message, params);
5960 SignMessage(message, params);
5961
5962 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5963 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5964 // must be invalidated from secure storage (such as RPMB partition).
5965 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5966 } else {
5967 // Usage count limit tag is enforced by keystore, keymint does nothing.
5968 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005969 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5970 }
5971}
5972
Qi Wu8e727f72021-02-11 02:49:33 +08005973/*
5974 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5975 *
5976 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5977 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5978 * in hardware.
5979 */
5980TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5981 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5982
5983 auto error = GenerateKey(AuthorizationSetBuilder()
5984 .RsaSigningKey(2048, 65537)
5985 .Digest(Digest::NONE)
5986 .Padding(PaddingMode::NONE)
5987 .Authorization(TAG_NO_AUTH_REQUIRED)
5988 .Authorization(TAG_ROLLBACK_RESISTANCE)
5989 .SetDefaultValidity());
5990 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5991
5992 if (error == ErrorCode::OK) {
5993 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5994 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5995 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5996 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5997
5998 // The KeyMint should also enforce single use key in hardware when it supports rollback
5999 // resistance.
6000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6001 .Authorization(TAG_NO_AUTH_REQUIRED)
6002 .RsaSigningKey(1024, 65537)
6003 .NoDigestOrPadding()
6004 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6005 .SetDefaultValidity()));
6006
6007 // Check the usage count limit tag appears in the hardware authorizations.
6008 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6009 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6010 << "key usage count limit " << 1U << " missing";
6011
6012 string message = "1234567890123456";
6013 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6014
6015 // First usage of RSA key should work.
6016 SignMessage(message, params);
6017
6018 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6019 // must be invalidated from secure storage (such as RPMB partition).
6020 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6021 }
6022}
6023
Qi Wud22ec842020-11-26 13:27:53 +08006024INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6025
David Drysdale7de9feb2021-03-05 14:56:19 +00006026typedef KeyMintAidlTestBase GetHardwareInfoTest;
6027
6028TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6029 // Retrieving hardware info should give the same result each time.
6030 KeyMintHardwareInfo info;
6031 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6032 KeyMintHardwareInfo info2;
6033 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6034 EXPECT_EQ(info, info2);
6035}
6036
6037INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6038
Selene Huang31ab4042020-04-29 04:22:39 -07006039typedef KeyMintAidlTestBase AddEntropyTest;
6040
6041/*
6042 * AddEntropyTest.AddEntropy
6043 *
6044 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6045 * is actually added.
6046 */
6047TEST_P(AddEntropyTest, AddEntropy) {
6048 string data = "foo";
6049 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6050}
6051
6052/*
6053 * AddEntropyTest.AddEmptyEntropy
6054 *
6055 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6056 */
6057TEST_P(AddEntropyTest, AddEmptyEntropy) {
6058 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6059}
6060
6061/*
6062 * AddEntropyTest.AddLargeEntropy
6063 *
6064 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6065 */
6066TEST_P(AddEntropyTest, AddLargeEntropy) {
6067 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6068}
6069
David Drysdalebb3d85e2021-04-13 11:15:51 +01006070/*
6071 * AddEntropyTest.AddTooLargeEntropy
6072 *
6073 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6074 */
6075TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6076 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6077 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6078}
6079
Selene Huang31ab4042020-04-29 04:22:39 -07006080INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6081
Selene Huang31ab4042020-04-29 04:22:39 -07006082typedef KeyMintAidlTestBase KeyDeletionTest;
6083
6084/**
6085 * KeyDeletionTest.DeleteKey
6086 *
6087 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6088 * valid key blob.
6089 */
6090TEST_P(KeyDeletionTest, DeleteKey) {
6091 auto error = GenerateKey(AuthorizationSetBuilder()
6092 .RsaSigningKey(2048, 65537)
6093 .Digest(Digest::NONE)
6094 .Padding(PaddingMode::NONE)
6095 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006096 .Authorization(TAG_ROLLBACK_RESISTANCE)
6097 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006098 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6099
6100 // Delete must work if rollback protection is implemented
6101 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006102 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006103 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6104
6105 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6106
6107 string message = "12345678901234567890123456789012";
6108 AuthorizationSet begin_out_params;
6109 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6110 Begin(KeyPurpose::SIGN, key_blob_,
6111 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6112 &begin_out_params));
6113 AbortIfNeeded();
6114 key_blob_ = AidlBuf();
6115 }
6116}
6117
6118/**
6119 * KeyDeletionTest.DeleteInvalidKey
6120 *
6121 * This test checks that the HAL excepts invalid key blobs..
6122 */
6123TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6124 // Generate key just to check if rollback protection is implemented
6125 auto error = GenerateKey(AuthorizationSetBuilder()
6126 .RsaSigningKey(2048, 65537)
6127 .Digest(Digest::NONE)
6128 .Padding(PaddingMode::NONE)
6129 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006130 .Authorization(TAG_ROLLBACK_RESISTANCE)
6131 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006132 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6133
6134 // Delete must work if rollback protection is implemented
6135 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006136 AuthorizationSet enforced(SecLevelAuthorizations());
6137 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006138
6139 // Delete the key we don't care about the result at this point.
6140 DeleteKey();
6141
6142 // Now create an invalid key blob and delete it.
6143 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6144
6145 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6146 }
6147}
6148
6149/**
6150 * KeyDeletionTest.DeleteAllKeys
6151 *
6152 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6153 *
6154 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6155 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6156 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6157 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6158 * credentials stored in Keystore/Keymint.
6159 */
6160TEST_P(KeyDeletionTest, DeleteAllKeys) {
6161 if (!arm_deleteAllKeys) return;
6162 auto error = GenerateKey(AuthorizationSetBuilder()
6163 .RsaSigningKey(2048, 65537)
6164 .Digest(Digest::NONE)
6165 .Padding(PaddingMode::NONE)
6166 .Authorization(TAG_NO_AUTH_REQUIRED)
6167 .Authorization(TAG_ROLLBACK_RESISTANCE));
6168 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6169
6170 // Delete must work if rollback protection is implemented
6171 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006172 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006173 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6174
6175 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6176
6177 string message = "12345678901234567890123456789012";
6178 AuthorizationSet begin_out_params;
6179
6180 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6181 Begin(KeyPurpose::SIGN, key_blob_,
6182 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6183 &begin_out_params));
6184 AbortIfNeeded();
6185 key_blob_ = AidlBuf();
6186 }
6187}
6188
6189INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6190
David Drysdaled2cc8c22021-04-15 13:29:45 +01006191typedef KeyMintAidlTestBase KeyUpgradeTest;
6192
6193/**
6194 * KeyUpgradeTest.UpgradeInvalidKey
6195 *
6196 * This test checks that the HAL excepts invalid key blobs..
6197 */
6198TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6199 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6200
6201 std::vector<uint8_t> new_blob;
6202 Status result = keymint_->upgradeKey(key_blob,
6203 AuthorizationSetBuilder()
6204 .Authorization(TAG_APPLICATION_ID, "clientid")
6205 .Authorization(TAG_APPLICATION_DATA, "appdata")
6206 .vector_data(),
6207 &new_blob);
6208 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6209}
6210
6211INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6212
Selene Huang31ab4042020-04-29 04:22:39 -07006213using UpgradeKeyTest = KeyMintAidlTestBase;
6214
6215/*
6216 * UpgradeKeyTest.UpgradeKey
6217 *
6218 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6219 */
6220TEST_P(UpgradeKeyTest, UpgradeKey) {
6221 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6222 .AesEncryptionKey(128)
6223 .Padding(PaddingMode::NONE)
6224 .Authorization(TAG_NO_AUTH_REQUIRED)));
6225
6226 auto result = UpgradeKey(key_blob_);
6227
6228 // Key doesn't need upgrading. Should get okay, but no new key blob.
6229 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6230}
6231
6232INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6233
6234using ClearOperationsTest = KeyMintAidlTestBase;
6235
6236/*
6237 * ClearSlotsTest.TooManyOperations
6238 *
6239 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6240 * operations are started without being finished or aborted. Also verifies
6241 * that aborting the operations clears the operations.
6242 *
6243 */
6244TEST_P(ClearOperationsTest, TooManyOperations) {
6245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6246 .Authorization(TAG_NO_AUTH_REQUIRED)
6247 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006248 .Padding(PaddingMode::NONE)
6249 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006250
6251 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6252 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006253 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006254 AuthorizationSet out_params;
6255 ErrorCode result;
6256 size_t i;
6257
6258 for (i = 0; i < max_operations; i++) {
6259 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6260 if (ErrorCode::OK != result) {
6261 break;
6262 }
6263 }
6264 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6265 // Try again just in case there's a weird overflow bug
6266 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6267 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6268 for (size_t j = 0; j < i; j++) {
6269 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6270 << "Aboort failed for i = " << j << std::endl;
6271 }
6272 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6273 AbortIfNeeded();
6274}
6275
6276INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6277
6278typedef KeyMintAidlTestBase TransportLimitTest;
6279
6280/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006281 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006282 *
6283 * Verifies that passing input data to finish succeeds as expected.
6284 */
6285TEST_P(TransportLimitTest, LargeFinishInput) {
6286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6287 .Authorization(TAG_NO_AUTH_REQUIRED)
6288 .AesEncryptionKey(128)
6289 .BlockMode(BlockMode::ECB)
6290 .Padding(PaddingMode::NONE)));
6291
6292 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6293 auto cipher_params =
6294 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6295
6296 AuthorizationSet out_params;
6297 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6298
6299 string plain_message = std::string(1 << msg_size, 'x');
6300 string encrypted_message;
6301 auto rc = Finish(plain_message, &encrypted_message);
6302
6303 EXPECT_EQ(ErrorCode::OK, rc);
6304 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6305 << "Encrypt finish returned OK, but did not consume all of the given input";
6306 cipher_params.push_back(out_params);
6307
6308 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6309
6310 string decrypted_message;
6311 rc = Finish(encrypted_message, &decrypted_message);
6312 EXPECT_EQ(ErrorCode::OK, rc);
6313 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6314 << "Decrypt finish returned OK, did not consume all of the given input";
6315 }
6316}
6317
6318INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6319
David Zeuthene0c40892021-01-08 12:54:11 -05006320typedef KeyMintAidlTestBase KeyAgreementTest;
6321
6322int CurveToOpenSslCurveName(EcCurve curve) {
6323 switch (curve) {
6324 case EcCurve::P_224:
6325 return NID_secp224r1;
6326 case EcCurve::P_256:
6327 return NID_X9_62_prime256v1;
6328 case EcCurve::P_384:
6329 return NID_secp384r1;
6330 case EcCurve::P_521:
6331 return NID_secp521r1;
6332 }
6333}
6334
6335/*
6336 * KeyAgreementTest.Ecdh
6337 *
6338 * Verifies that ECDH works for all curves
6339 */
6340TEST_P(KeyAgreementTest, Ecdh) {
6341 // Because it's possible to use this API with keys on different curves, we
6342 // check all N^2 combinations where N is the number of supported
6343 // curves.
6344 //
6345 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6346 // lot more curves we can be smart about things and just pick |otherCurve| so
6347 // it's not |curve| and that way we end up with only 2*N runs
6348 //
6349 for (auto curve : ValidCurves()) {
6350 for (auto localCurve : ValidCurves()) {
6351 // Generate EC key locally (with access to private key material)
6352 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6353 int curveName = CurveToOpenSslCurveName(localCurve);
6354 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6355 ASSERT_NE(group, nullptr);
6356 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6357 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6358 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6359 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6360
6361 // Get encoded form of the public part of the locally generated key...
6362 unsigned char* p = nullptr;
6363 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6364 ASSERT_GT(encodedPublicKeySize, 0);
6365 vector<uint8_t> encodedPublicKey(
6366 reinterpret_cast<const uint8_t*>(p),
6367 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6368 OPENSSL_free(p);
6369
6370 // Generate EC key in KeyMint (only access to public key material)
6371 vector<uint8_t> challenge = {0x41, 0x42};
6372 EXPECT_EQ(
6373 ErrorCode::OK,
6374 GenerateKey(AuthorizationSetBuilder()
6375 .Authorization(TAG_NO_AUTH_REQUIRED)
6376 .Authorization(TAG_EC_CURVE, curve)
6377 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6378 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6379 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006380 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6381 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006382 << "Failed to generate key";
6383 ASSERT_GT(cert_chain_.size(), 0);
6384 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6385 ASSERT_NE(kmKeyCert, nullptr);
6386 // Check that keyAgreement (bit 4) is set in KeyUsage
6387 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6388 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6389 ASSERT_NE(kmPkey, nullptr);
6390 if (dump_Attestations) {
6391 for (size_t n = 0; n < cert_chain_.size(); n++) {
6392 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6393 }
6394 }
6395
6396 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6397 if (curve != localCurve) {
6398 // If the keys are using different curves KeyMint should fail with
6399 // ErrorCode:INVALID_ARGUMENT. Check that.
6400 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6401 string ZabFromKeyMintStr;
6402 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6403 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6404 &ZabFromKeyMintStr));
6405
6406 } else {
6407 // Otherwise if the keys are using the same curve, it should work.
6408 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6409 string ZabFromKeyMintStr;
6410 EXPECT_EQ(ErrorCode::OK,
6411 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6412 &ZabFromKeyMintStr));
6413 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6414
6415 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6416 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6417 ASSERT_NE(ctx, nullptr);
6418 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6419 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6420 size_t ZabFromTestLen = 0;
6421 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6422 vector<uint8_t> ZabFromTest;
6423 ZabFromTest.resize(ZabFromTestLen);
6424 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6425
6426 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6427 }
6428
6429 CheckedDeleteKey();
6430 }
6431 }
6432}
6433
6434INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6435
David Drysdaled2cc8c22021-04-15 13:29:45 +01006436using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6437
6438// This is a problematic test, as it can render the device under test permanently unusable.
6439// Re-enable and run at your own risk.
6440TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6441 auto result = DestroyAttestationIds();
6442 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6443}
6444
6445INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6446
Shawn Willdend659c7c2021-02-19 14:51:51 -07006447using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006448
David Drysdale216d9922021-05-18 11:43:31 +01006449/*
6450 * EarlyBootKeyTest.CreateEarlyBootKeys
6451 *
6452 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6453 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006454TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdale216d9922021-05-18 11:43:31 +01006455 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006456 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6457 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6458
David Drysdaleeaab0f22021-05-27 12:00:53 +01006459 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6460 ASSERT_GT(keyData.blob.size(), 0U);
6461 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6462 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6463 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006464 CheckedDeleteKey(&aesKeyData.blob);
6465 CheckedDeleteKey(&hmacKeyData.blob);
6466 CheckedDeleteKey(&rsaKeyData.blob);
6467 CheckedDeleteKey(&ecdsaKeyData.blob);
6468}
6469
David Drysdale216d9922021-05-18 11:43:31 +01006470/*
David Drysdaleeaab0f22021-05-27 12:00:53 +01006471 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6472 *
6473 * Verifies that creating an early boot key with attestation succeeds.
6474 */
6475TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6476 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6477 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6478 builder->AttestationChallenge("challenge");
6479 builder->AttestationApplicationId("app_id");
6480 });
6481
6482 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6483 ASSERT_GT(keyData.blob.size(), 0U);
6484 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6485 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6486 }
6487 CheckedDeleteKey(&aesKeyData.blob);
6488 CheckedDeleteKey(&hmacKeyData.blob);
6489 CheckedDeleteKey(&rsaKeyData.blob);
6490 CheckedDeleteKey(&ecdsaKeyData.blob);
6491}
6492
6493/*
6494 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdale216d9922021-05-18 11:43:31 +01006495 *
6496 * Verifies that using early boot keys at a later stage fails.
6497 */
6498TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6500 .Authorization(TAG_NO_AUTH_REQUIRED)
6501 .Authorization(TAG_EARLY_BOOT_ONLY)
6502 .HmacKey(128)
6503 .Digest(Digest::SHA_2_256)
6504 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6505 AuthorizationSet output_params;
6506 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6507 AuthorizationSetBuilder()
6508 .Digest(Digest::SHA_2_256)
6509 .Authorization(TAG_MAC_LENGTH, 256),
6510 &output_params));
6511}
6512
6513/*
6514 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6515 *
6516 * Verifies that importing early boot keys fails.
6517 */
6518TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6519 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6520 .Authorization(TAG_NO_AUTH_REQUIRED)
6521 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdale308916b2021-06-08 15:46:11 +01006522 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale216d9922021-05-18 11:43:31 +01006523 .Digest(Digest::SHA_2_256)
6524 .SetDefaultValidity(),
6525 KeyFormat::PKCS8, ec_256_key));
6526}
6527
David Drysdaled2cc8c22021-04-15 13:29:45 +01006528// 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 +00006529// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6530// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6531// early boot, so you'll have to reboot between runs.
6532TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6533 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6534 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6535 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6536 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6537 EXPECT_TRUE(
6538 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6539 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6540 EXPECT_TRUE(
6541 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6542
6543 // Should be able to use keys, since early boot has not ended
6544 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6545 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6546 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6547 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6548
6549 // End early boot
6550 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6551 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6552
6553 // Should not be able to use already-created keys.
6554 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6555 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6556 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6557 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6558
6559 CheckedDeleteKey(&aesKeyData.blob);
6560 CheckedDeleteKey(&hmacKeyData.blob);
6561 CheckedDeleteKey(&rsaKeyData.blob);
6562 CheckedDeleteKey(&ecdsaKeyData.blob);
6563
6564 // Should not be able to create new keys
6565 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6566 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6567
6568 CheckedDeleteKey(&aesKeyData.blob);
6569 CheckedDeleteKey(&hmacKeyData.blob);
6570 CheckedDeleteKey(&rsaKeyData.blob);
6571 CheckedDeleteKey(&ecdsaKeyData.blob);
6572}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006573
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006574INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6575
Shawn Willdend659c7c2021-02-19 14:51:51 -07006576using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006577
6578// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6579// between runs... and on most test devices there are no enrolled credentials so it can't be
6580// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6581// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6582// a manual test process, which includes unlocking between runs, which is why it's included here.
6583// Well, that and the fact that it's the only test we can do without also making calls into the
6584// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6585// implications might be, so that may or may not be a solution.
6586TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6587 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6588 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6589
6590 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6591 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6592 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6593 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6594
6595 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006596 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006597 ASSERT_EQ(ErrorCode::OK, rc);
6598 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6599 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6600 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6601 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6602
6603 CheckedDeleteKey(&aesKeyData.blob);
6604 CheckedDeleteKey(&hmacKeyData.blob);
6605 CheckedDeleteKey(&rsaKeyData.blob);
6606 CheckedDeleteKey(&ecdsaKeyData.blob);
6607}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006608
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006609INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6610
Janis Danisevskis24c04702020-12-16 18:28:39 -08006611} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006612
6613int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006614 std::cout << "Testing ";
6615 auto halInstances =
6616 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6617 std::cout << "HAL instances:\n";
6618 for (auto& entry : halInstances) {
6619 std::cout << " " << entry << '\n';
6620 }
6621
Selene Huang31ab4042020-04-29 04:22:39 -07006622 ::testing::InitGoogleTest(&argc, argv);
6623 for (int i = 1; i < argc; ++i) {
6624 if (argv[i][0] == '-') {
6625 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006626 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6627 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006628 }
6629 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006630 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6631 dump_Attestations = true;
6632 } else {
6633 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006634 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006635 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6636 if (std::string(argv[i]) == "--check_patchLevels") {
6637 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6638 }
Selene Huang31ab4042020-04-29 04:22:39 -07006639 }
6640 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006641 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006642}