1 /*
2  * Copyright (C) 2015 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 
17 #define LOG_TAG "TrustyKeymaster"
18 
19 // TODO: make this generic in libtrusty
20 
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/uio.h>
25 #include <unistd.h>
26 
27 #include <algorithm>
28 #include <variant>
29 #include <vector>
30 
31 #include <log/log.h>
32 #include <trusty/tipc.h>
33 
34 #include <trusty_keymaster/ipc/keymaster_ipc.h>
35 #include <trusty_keymaster/ipc/trusty_keymaster_ipc.h>
36 
37 #define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
38 
39 static int handle_ = -1;
40 
trusty_keymaster_connect()41 int trusty_keymaster_connect() {
42     int rc = tipc_connect(TRUSTY_DEVICE_NAME, KEYMASTER_PORT);
43     if (rc < 0) {
44         return rc;
45     }
46 
47     handle_ = rc;
48     return 0;
49 }
50 
51 class VectorEraser {
52   public:
VectorEraser(std::vector<uint8_t> * v)53     VectorEraser(std::vector<uint8_t>* v) : _v(v) {}
~VectorEraser()54     ~VectorEraser() {
55         if (_v) {
56             std::fill(const_cast<volatile uint8_t*>(_v->data()),
57                       const_cast<volatile uint8_t*>(_v->data() + _v->size()), 0);
58         }
59     }
disarm()60     void disarm() { _v = nullptr; }
61     VectorEraser(const VectorEraser&) = delete;
62     VectorEraser& operator=(const VectorEraser&) = delete;
63     VectorEraser(VectorEraser&& other) = delete;
64     VectorEraser& operator=(VectorEraser&&) = delete;
65 
66   private:
67     std::vector<uint8_t>* _v;
68 };
69 
trusty_keymaster_call_2(uint32_t cmd,void * in,uint32_t in_size)70 std::variant<int, std::vector<uint8_t>> trusty_keymaster_call_2(uint32_t cmd, void* in,
71                                                                 uint32_t in_size) {
72     if (handle_ < 0) {
73         ALOGE("not connected\n");
74         return -EINVAL;
75     }
76 
77     size_t msg_size = in_size + sizeof(struct keymaster_message);
78     struct keymaster_message* msg = reinterpret_cast<struct keymaster_message*>(malloc(msg_size));
79     if (!msg) {
80         ALOGE("failed to allocate msg buffer\n");
81         return -EINVAL;
82     }
83 
84     msg->cmd = cmd;
85     memcpy(msg->payload, in, in_size);
86 
87     ssize_t rc = write(handle_, msg, msg_size);
88     free(msg);
89 
90     if (rc < 0) {
91         ALOGE("failed to send cmd (%d) to %s: %s\n", cmd, KEYMASTER_PORT, strerror(errno));
92         return -errno;
93     }
94 
95     std::vector<uint8_t> out(TRUSTY_KEYMASTER_RECV_BUF_SIZE);
96     VectorEraser out_eraser(&out);
97     uint8_t* write_pos = out.data();
98     uint8_t* out_end = out.data() + out.size();
99 
100     struct iovec iov[2];
101     struct keymaster_message header;
102     iov[0] = {.iov_base = &header, .iov_len = sizeof(struct keymaster_message)};
103     while (true) {
104         if (out_end - write_pos < KEYMASTER_MAX_BUFFER_LENGTH) {
105             // In stead of using std::vector.resize(), allocate a new one to have chance
106             // at zeroing the old buffer.
107             std::vector<uint8_t> new_out(out.size() + KEYMASTER_MAX_BUFFER_LENGTH);
108             // After the swap below this erases the old out buffer.
109             VectorEraser new_out_eraser(&new_out);
110             std::copy(out.data(), write_pos, new_out.begin());
111 
112             auto write_offset = write_pos - out.data();
113 
114             std::swap(new_out, out);
115 
116             write_pos = out.data() + write_offset;
117             out_end = out.data() + out.size();
118         }
119         size_t buffer_size = 0;
120         if (__builtin_sub_overflow(reinterpret_cast<uintptr_t>(out_end),
121                                    reinterpret_cast<uintptr_t>(write_pos), &buffer_size)) {
122             return -EOVERFLOW;
123         }
124         iov[1] = {.iov_base = write_pos, .iov_len = buffer_size};
125 
126         rc = readv(handle_, iov, 2);
127         if (rc < 0) {
128             ALOGE("failed to retrieve response for cmd (%d) to %s: %s\n", cmd, KEYMASTER_PORT,
129                   strerror(errno));
130             return -errno;
131         }
132 
133         if ((size_t)rc < sizeof(struct keymaster_message)) {
134             ALOGE("invalid response size (%d)\n", (int)rc);
135             return -EINVAL;
136         }
137 
138         if ((cmd | KEYMASTER_RESP_BIT) != (header.cmd & ~(KEYMASTER_STOP_BIT))) {
139             ALOGE("invalid command (%d)", header.cmd);
140             return -EINVAL;
141         }
142         write_pos += ((size_t)rc - sizeof(struct keymaster_message));
143         if (header.cmd & KEYMASTER_STOP_BIT) {
144             break;
145         }
146     }
147 
148     out.resize(write_pos - out.data());
149     out_eraser.disarm();
150     return out;
151 }
152 
trusty_keymaster_call(uint32_t cmd,void * in,uint32_t in_size,uint8_t * out,uint32_t * out_size)153 int trusty_keymaster_call(uint32_t cmd, void* in, uint32_t in_size, uint8_t* out,
154                           uint32_t* out_size) {
155     auto result = trusty_keymaster_call_2(cmd, in, in_size);
156     if (auto out_buffer = std::get_if<std::vector<uint8_t>>(&result)) {
157         if (out_buffer->size() <= *out_size) {
158             std::copy(out_buffer->begin(), out_buffer->end(), out);
159             std::fill(const_cast<volatile uint8_t*>(&*out_buffer->begin()),
160                       const_cast<volatile uint8_t*>(&*out_buffer->end()), 0);
161 
162             *out_size = out_buffer->size();
163             return 0;
164         } else {
165             ALOGE("Message was to large (%zu) for the provided buffer (%u)", out_buffer->size(),
166                   *out_size);
167             return -EMSGSIZE;
168         }
169     } else {
170         return std::get<int>(result);
171     }
172 }
173 
trusty_keymaster_disconnect()174 void trusty_keymaster_disconnect() {
175     if (handle_ >= 0) {
176         tipc_close(handle_);
177     }
178     handle_ = -1;
179 }
180 
translate_error(int err)181 keymaster_error_t translate_error(int err) {
182     switch (err) {
183         case 0:
184             return KM_ERROR_OK;
185         case -EPERM:
186         case -EACCES:
187             return KM_ERROR_SECURE_HW_ACCESS_DENIED;
188 
189         case -ECANCELED:
190             return KM_ERROR_OPERATION_CANCELLED;
191 
192         case -ENODEV:
193             return KM_ERROR_UNIMPLEMENTED;
194 
195         case -ENOMEM:
196             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
197 
198         case -EBUSY:
199             return KM_ERROR_SECURE_HW_BUSY;
200 
201         case -EIO:
202             return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
203 
204         case -EOVERFLOW:
205             return KM_ERROR_INVALID_INPUT_LENGTH;
206 
207         default:
208             return KM_ERROR_UNKNOWN_ERROR;
209     }
210 }
211 
trusty_keymaster_send(uint32_t command,const keymaster::Serializable & req,keymaster::KeymasterResponse * rsp)212 keymaster_error_t trusty_keymaster_send(uint32_t command, const keymaster::Serializable& req,
213                                         keymaster::KeymasterResponse* rsp) {
214     uint32_t req_size = req.SerializedSize();
215     if (req_size > TRUSTY_KEYMASTER_SEND_BUF_SIZE) {
216         ALOGE("Request too big: %u Max size: %u", req_size, TRUSTY_KEYMASTER_SEND_BUF_SIZE);
217         return KM_ERROR_INVALID_INPUT_LENGTH;
218     }
219 
220     uint8_t send_buf[TRUSTY_KEYMASTER_SEND_BUF_SIZE];
221     keymaster::Eraser send_buf_eraser(send_buf, TRUSTY_KEYMASTER_SEND_BUF_SIZE);
222     req.Serialize(send_buf, send_buf + req_size);
223 
224     // Send it
225     auto response = trusty_keymaster_call_2(command, send_buf, req_size);
226     if (auto response_buffer = std::get_if<std::vector<uint8_t>>(&response)) {
227         keymaster::Eraser response_buffer_erasor(response_buffer->data(), response_buffer->size());
228         ALOGV("Received %zu byte response\n", response_buffer->size());
229 
230         const uint8_t* p = response_buffer->data();
231         if (!rsp->Deserialize(&p, p + response_buffer->size())) {
232             ALOGE("Error deserializing response of size %zu\n", response_buffer->size());
233             return KM_ERROR_UNKNOWN_ERROR;
234         } else if (rsp->error != KM_ERROR_OK) {
235             ALOGE("Response of size %zu contained error code %d\n", response_buffer->size(),
236                   (int)rsp->error);
237         }
238         return rsp->error;
239     } else {
240         auto rc = std::get<int>(response);
241         // Reset the connection on tipc error
242         trusty_keymaster_disconnect();
243         trusty_keymaster_connect();
244         ALOGE("tipc error: %d\n", rc);
245         // TODO(swillden): Distinguish permanent from transient errors and set error_ appropriately.
246         return translate_error(rc);
247     }
248 }
249