1 /*
2  * Copyright (C) 2020 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 "TrustyAppLoader"
18 
19 #include <BufferAllocator/BufferAllocator.h>
20 #include <android-base/logging.h>
21 #include <android-base/unique_fd.h>
22 #include <fcntl.h>
23 #include <getopt.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/mman.h>
29 #include <sys/sendfile.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <trusty/tipc.h>
33 #include <unistd.h>
34 #include <algorithm>
35 #include <string>
36 
37 #include "apploader_ipc.h"
38 
39 using android::base::unique_fd;
40 using std::string;
41 
42 constexpr const char kTrustyDefaultDeviceName[] = "/dev/trusty-ipc-dev0";
43 
44 static const char* dev_name = kTrustyDefaultDeviceName;
45 
46 static const char* _sopts = "hD:";
47 static const struct option _lopts[] = {
48         {"help", no_argument, 0, 'h'},
49         {"dev", required_argument, 0, 'D'},
50         {0, 0, 0, 0},
51 };
52 
53 static const char* usage =
54         "Usage: %s [options] package-file\n"
55         "\n"
56         "options:\n"
57         "  -h, --help            prints this message and exit\n"
58         "  -D, --dev name        Trusty device name\n"
59         "\n";
60 
print_usage_and_exit(const char * prog,int code)61 static void print_usage_and_exit(const char* prog, int code) {
62     fprintf(stderr, usage, prog);
63     exit(code);
64 }
65 
parse_options(int argc,char ** argv)66 static void parse_options(int argc, char** argv) {
67     int c;
68     int oidx = 0;
69 
70     while (1) {
71         c = getopt_long(argc, argv, _sopts, _lopts, &oidx);
72         if (c == -1) {
73             break; /* done */
74         }
75 
76         switch (c) {
77             case 'h':
78                 print_usage_and_exit(argv[0], EXIT_SUCCESS);
79                 break;
80 
81             case 'D':
82                 dev_name = strdup(optarg);
83                 break;
84 
85             default:
86                 print_usage_and_exit(argv[0], EXIT_FAILURE);
87         }
88     }
89 }
90 
read_file(const char * file_name,off64_t * out_file_size)91 static unique_fd read_file(const char* file_name, off64_t* out_file_size) {
92     int rc;
93     long page_size = sysconf(_SC_PAGESIZE);
94     off64_t file_size, file_page_offset, file_page_size;
95     struct stat64 st;
96 
97     unique_fd file_fd(TEMP_FAILURE_RETRY(open(file_name, O_RDONLY)));
98     if (!file_fd.ok()) {
99         PLOG(ERROR) << "Error opening file " << file_name;
100         return {};
101     }
102 
103     rc = fstat64(file_fd, &st);
104     if (rc < 0) {
105         PLOG(ERROR) << "Error calling stat on file '" << file_name << "'";
106         return {};
107     }
108 
109     assert(st.st_size >= 0);
110     file_size = st.st_size;
111 
112     /* The dmabuf size needs to be a multiple of the page size */
113     file_page_offset = file_size & (page_size - 1);
114     if (file_page_offset) {
115         file_page_offset = page_size - file_page_offset;
116     }
117     if (__builtin_add_overflow(file_size, file_page_offset, &file_page_size)) {
118         LOG(ERROR) << "Failed to page-align file size";
119         return {};
120     }
121 
122     BufferAllocator alloc;
123     unique_fd dmabuf_fd(alloc.Alloc(kDmabufSystemHeapName, file_page_size));
124     if (!dmabuf_fd.ok()) {
125         LOG(ERROR) << "Error creating dmabuf: " << dmabuf_fd.get();
126         return dmabuf_fd;
127     }
128 
129     void* shm = mmap(0, file_page_size, PROT_READ | PROT_WRITE, MAP_SHARED, dmabuf_fd, 0);
130     if (shm == MAP_FAILED) {
131         return {};
132     }
133 
134     off64_t file_offset = 0;
135     while (file_offset < file_size) {
136         ssize_t num_read = TEMP_FAILURE_RETRY(
137                 pread(file_fd, (char*)shm + file_offset, file_size - file_offset, file_offset));
138 
139         if (num_read < 0) {
140             PLOG(ERROR) << "Error reading package file '" << file_name << "'";
141             break;
142         }
143 
144         if (num_read == 0) {
145             LOG(ERROR) << "Unexpected end of file '" << file_name << "'";
146             break;
147         }
148 
149         file_offset += (off64_t)num_read;
150     }
151 
152     munmap(shm, file_page_size);
153 
154     if (file_offset < file_size) {
155         return {};
156     }
157 
158     assert(file_offset == file_size);
159     if (out_file_size) {
160         *out_file_size = file_size;
161     }
162 
163     return dmabuf_fd;
164 }
165 
send_load_message(int tipc_fd,int package_fd,off64_t package_size)166 static ssize_t send_load_message(int tipc_fd, int package_fd, off64_t package_size) {
167     struct apploader_header hdr = {
168             .cmd = APPLOADER_CMD_LOAD_APPLICATION,
169     };
170     struct apploader_load_app_req req = {
171             .package_size = static_cast<uint64_t>(package_size),
172     };
173     struct iovec tx[2] = {{&hdr, sizeof(hdr)}, {&req, sizeof(req)}};
174     struct trusty_shm shm = {
175             .fd = package_fd,
176             .transfer = TRUSTY_SHARE,
177     };
178     return tipc_send(tipc_fd, tx, 2, &shm, 1);
179 }
180 
read_response(int tipc_fd)181 static ssize_t read_response(int tipc_fd) {
182     struct apploader_resp resp;
183     ssize_t rc = read(tipc_fd, &resp, sizeof(resp));
184     if (rc < 0) {
185         PLOG(ERROR) << "Failed to read response";
186         return rc;
187     }
188 
189     if (rc < sizeof(resp)) {
190         LOG(ERROR) << "Not enough data in response: " << rc;
191         return -EIO;
192     }
193 
194     if (resp.hdr.cmd != (APPLOADER_CMD_LOAD_APPLICATION | APPLOADER_RESP_BIT)) {
195         LOG(ERROR) << "Invalid command in response: " << resp.hdr.cmd;
196         return -EINVAL;
197     }
198 
199     switch (resp.error) {
200         case APPLOADER_NO_ERROR:
201             break;
202         case APPLOADER_ERR_UNKNOWN_CMD:
203             LOG(ERROR) << "Error: unknown command";
204             break;
205         case APPLOADER_ERR_INVALID_CMD:
206             LOG(ERROR) << "Error: invalid command arguments";
207             break;
208         case APPLOADER_ERR_NO_MEMORY:
209             LOG(ERROR) << "Error: out of Trusty memory";
210             break;
211         case APPLOADER_ERR_VERIFICATION_FAILED:
212             LOG(ERROR) << "Error: failed to verify the package";
213             break;
214         case APPLOADER_ERR_LOADING_FAILED:
215             LOG(ERROR) << "Error: failed to load the package";
216             break;
217         case APPLOADER_ERR_ALREADY_EXISTS:
218             LOG(ERROR) << "Error: application already exists";
219             break;
220         case APPLOADER_ERR_INTERNAL:
221             LOG(ERROR) << "Error: internal apploader error";
222             break;
223         case APPLOADER_ERR_INVALID_VERSION:
224             LOG(ERROR) << "Error: invalid application version";
225             break;
226         case APPLOADER_ERR_POLICY_VIOLATION:
227             LOG(ERROR) << "Error: loading denied by policy engine";
228             break;
229         case APPLOADER_ERR_NOT_ENCRYPTED:
230             LOG(ERROR) << "Error: unmet application encryption requirement";
231             break;
232         default:
233             LOG(ERROR) << "Unrecognized error: " << resp.error;
234             break;
235     }
236 
237     return static_cast<ssize_t>(resp.error);
238 }
239 
send_app_package(const char * package_file_name)240 static ssize_t send_app_package(const char* package_file_name) {
241     ssize_t rc = 0;
242     int tipc_fd = -1;
243     off64_t package_size;
244 
245     unique_fd package_fd = read_file(package_file_name, &package_size);
246     if (!package_fd.ok()) {
247         rc = -1;
248         goto err_read_file;
249     }
250 
251     tipc_fd = tipc_connect(dev_name, APPLOADER_PORT);
252     if (tipc_fd < 0) {
253         LOG(ERROR) << "Failed to connect to Trusty app loader: " << strerror(-tipc_fd);
254         // print this to stderr too to avoid silently exiting when run as non-root
255         fprintf(stderr, "Failed to connect to Trusty app loader: %s\n", strerror(-tipc_fd));
256         rc = tipc_fd;
257         goto err_tipc_connect;
258     }
259 
260     rc = send_load_message(tipc_fd, package_fd, package_size);
261     if (rc < 0) {
262         LOG(ERROR) << "Failed to send package: " << rc;
263         goto err_send;
264     }
265 
266     rc = read_response(tipc_fd);
267 
268 err_send:
269     tipc_close(tipc_fd);
270 err_tipc_connect:
271 err_read_file:
272     return rc;
273 }
274 
main(int argc,char ** argv)275 int main(int argc, char** argv) {
276     parse_options(argc, argv);
277     if (optind + 1 != argc) {
278         print_usage_and_exit(argv[0], EXIT_FAILURE);
279     }
280 
281     int rc = send_app_package(argv[optind]);
282     return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
283 }
284