1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Permission is hereby granted, free of charge, to any person
5  * obtaining a copy of this software and associated documentation
6  * files (the "Software"), to deal in the Software without
7  * restriction, including without limitation the rights to use, copy,
8  * modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 
25 #include <trusty/keymaster.h>
26 #include <trusty/keymaster_serializable.h>
27 #include <trusty/rpmb.h>
28 #include <trusty/trusty_ipc.h>
29 #include <trusty/util.h>
30 
31 #define LOCAL_LOG 0
32 
33 static struct trusty_ipc_chan km_chan;
34 static bool initialized;
35 static int trusty_km_version = 2;
36 static const size_t kMaxCaRequestSize = 10000;
37 static const size_t kMaxSendSize = 4000;
38 static const size_t kUuidSize = 32;
39 
40 #ifndef MIN
41 #define MIN(a, b) ((a) < (b) ? (a) : (b))
42 #endif
43 
44 #ifndef NELEMS
45 #define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
46 #endif
47 
km_send_request(uint32_t cmd,const void * req,size_t req_len)48 static int km_send_request(uint32_t cmd, const void* req, size_t req_len) {
49     struct keymaster_message header = {.cmd = cmd};
50     int num_iovecs = req ? 2 : 1;
51 
52     struct trusty_ipc_iovec req_iovs[2] = {
53             {.base = &header, .len = sizeof(header)},
54             {.base = (void*)req, .len = req_len},
55     };
56 
57     return trusty_ipc_send(&km_chan, req_iovs, num_iovecs, true);
58 }
59 
60 /* Checks that the command opcode in |header| matches |ex-ected_cmd|. Checks
61  * that |tipc_result| is a valid response size. Returns negative on error.
62  */
check_response_error(uint32_t expected_cmd,struct keymaster_message header,int32_t tipc_result)63 static int check_response_error(uint32_t expected_cmd,
64                                 struct keymaster_message header,
65                                 int32_t tipc_result) {
66     if (tipc_result < 0) {
67         trusty_error("failed (%d) to recv response\n", tipc_result);
68         return tipc_result;
69     }
70     if ((size_t)tipc_result < sizeof(struct keymaster_message)) {
71         trusty_error("invalid response size (%d)\n", tipc_result);
72         return TRUSTY_ERR_GENERIC;
73     }
74     if ((header.cmd & ~(KEYMASTER_STOP_BIT)) !=
75         (expected_cmd | KEYMASTER_RESP_BIT)) {
76         trusty_error("malformed response\n");
77         return TRUSTY_ERR_GENERIC;
78     }
79     return tipc_result;
80 }
81 
82 /* Reads the raw response to |resp| up to a maximum size of |resp_len|. Format
83  * of each message frame read from the secure side:
84  *
85  * command header : 4 bytes
86  * opaque bytes   : MAX(KEYMASTER_MAX_BUFFER_LENGTH, x) bytes
87  *
88  * The individual message frames from the secure side are reassembled
89  * into |resp|, stripping each frame's command header. Returns the number
90  * of bytes written to |resp| on success, negative on error.
91  */
km_read_raw_response(uint32_t cmd,void * resp,size_t resp_len)92 static int km_read_raw_response(uint32_t cmd, void* resp, size_t resp_len) {
93     struct keymaster_message header = {.cmd = cmd};
94     int rc = TRUSTY_ERR_GENERIC;
95     size_t max_resp_len = resp_len;
96     struct trusty_ipc_iovec resp_iovs[2] = {
97             {.base = &header, .len = sizeof(header)},
98             {.base = resp,
99              .len = MIN(KEYMASTER_MAX_BUFFER_LENGTH, max_resp_len)}};
100 
101     if (!resp) {
102         return TRUSTY_ERR_GENERIC;
103     }
104     resp_len = 0;
105     while (true) {
106         resp_iovs[1].base = (uint8_t*)resp + resp_len;
107         resp_iovs[1].len = MIN(KEYMASTER_MAX_BUFFER_LENGTH,
108                                (int)max_resp_len - (int)resp_len);
109 
110         rc = trusty_ipc_recv(&km_chan, resp_iovs, NELEMS(resp_iovs), true);
111         rc = check_response_error(cmd, header, rc);
112         if (rc < 0) {
113             return rc;
114         }
115         resp_len += ((size_t)rc - sizeof(struct keymaster_message));
116         if (header.cmd & KEYMASTER_STOP_BIT || resp_len >= max_resp_len) {
117             break;
118         }
119     }
120 
121     return resp_len;
122 }
123 
124 /* Reads a Keymaster Response message with a sized buffer. The format
125  * of the response is as follows:
126  *
127  * command header : 4 bytes
128  * error          : 4 bytes
129  * data length    : 4 bytes
130  * data           : |data length| bytes
131  *
132  * On success, |error|, |resp_data|, and |resp_data_len| are filled
133  * successfully. Returns a trusty_err.
134  */
km_read_data_response(uint32_t cmd,int32_t * error,uint8_t * resp_data,uint32_t * resp_data_len)135 static int km_read_data_response(uint32_t cmd,
136                                  int32_t* error,
137                                  uint8_t* resp_data,
138                                  uint32_t* resp_data_len) {
139     struct keymaster_message header = {.cmd = cmd};
140     int rc = TRUSTY_ERR_GENERIC;
141     size_t max_resp_len = *resp_data_len;
142     uint32_t resp_data_bytes = 0;
143     /* On the first read, recv the keymaster_message header, error code,
144      * response data length, and response data. On subsequent iterations,
145      * only recv the keymaster_message header and response data.
146      */
147     struct trusty_ipc_iovec resp_iovs[4] = {
148             {.base = &header, .len = sizeof(header)},
149             {.base = error, .len = sizeof(int32_t)},
150             {.base = resp_data_len, .len = sizeof(uint32_t)},
151             {.base = resp_data,
152              .len = MIN(KEYMASTER_MAX_BUFFER_LENGTH, max_resp_len)}};
153 
154     rc = trusty_ipc_recv(&km_chan, resp_iovs, NELEMS(resp_iovs), true);
155     rc = check_response_error(cmd, header, rc);
156     if (rc < 0) {
157         return rc;
158     }
159     /* resp_data_bytes does not include the error or response data length */
160     resp_data_bytes += ((size_t)rc - sizeof(struct keymaster_message) -
161                         2 * sizeof(uint32_t));
162     if (header.cmd & KEYMASTER_STOP_BIT) {
163         return TRUSTY_ERR_NONE;
164     }
165 
166     /* Read the remaining response data */
167     uint8_t* resp_data_start = resp_data + resp_data_bytes;
168     size_t resp_data_remaining = *resp_data_len - resp_data_bytes;
169     rc = km_read_raw_response(cmd, resp_data_start, resp_data_remaining);
170     if (rc < 0) {
171         return rc;
172     }
173     resp_data_bytes += rc;
174     if (*resp_data_len != resp_data_bytes) {
175         return TRUSTY_ERR_GENERIC;
176     }
177     return TRUSTY_ERR_NONE;
178 }
179 
180 /**
181  * Convenience method to send a request to the secure side, handle rpmb
182  * operations, and receive the response. If |resp_data| is not NULL, the
183  * caller expects an additional data buffer to be returned from the secure
184  * side.
185  */
km_do_tipc(uint32_t cmd,void * req,uint32_t req_len,void * resp_data,uint32_t * resp_data_len)186 static int km_do_tipc(uint32_t cmd,
187                       void* req,
188                       uint32_t req_len,
189                       void* resp_data,
190                       uint32_t* resp_data_len) {
191     int rc = TRUSTY_ERR_GENERIC;
192     struct km_no_response resp_header;
193 
194     rc = km_send_request(cmd, req, req_len);
195     if (rc < 0) {
196         trusty_error("%s: failed (%d) to send km request\n", __func__, rc);
197         return rc;
198     }
199 
200     if (!resp_data) {
201         rc = km_read_raw_response(cmd, &resp_header, sizeof(resp_header));
202     } else {
203         rc = km_read_data_response(cmd, &resp_header.error, resp_data,
204                                    resp_data_len);
205     }
206 
207     if (rc < 0) {
208         trusty_error("%s: failed (%d) to read km response\n", __func__, rc);
209         return rc;
210     }
211     if (resp_header.error != KM_ERROR_OK) {
212         trusty_error("%s: keymaster returned error (%d)\n", __func__,
213                      resp_header.error);
214         return TRUSTY_ERR_GENERIC;
215     }
216     return TRUSTY_ERR_NONE;
217 }
218 
MessageVersion(uint8_t major_ver,uint8_t minor_ver,uint8_t subminor_ver)219 static int32_t MessageVersion(uint8_t major_ver,
220                               uint8_t minor_ver,
221                               uint8_t subminor_ver) {
222     int32_t message_version = -1;
223     switch (major_ver) {
224     case 0:
225         message_version = 0;
226         break;
227     case 1:
228         switch (minor_ver) {
229         case 0:
230             message_version = 1;
231             break;
232         case 1:
233             message_version = 2;
234             break;
235         }
236         break;
237     case 2:
238         message_version = 3;
239         break;
240     }
241     return message_version;
242 }
243 
km_get_version(int32_t * version)244 static int km_get_version(int32_t* version) {
245     int rc = TRUSTY_ERR_GENERIC;
246     struct km_get_version_resp resp;
247 
248     rc = km_send_request(KM_GET_VERSION, NULL, 0);
249     if (rc < 0) {
250         trusty_error("failed to send km version request", rc);
251         return rc;
252     }
253 
254     rc = km_read_raw_response(KM_GET_VERSION, &resp, sizeof(resp));
255     if (rc < 0) {
256         trusty_error("%s: failed (%d) to read km response\n", __func__, rc);
257         return rc;
258     }
259 
260     *version =
261             MessageVersion(resp.major_ver, resp.minor_ver, resp.subminor_ver);
262     return TRUSTY_ERR_NONE;
263 }
264 
km_tipc_init(struct trusty_ipc_dev * dev)265 int km_tipc_init(struct trusty_ipc_dev* dev) {
266     int rc = TRUSTY_ERR_GENERIC;
267 
268     trusty_assert(dev);
269 
270     trusty_ipc_chan_init(&km_chan, dev);
271     trusty_debug("Connecting to Keymaster service\n");
272 
273     /* connect to km service and wait for connect to complete */
274     rc = trusty_ipc_connect(&km_chan, KEYMASTER_PORT, true);
275     if (rc < 0) {
276         trusty_error("failed (%d) to connect to '%s'\n", rc, KEYMASTER_PORT);
277         return rc;
278     }
279     initialized = true;
280 
281     int32_t version = -1;
282     rc = km_get_version(&version);
283     if (rc < 0) {
284         trusty_error("failed (%d) to get keymaster version\n", rc);
285         return rc;
286     }
287     if (version < trusty_km_version) {
288         trusty_error("keymaster version mismatch. Expected %d, received %d\n",
289                      trusty_km_version, version);
290         return TRUSTY_ERR_GENERIC;
291     }
292 
293     return TRUSTY_ERR_NONE;
294 }
295 
km_tipc_shutdown(void)296 void km_tipc_shutdown(void) {
297     if (!initialized)
298         return;
299     /* close channel */
300     trusty_ipc_close(&km_chan);
301 
302     initialized = false;
303 }
304 
trusty_set_boot_params(uint32_t os_version,uint32_t os_patchlevel,keymaster_verified_boot_t verified_boot_state,bool device_locked,const uint8_t * verified_boot_key_hash,uint32_t verified_boot_key_hash_size,const uint8_t * verified_boot_hash,uint32_t verified_boot_hash_size)305 int trusty_set_boot_params(uint32_t os_version,
306                            uint32_t os_patchlevel,
307                            keymaster_verified_boot_t verified_boot_state,
308                            bool device_locked,
309                            const uint8_t* verified_boot_key_hash,
310                            uint32_t verified_boot_key_hash_size,
311                            const uint8_t* verified_boot_hash,
312                            uint32_t verified_boot_hash_size) {
313     struct km_boot_params params = {
314             .os_version = os_version,
315             .os_patchlevel = os_patchlevel,
316             .device_locked = (uint32_t)device_locked,
317             .verified_boot_state = (uint32_t)verified_boot_state,
318             .verified_boot_key_hash_size = verified_boot_key_hash_size,
319             .verified_boot_key_hash = verified_boot_key_hash,
320             .verified_boot_hash_size = verified_boot_hash_size,
321             .verified_boot_hash = verified_boot_hash};
322     uint8_t* req = NULL;
323     uint32_t req_size = 0;
324     int rc = km_boot_params_serialize(&params, &req, &req_size);
325 
326     if (rc < 0) {
327         trusty_error("failed (%d) to serialize request\n", rc);
328         goto end;
329     }
330     rc = km_do_tipc(KM_SET_BOOT_PARAMS, req, req_size, NULL, NULL);
331 
332 end:
333     if (req) {
334         trusty_free(req);
335     }
336     return rc;
337 }
338 
trusty_send_attestation_data(uint32_t cmd,const uint8_t * data,uint32_t data_size,keymaster_algorithm_t algorithm)339 static int trusty_send_attestation_data(uint32_t cmd,
340                                         const uint8_t* data,
341                                         uint32_t data_size,
342                                         keymaster_algorithm_t algorithm) {
343     struct km_attestation_data attestation_data = {
344             .algorithm = (uint32_t)algorithm,
345             .data_size = data_size,
346             .data = data,
347     };
348     uint8_t* req = NULL;
349     uint32_t req_size = 0;
350     int rc = km_attestation_data_serialize(&attestation_data, &req, &req_size);
351 
352     if (rc < 0) {
353         trusty_error("failed (%d) to serialize request\n", rc);
354         goto end;
355     }
356     rc = km_do_tipc(cmd, req, req_size, NULL, NULL);
357 
358 end:
359     if (req) {
360         trusty_free(req);
361     }
362     return rc;
363 }
364 
trusty_send_raw_buffer(uint32_t cmd,const uint8_t * req_data,uint32_t req_data_size,uint8_t * resp_data,uint32_t * resp_data_size)365 static int trusty_send_raw_buffer(uint32_t cmd,
366                                   const uint8_t* req_data,
367                                   uint32_t req_data_size,
368                                   uint8_t* resp_data,
369                                   uint32_t* resp_data_size) {
370     struct km_raw_buffer buf = {
371             .data_size = req_data_size,
372             .data = req_data,
373     };
374     uint8_t* req = NULL;
375     uint32_t req_size = 0;
376     int rc = km_raw_buffer_serialize(&buf, &req, &req_size);
377     if (rc < 0) {
378         trusty_error("failed (%d) to serialize request\n", rc);
379         goto end;
380     }
381     rc = km_do_tipc(cmd, req, req_size, resp_data, resp_data_size);
382 
383 end:
384     if (req) {
385         trusty_free(req);
386     }
387     return rc;
388 }
389 
trusty_set_attestation_key(const uint8_t * key,uint32_t key_size,keymaster_algorithm_t algorithm)390 int trusty_set_attestation_key(const uint8_t* key,
391                                uint32_t key_size,
392                                keymaster_algorithm_t algorithm) {
393     return trusty_send_attestation_data(KM_SET_ATTESTATION_KEY, key, key_size,
394                                         algorithm);
395 }
396 
trusty_append_attestation_cert_chain(const uint8_t * cert,uint32_t cert_size,keymaster_algorithm_t algorithm)397 int trusty_append_attestation_cert_chain(const uint8_t* cert,
398                                          uint32_t cert_size,
399                                          keymaster_algorithm_t algorithm) {
400     return trusty_send_attestation_data(KM_APPEND_ATTESTATION_CERT_CHAIN, cert,
401                                         cert_size, algorithm);
402 }
403 
trusty_atap_get_ca_request(const uint8_t * operation_start,uint32_t operation_start_size,uint8_t ** ca_request_p,uint32_t * ca_request_size_p)404 int trusty_atap_get_ca_request(const uint8_t* operation_start,
405                                uint32_t operation_start_size,
406                                uint8_t** ca_request_p,
407                                uint32_t* ca_request_size_p) {
408     *ca_request_p = trusty_calloc(1, kMaxCaRequestSize);
409     if (!*ca_request_p) {
410         return TRUSTY_ERR_NO_MEMORY;
411     }
412     *ca_request_size_p = kMaxCaRequestSize;
413     int rc = trusty_send_raw_buffer(KM_ATAP_GET_CA_REQUEST, operation_start,
414                                     operation_start_size, *ca_request_p,
415                                     ca_request_size_p);
416     if (rc != TRUSTY_ERR_NONE) {
417         trusty_free(*ca_request_p);
418     }
419     return rc;
420 }
421 
trusty_atap_set_ca_response(const uint8_t * ca_response,uint32_t ca_response_size)422 int trusty_atap_set_ca_response(const uint8_t* ca_response,
423                                 uint32_t ca_response_size) {
424     struct km_set_ca_response_begin_req begin_req;
425     int rc = TRUSTY_ERR_GENERIC;
426     uint32_t bytes_sent = 0, send_size = 0;
427 
428     /* Tell the Trusty Keymaster TA the size of CA Response message */
429     begin_req.ca_response_size = ca_response_size;
430     rc = km_do_tipc(KM_ATAP_SET_CA_RESPONSE_BEGIN, &begin_req,
431                     sizeof(begin_req), NULL, NULL);
432     if (rc != TRUSTY_ERR_NONE) {
433         return rc;
434     }
435 
436     /* Send the CA Response message in chunks */
437     while (bytes_sent < ca_response_size) {
438         send_size = MIN(kMaxSendSize, ca_response_size - bytes_sent);
439         rc = trusty_send_raw_buffer(KM_ATAP_SET_CA_RESPONSE_UPDATE,
440                                     ca_response + bytes_sent, send_size, NULL,
441                                     NULL);
442         if (rc != TRUSTY_ERR_NONE) {
443             return rc;
444         }
445         bytes_sent += send_size;
446     }
447 
448     /* Tell Trusty Keymaster to parse the CA Response message */
449     return km_do_tipc(KM_ATAP_SET_CA_RESPONSE_FINISH, NULL, 0, NULL, NULL);
450 }
451 
trusty_atap_read_uuid_str(char ** uuid_p)452 int trusty_atap_read_uuid_str(char** uuid_p) {
453     *uuid_p = (char*)trusty_calloc(1, kUuidSize + 1);
454     *uuid_p[kUuidSize] = '\0';
455 
456     uint32_t response_size = kUuidSize;
457     int rc = km_do_tipc(KM_ATAP_READ_UUID, NULL, 0, *uuid_p, &response_size);
458     if (rc < 0) {
459         trusty_error("failed to read uuid: %d\n", rc);
460         trusty_free(*uuid_p);
461         return rc;
462     }
463     if (response_size != kUuidSize) {
464         trusty_error("keymaster returned wrong uuid size: %d\n", response_size);
465         trusty_free(*uuid_p);
466         rc = TRUSTY_ERR_GENERIC;
467     }
468     return rc;
469 }
470