summaryrefslogtreecommitdiff
path: root/KM300/JavacardSecureElement.cpp
blob: 51e047cdbb4fb0a13637a2a3cb97def85981254a (plain)
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
/*
 * 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.
 */

#define LOG_TAG "javacard.keymint.device.strongbox-impl"
#include "JavacardSecureElement.h"

#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <regex.h>
#include <string>
#include <vector>

#include <android-base/logging.h>
#include <android-base/properties.h>
#include <keymaster/android_keymaster_messages.h>

#include "keymint_utils.h"

namespace keymint::javacard {

keymaster_error_t JavacardSecureElement::initializeJavacard() {
    Array request;
    request.add(Uint(getOsVersion()));
    request.add(Uint(getOsPatchlevel()));
    request.add(Uint(getVendorPatchlevel()));
    auto [item, err] = sendRequest(Instruction::INS_INIT_STRONGBOX_CMD, request);
    return err;
}

void JavacardSecureElement::setDeleteAllKeysPending() {
    isDeleteAllKeysPending = true;
}
void JavacardSecureElement::setEarlyBootEndedPending() {
    isEarlyBootEndedPending = true;
}
void JavacardSecureElement::sendPendingEvents() {
    if (isDeleteAllKeysPending) {
      auto [_, err] = sendRequest(Instruction::INS_DELETE_ALL_KEYS_CMD);
      if (err == KM_ERROR_OK) {
        isDeleteAllKeysPending = false;
      } else {
        LOG(ERROR) << "Error in sending deleteAllKeys.";
      }
    }
    if (isEarlyBootEndedPending) {
      auto [_, err] = sendRequest(Instruction::INS_EARLY_BOOT_ENDED_CMD);
      if (err == KM_ERROR_OK) {
        isEarlyBootEndedPending = false;
      } else {
        LOG(ERROR) << "Error in sending earlyBootEnded.";
      }
    }
}

keymaster_error_t JavacardSecureElement::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 {
        LOG(ERROR) << "Error in constructApduMessage.";
        return (KM_ERROR_INVALID_INPUT_LENGTH);
    }
    return (KM_ERROR_OK);  // success
}

keymaster_error_t JavacardSecureElement::sendData(Instruction ins, std::vector<uint8_t>& inData,
                                                  std::vector<uint8_t>& response) {
    keymaster_error_t ret = KM_ERROR_UNKNOWN_ERROR;
    std::vector<uint8_t> apdu;

    ret = constructApduMessage(ins, inData, apdu);

    if (ret != KM_ERROR_OK) {
        return ret;
    }

    if (!transport_->sendData(apdu, response)) {
        LOG(ERROR) << "Error in sending data in sendData.";
        return (KM_ERROR_SECURE_HW_COMMUNICATION_FAILED);
    }

    // Response size should be greater than 2. Cbor output data followed by two
    // bytes of APDU status.
    if ((response.size() <= 2) || (getApduStatus(response) != APDU_RESP_STATUS_OK)) {
        LOG(ERROR) << "Response of the sendData is wrong: response size = " << response.size()
                   << " apdu status = " << getApduStatus(response);
        return (KM_ERROR_UNKNOWN_ERROR);
    }
    // remove the status bytes
    response.pop_back();
    response.pop_back();
    return (KM_ERROR_OK);  // success
}

std::tuple<std::unique_ptr<Item>, keymaster_error_t>
JavacardSecureElement::sendRequest(Instruction ins, Array& request) {
    vector<uint8_t> response;
    // encode request
    std::vector<uint8_t> command = request.encode();
    auto sendError = sendData(ins, command, response);
    if (sendError != KM_ERROR_OK) {
        return {unique_ptr<Item>(nullptr), sendError};
    }
    // decode the response and send that back
    return cbor_.decodeData(response);
}

std::tuple<std::unique_ptr<Item>, keymaster_error_t>
JavacardSecureElement::sendRequest(Instruction ins, std::vector<uint8_t>& command) {
    vector<uint8_t> response;
    auto sendError = sendData(ins, command, response);
    if (sendError != KM_ERROR_OK) {
        return {unique_ptr<Item>(nullptr), sendError};
    }
    // decode the response and send that back
    return cbor_.decodeData(response);
}

std::tuple<std::unique_ptr<Item>, keymaster_error_t>
JavacardSecureElement::sendRequest(Instruction ins) {
    vector<uint8_t> response;
    vector<uint8_t> emptyRequest;
    auto sendError = sendData(ins, emptyRequest, response);
    if (sendError != KM_ERROR_OK) {
        return {unique_ptr<Item>(nullptr), sendError};
    }
    // decode the response and send that back
    return cbor_.decodeData(response);
}

}  // namespace keymint::javacard