• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <unistd.h>
25 
26 #include <log/log.h>
27 #include <trusty/tipc.h>
28 
29 #include "trusty_keymaster_ipc.h"
30 #include "keymaster_ipc.h"
31 
32 #define TRUSTY_DEVICE_NAME "/dev/trusty-ipc-dev0"
33 
34 static int handle_ = 0;
35 
trusty_keymaster_connect()36 int trusty_keymaster_connect() {
37     int rc = tipc_connect(TRUSTY_DEVICE_NAME, KEYMASTER_PORT);
38     if (rc < 0) {
39         return rc;
40     }
41 
42     handle_ = rc;
43     return 0;
44 }
45 
trusty_keymaster_call(uint32_t cmd,void * in,uint32_t in_size,uint8_t * out,uint32_t * out_size)46 int trusty_keymaster_call(uint32_t cmd, void *in, uint32_t in_size, uint8_t *out,
47                           uint32_t *out_size)  {
48     if (handle_ == 0) {
49         ALOGE("not connected\n");
50         return -EINVAL;
51     }
52 
53     size_t msg_size = in_size + sizeof(struct keymaster_message);
54     struct keymaster_message *msg = malloc(msg_size);
55     msg->cmd = cmd;
56     memcpy(msg->payload, in, in_size);
57 
58     ssize_t rc = write(handle_, msg, msg_size);
59     free(msg);
60 
61     if (rc < 0) {
62         ALOGE("failed to send cmd (%d) to %s: %s\n", cmd,
63                 KEYMASTER_PORT, strerror(errno));
64         return -errno;
65     }
66 
67     rc = read(handle_, out, *out_size);
68     if (rc < 0) {
69         ALOGE("failed to retrieve response for cmd (%d) to %s: %s\n",
70                 cmd, KEYMASTER_PORT, strerror(errno));
71         return -errno;
72     }
73 
74     if ((size_t) rc < sizeof(struct keymaster_message)) {
75         ALOGE("invalid response size (%d)\n", (int) rc);
76         return -EINVAL;
77     }
78 
79     msg = (struct keymaster_message *) out;
80 
81     if ((cmd | KEYMASTER_RESP_BIT) != msg->cmd) {
82         ALOGE("invalid command (%d)", msg->cmd);
83         return -EINVAL;
84     }
85 
86     *out_size = ((size_t) rc) - sizeof(struct keymaster_message);
87     return rc;
88 }
89 
trusty_keymaster_disconnect()90 void trusty_keymaster_disconnect() {
91     if (handle_ != 0) {
92         tipc_close(handle_);
93     }
94 }
95 
96