forked from BKSSMVenkateswarlu/JavaCardKeymaster
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProvision.cpp
More file actions
509 lines (444 loc) · 18.1 KB
/
Copy pathProvision.cpp
File metadata and controls
509 lines (444 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
**
** Copyright 2020, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/bio.h>
#include <openssl/asn1.h>
#include <cppbor.h>
#include <cppbor_parse.h>
#include <CborConverter.h>
#include <keymaster/keymaster_configuration.h>
#include <keymaster/attestation_record.h>
#include <android-base/logging.h>
#include <Transport.h>
#include <CommonUtils.h>
#include <Provision.h>
#include <android-base/properties.h>
#define INS_BEGIN_KM_CMD 0x00
#define APDU_CLS 0x80
#define APDU_P1 0x40
#define APDU_P2 0x00
#define APDU_RESP_STATUS_OK 0x9000
#define SE_POWER_RESET_STATUS_FLAG ( 1 << 30)
namespace keymaster {
namespace V4_1 {
namespace javacard {
enum class Instruction {
// Provisioning commands
INS_PROVISION_ATTESTATION_KEY_CMD = INS_BEGIN_KM_CMD+1,
INS_PROVISION_CERT_CHAIN_CMD = INS_BEGIN_KM_CMD+2,
INS_PROVISION_CERT_PARAMS_CMD = INS_BEGIN_KM_CMD+3,
INS_PROVISION_ATTEST_IDS_CMD = INS_BEGIN_KM_CMD+4,
INS_PROVISION_PRESHARED_SECRET_CMD = INS_BEGIN_KM_CMD+5,
INS_SET_BOOT_PARAMS_CMD = INS_BEGIN_KM_CMD+6,
INS_LOCK_PROVISIONING_CMD = INS_BEGIN_KM_CMD+7,
INS_GET_PROVISION_STATUS_CMD = INS_BEGIN_KM_CMD+8,
INS_SET_VERSION_PATCHLEVEL_CMD = INS_BEGIN_KM_CMD+9,
};
//Extended error codes
enum ExtendedErrors {
SW_CONDITIONS_NOT_SATISFIED = -10001,
UNSUPPORTED_CLA = -10002,
INVALID_P1P2 = -10003,
UNSUPPORTED_INSTRUCTION = -10004,
CMD_NOT_ALLOWED = -10005,
SW_WRONG_LENGTH = -10006,
INVALID_DATA = -10007,
CRYPTO_ILLEGAL_USE = -10008,
CRYPTO_ILLEGAL_VALUE = -10009,
CRYPTO_INVALID_INIT = -10010,
CRYPTO_NO_SUCH_ALGORITHM = -10011,
CRYPTO_UNINITIALIZED_KEY = -10012,
GENERIC_UNKNOWN_ERROR = -10013
};
enum ProvisionStatus {
NOT_PROVISIONED = 0x00,
PROVISION_STATUS_ATTESTATION_KEY = 0x01,
PROVISION_STATUS_ATTESTATION_CERT_CHAIN = 0x02,
PROVISION_STATUS_ATTESTATION_CERT_PARAMS = 0x04,
PROVISION_STATUS_ATTEST_IDS = 0x08,
PROVISION_STATUS_PRESHARED_SECRET = 0x10,
PROVISION_STATUS_BOOT_PARAM = 0x20,
PROVISION_STATUS_PROVISIONING_LOCKED = 0x40,
};
// Static function declarations.
static ErrorCode constructApduMessage(Instruction& ins, std::vector<uint8_t>& inputData, std::vector<uint8_t>& apduOut);
static ErrorCode sendProvisionData(std::unique_ptr<se_transport::TransportFactory>& transport, Instruction ins, std::vector<uint8_t>& inData, std::vector<uint8_t>& response);
static uint16_t getStatus(std::vector<uint8_t>& inputData);
template<typename T = ErrorCode>
static std::tuple<std::unique_ptr<Item>, T> decodeData(CborConverter& cb, const std::vector<uint8_t>& response);
template<typename T = ErrorCode>
static T translateExtendedErrorsToHalErrors(T& errorCode);
template<typename T>
static T translateExtendedErrorsToHalErrors(T& errorCode) {
T err;
switch(static_cast<int32_t>(errorCode)) {
case SW_CONDITIONS_NOT_SATISFIED:
case UNSUPPORTED_CLA:
case INVALID_P1P2:
case INVALID_DATA:
case CRYPTO_ILLEGAL_USE:
case CRYPTO_ILLEGAL_VALUE:
case CRYPTO_INVALID_INIT:
case CRYPTO_UNINITIALIZED_KEY:
case GENERIC_UNKNOWN_ERROR:
err = T::UNKNOWN_ERROR;
break;
case CRYPTO_NO_SUCH_ALGORITHM:
err = T::UNSUPPORTED_ALGORITHM;
break;
case UNSUPPORTED_INSTRUCTION:
case CMD_NOT_ALLOWED:
case SW_WRONG_LENGTH:
err = T::UNIMPLEMENTED;
break;
default:
err = static_cast<T>(errorCode);
break;
}
return err;
}
/**
* Returns the negative value of the same number.
*/
static inline int32_t get2sCompliment(uint32_t value) {
return static_cast<int32_t>(~value+1);
}
/**
* This function separates the original error code from the
* power reset flag and returns the original error code.
*/
static uint32_t extractErrorCode(uint32_t errorCode) {
//Check if secure element is reset
bool isSeResetOccurred = (0 != (errorCode & SE_POWER_RESET_STATUS_FLAG));
if (isSeResetOccurred) {
LOG(ERROR) << "Secure element reset happened";
errorCode &= ~SE_POWER_RESET_STATUS_FLAG;
}
return errorCode;
}
template<typename T>
static std::tuple<std::unique_ptr<Item>, T> decodeData(CborConverter& cb, const std::vector<uint8_t>& response) {
std::unique_ptr<Item> item(nullptr);
T errorCode = T::OK;
std::tie(item, errorCode) = cb.decodeData<T>(response, true);
uint32_t tempErrCode = extractErrorCode(static_cast<uint32_t>(errorCode));
// SE sends errocode as unsigned value so convert the unsigned value
// into a signed value of same magnitude and copy back to errorCode.
errorCode = static_cast<T>(get2sCompliment(tempErrCode));
if (T::OK != errorCode)
errorCode = translateExtendedErrorsToHalErrors<T>(errorCode);
return {std::move(item), errorCode};
}
static inline X509* parseDerCertificate(std::vector<uint8_t>& certData) {
X509 *x509 = NULL;
/* Create BIO instance from certificate data */
BIO *bio = BIO_new_mem_buf(certData.data(), certData.size());
if(bio == NULL) {
LOG(ERROR) << " Failed to create BIO from buffer.";
return NULL;
}
/* Create X509 instance from BIO */
x509 = d2i_X509_bio(bio, NULL);
if(x509 == NULL) {
LOG(ERROR) << " Failed to get X509 instance from BIO.";
return NULL;
}
BIO_free(bio);
return x509;
}
static inline void getDerSubjectName(X509* x509, std::vector<uint8_t>& subject) {
uint8_t *subjectDer = NULL;
X509_NAME* asn1Subject = X509_get_subject_name(x509);
if(asn1Subject == NULL) {
LOG(ERROR) << " Failed to read the subject.";
return;
}
/* Convert X509_NAME to der encoded subject */
int len = i2d_X509_NAME(asn1Subject, &subjectDer);
if (len < 0) {
LOG(ERROR) << " Failed to get readable name from X509_NAME.";
return;
}
subject.insert(subject.begin(), subjectDer, subjectDer+len);
}
static inline void getNotAfter(X509* x509, std::vector<uint8_t>& notAfterDate) {
const ASN1_TIME* notAfter = X509_get0_notAfter(x509);
if(notAfter == NULL) {
LOG(ERROR) << " Failed to read expiry time.";
return;
}
int strNotAfterLen = ASN1_STRING_length(notAfter);
const uint8_t *strNotAfter = ASN1_STRING_get0_data(notAfter);
if(strNotAfter == NULL) {
LOG(ERROR) << " Failed to read expiry time from ASN1 string.";
return;
}
notAfterDate.insert(notAfterDate.begin(), strNotAfter, strNotAfter + strNotAfterLen);
}
static uint16_t getStatus(std::vector<uint8_t>& inputData) {
//Last two bytes are the status SW0SW1
return (inputData.at(inputData.size()-2) << 8) | (inputData.at(inputData.size()-1));
}
static ErrorCode constructApduMessage(Instruction& ins, std::vector<uint8_t>& inputData, std::vector<uint8_t>& apduOut) {
apduOut.push_back(static_cast<uint8_t>(APDU_CLS)); //CLS
apduOut.push_back(static_cast<uint8_t>(ins)); //INS
apduOut.push_back(static_cast<uint8_t>(APDU_P1)); //P1
apduOut.push_back(static_cast<uint8_t>(APDU_P2)); //P2
if(USHRT_MAX >= inputData.size()) {
// Send extended length APDU always as response size is not known to HAL.
// Case 1: Lc > 0 CLS | INS | P1 | P2 | 00 | 2 bytes of Lc | CommandData | 2 bytes of Le all set to 00.
// Case 2: Lc = 0 CLS | INS | P1 | P2 | 3 bytes of Le all set to 00.
//Extended length 3 bytes, starts with 0x00
apduOut.push_back(static_cast<uint8_t>(0x00));
if (inputData.size() > 0) {
apduOut.push_back(static_cast<uint8_t>(inputData.size() >> 8));
apduOut.push_back(static_cast<uint8_t>(inputData.size() & 0xFF));
//Data
apduOut.insert(apduOut.end(), inputData.begin(), inputData.end());
}
//Expected length of output.
//Accepting complete length of output every time.
apduOut.push_back(static_cast<uint8_t>(0x00));
apduOut.push_back(static_cast<uint8_t>(0x00));
} else {
return (ErrorCode::INSUFFICIENT_BUFFER_SPACE);
}
return (ErrorCode::OK);//success
}
static ErrorCode sendProvisionData(std::unique_ptr<se_transport::TransportFactory>& transport, Instruction ins, std::vector<uint8_t>& inData, std::vector<uint8_t>& response) {
ErrorCode ret = ErrorCode::OK;
std::vector<uint8_t> apdu;
CborConverter cborConverter;
std::unique_ptr<Item> item;
ret = constructApduMessage(ins, inData, apdu);
if(ret != ErrorCode::OK) return ret;
if(!transport->sendData(apdu.data(), apdu.size(), response)) {
return (ErrorCode::SECURE_HW_COMMUNICATION_FAILED);
}
if((response.size() < 2) || (getStatus(response) != APDU_RESP_STATUS_OK)) {
return (ErrorCode::UNKNOWN_ERROR);
}
if((response.size() > 2)) {
//Skip last 2 bytes in cborData, it contains status.
std::tie(item, ret) = decodeData(cborConverter, std::vector<uint8_t>(response.begin(), response.end()-2));
} else {
ret = ErrorCode::UNKNOWN_ERROR;
}
return ret;
}
ErrorCode Provision::init() {
if(pTransportFactory == nullptr) {
pTransportFactory = std::unique_ptr<se_transport::TransportFactory>(new se_transport::TransportFactory(
android::base::GetBoolProperty("ro.kernel.qemu", false)));
if(!pTransportFactory->openConnection())
return ErrorCode::UNKNOWN_ERROR;
}
return ErrorCode::OK;
}
ErrorCode Provision::provisionAttestationKey(std::vector<uint8_t>& batchKey) {
ErrorCode errorCode = ErrorCode::OK;
std::vector<uint8_t> privKey;
std::vector<uint8_t> pubKey;
EcCurve curve;
CborConverter cborConverter;
cppbor::Array array;
cppbor::Array subArray;
std::vector<uint8_t> response;
Instruction ins = Instruction::INS_PROVISION_ATTESTATION_KEY_CMD;
AuthorizationSet authSetKeyParams(AuthorizationSetBuilder()
.Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
.Authorization(TAG_DIGEST, KM_DIGEST_SHA_2_256)
.Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256)
.Authorization(TAG_PURPOSE, static_cast<keymaster_purpose_t>(0x7F))); /* The value 0x7F is not present in types.hal */
hidl_vec<KeyParameter> keyParams = kmParamSet2Hidl(authSetKeyParams);
if(ErrorCode::OK != (errorCode = ecRawKeyFromPKCS8(batchKey, privKey, pubKey, curve))) {
return errorCode;
}
subArray.add(privKey);
subArray.add(pubKey);
std::vector<uint8_t> encodedArray = subArray.encode();
cppbor::Bstr bstr(encodedArray.begin(), encodedArray.end());
//Encode data.
cborConverter.addKeyparameters(array, keyParams);
array.add(static_cast<uint32_t>(KeyFormat::RAW));
array.add(bstr);
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::provisionAtestationCertificateChain(std::vector<std::vector<uint8_t>>& certChain) {
ErrorCode errorCode = ErrorCode::OK;
cppbor::Array array;
Instruction ins = Instruction::INS_PROVISION_CERT_CHAIN_CMD;
std::vector<uint8_t> response;
std::vector<uint8_t> certData;
for (auto data : certChain) {
certData.insert(certData.end(), data.begin(), data.end());
}
cppbor::Bstr bstrCertChain(certData.begin(), certData.end());
std::vector<uint8_t> cborData = bstrCertChain.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::provisionAttestationCertificateParams(std::vector<uint8_t>& batchCertificate) {
ErrorCode errorCode = ErrorCode::OK;
cppbor::Array array;
Instruction ins = Instruction::INS_PROVISION_CERT_PARAMS_CMD;
std::vector<uint8_t> response;
X509 *x509 = NULL;
std::vector<uint8_t> subject;
std::vector<uint8_t> notAfter;
/* Subject, AuthorityKeyIdentifier and Expirty time of the root certificate are required by javacard. */
/* Get X509 certificate instance for the root certificate.*/
if(NULL == (x509 = parseDerCertificate(batchCertificate))) {
return errorCode;
}
/* Get subject in DER */
getDerSubjectName(x509, subject);
/* Get Expirty Time */
getNotAfter(x509, notAfter);
/*Free X509 */
X509_free(x509);
array = cppbor::Array();
array.add(subject);
array.add(notAfter);
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::provisionAttestationID(AttestIDParams& attestParams) {
ErrorCode errorCode = ErrorCode::OK;
CborConverter cborConverter;
cppbor::Array array;
Instruction ins = Instruction::INS_PROVISION_ATTEST_IDS_CMD;
std::vector<uint8_t> response;
AuthorizationSet authSetAttestParams(AuthorizationSetBuilder()
.Authorization(TAG_ATTESTATION_ID_BRAND, attestParams.brand.data(), attestParams.brand.size())
.Authorization(TAG_ATTESTATION_ID_DEVICE, attestParams.device.data(), attestParams.device.size())
.Authorization(TAG_ATTESTATION_ID_PRODUCT, attestParams.product.data(), attestParams.product.size())
.Authorization(TAG_ATTESTATION_ID_SERIAL, attestParams.serial.data(), attestParams.serial.size())
.Authorization(TAG_ATTESTATION_ID_IMEI, attestParams.imei.data(), attestParams.imei.size())
.Authorization(TAG_ATTESTATION_ID_MEID, attestParams.meid.data(), attestParams.meid.size())
.Authorization(TAG_ATTESTATION_ID_MANUFACTURER, attestParams.manufacturer.data(), attestParams.manufacturer.size())
.Authorization(TAG_ATTESTATION_ID_MODEL, attestParams.model.data(), attestParams.model.size()));
hidl_vec<KeyParameter> attestKeyParams = kmParamSet2Hidl(authSetAttestParams);
array = cppbor::Array();
cborConverter.addKeyparameters(array, attestKeyParams);
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::provisionPreSharedSecret(std::vector<uint8_t>& preSharedSecret) {
ErrorCode errorCode = ErrorCode::OK;
cppbor::Array array;
Instruction ins = Instruction::INS_PROVISION_PRESHARED_SECRET_CMD;
std::vector<uint8_t> response;
array = cppbor::Array();
array.add(preSharedSecret);
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::setAndroidSystemProperties() {
ErrorCode errorCode = ErrorCode::OK;
cppbor::Array array;
std::vector<uint8_t> apdu;
std::vector<uint8_t> response;
Instruction ins = Instruction::INS_SET_VERSION_PATCHLEVEL_CMD;
array.add(GetOsVersion()).
add(GetOsPatchlevel()).
add(GetVendorPatchlevel());
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::provisionBootParameters(BootParams& bootParams) {
ErrorCode errorCode = ErrorCode::OK;
cppbor::Array array;
std::vector<uint8_t> apdu;
std::vector<uint8_t> response;
Instruction ins = Instruction::INS_SET_BOOT_PARAMS_CMD;
array.add(bootParams.bootPatchLevel).
/* Verified Boot Key */
add(bootParams.verifiedBootKey).
/* Verified Boot Hash */
add(bootParams.verifiedBootKeyHash).
/* boot state */
add(bootParams.verifiedBootState).
/* device locked */
add(bootParams.deviceLocked);
std::vector<uint8_t> cborData = array.encode();
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::getProvisionStatus(uint64_t& status) {
ErrorCode errorCode = ErrorCode::OK;
Instruction ins = Instruction::INS_GET_PROVISION_STATUS_CMD;
std::vector<uint8_t> cborData;
std::vector<uint8_t> response;
std::unique_ptr<Item> item;
CborConverter cborConverter;
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
LOG(ERROR) << "Failed to get provision status err: " << static_cast<int32_t>(errorCode);
return errorCode;
}
//Check if SE is provisioned.
std::tie(item, errorCode) = decodeData(cborConverter, std::vector<uint8_t>(response.begin(), response.end()-2));
if(item != NULL) {
if(!cborConverter.getUint64(item, 1, status)) {
LOG(ERROR) << "Failed to parse the status from cbor data";
return ErrorCode::UNKNOWN_ERROR;
}
}
return errorCode;
}
ErrorCode Provision::lockProvision() {
ErrorCode errorCode = ErrorCode::OK;
Instruction ins = Instruction::INS_LOCK_PROVISIONING_CMD;
std::vector<uint8_t> cborData;
std::vector<uint8_t> response;
if(ErrorCode::OK != (errorCode = sendProvisionData(pTransportFactory, ins, cborData, response))) {
return errorCode;
}
return errorCode;
}
ErrorCode Provision::uninit() {
if(pTransportFactory != nullptr) {
if(!pTransportFactory->closeConnection())
return ErrorCode::UNKNOWN_ERROR;
}
return ErrorCode::OK;
}
// Provision End
} // namespace javacard
} // namespace V4_1
} // namespace keymaster