blob: 45c79f90b9427beacb11f2733fde6a3d3c31dd68 [file] [log] [blame]
bigbiffd58ba182020-03-23 10:02:29 -04001/*
2 * Copyright (C) 2014 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// This module creates a special filesystem containing two files.
18//
19// "/sideload/package.zip" appears to be a normal file, but reading
20// from it causes data to be fetched from the adb host. We can use
21// this to sideload packages over an adb connection without having to
22// store the entire package in RAM on the device.
23//
24// Because we may not trust the adb host, this filesystem maintains
25// the following invariant: each read of a given position returns the
26// same data as the first read at that position. That is, once a
27// section of the file is read, future reads of that section return
28// the same data. (Otherwise, a malicious adb host process could
29// return one set of bits when the package is read for signature
30// verification, and then different bits for when the package is
31// accessed by the installer.) If the adb host returns something
32// different than it did on the first read, the reader of the file
33// will see their read fail with EINVAL.
34//
35// The other file, "/sideload/exit", is used to control the subprocess
36// that creates this filesystem. Calling stat() on the exit file
37// causes the filesystem to be unmounted and the adb process on the
38// device shut down.
39//
40// Note that only the minimal set of file operations needed for these
41// two files is implemented. In particular, you can't opendir() or
42// readdir() on the "/sideload" directory; ls on it won't work.
43
44#include "fuse_sideload.h"
45
46#include <errno.h>
47#include <fcntl.h>
48#include <limits.h>
49#include "fuse.h"
50#include <pthread.h>
51#include <stdint.h>
52#include <stdio.h>
53#include <stdlib.h>
54#include <string.h>
55#include <sys/mount.h>
56#include <sys/param.h> // MIN
57#include <sys/stat.h>
58#include <sys/uio.h>
59#include <unistd.h>
60
61#ifdef USE_MINCRYPT
62#include "mincrypt/sha256.h"
63#define SHA256_DIGEST_LENGTH SHA256_DIGEST_SIZE
64#else
65#include <openssl/sha.h>
66#endif
67
68#include <array>
69#include <string>
70#include <vector>
71
72//#include <android-base/stringprintf.h>
73//#include <android-base/unique_fd.h>
74
75static constexpr uint64_t PACKAGE_FILE_ID = FUSE_ROOT_ID + 1;
76static constexpr uint64_t EXIT_FLAG_ID = FUSE_ROOT_ID + 2;
77
78static constexpr int NO_STATUS = 1;
79static constexpr int NO_STATUS_EXIT = 2;
80
81using SHA256Digest = std::array<uint8_t, SHA256_DIGEST_LENGTH>;
82
83#ifndef MIN
84#define MIN(a, b) ((a) < (b) ? (a) : (b))
85#endif
86
87struct fuse_data {
88 int ffd; // file descriptor for the fuse socket
89
90 provider_vtab vtab;
91
92 uint64_t file_size; // bytes
93
94 uint32_t block_size; // block size that the adb host is using to send the file to us
95 uint32_t file_blocks; // file size in block_size blocks
96
97 uid_t uid;
98 gid_t gid;
99
100 uint32_t curr_block; // cache the block most recently read from the host
101 uint8_t* block_data;
102
103 uint8_t* extra_block; // another block of storage for reads that span two blocks
104
105 uint8_t* hashes; // SHA-256 hash of each block (all zeros
106 // if block hasn't been read yet)
107};
108
109static void fuse_reply(const fuse_data* fd, uint64_t unique, const void* data, size_t len) {
110 fuse_out_header hdr;
111 hdr.len = len + sizeof(hdr);
112 hdr.error = 0;
113 hdr.unique = unique;
114
115 struct iovec vec[2];
116 vec[0].iov_base = &hdr;
117 vec[0].iov_len = sizeof(hdr);
118 vec[1].iov_base = const_cast<void*>(data);
119 vec[1].iov_len = len;
120
121 int res = writev(fd->ffd, vec, 2);
122 if (res == -1) {
123 printf("*** REPLY FAILED *** %s\n", strerror(errno));
124 }
125}
126
127static int handle_init(void* data, fuse_data* fd, const fuse_in_header* hdr) {
128 const fuse_init_in* req = static_cast<const fuse_init_in*>(data);
129
130 // Kernel 2.6.16 is the first stable kernel with struct fuse_init_out defined (fuse version 7.6).
131 // The structure is the same from 7.6 through 7.22. Beginning with 7.23, the structure increased
132 // in size and added new parameters.
133 if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
134 printf("Fuse kernel version mismatch: Kernel version %d.%d, Expected at least %d.6", req->major,
135 req->minor, FUSE_KERNEL_VERSION);
136 return -1;
137 }
138
139 fuse_init_out out;
140 out.minor = MIN(req->minor, FUSE_KERNEL_MINOR_VERSION);
141 size_t fuse_struct_size = sizeof(out);
142#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
143 /* FUSE_KERNEL_VERSION >= 23. */
144
145 // If the kernel only works on minor revs older than or equal to 22, then use the older structure
146 // size since this code only uses the 7.22 version of the structure.
147 if (req->minor <= 22) {
148 fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
149 }
150#endif
151
152 out.major = FUSE_KERNEL_VERSION;
153 out.max_readahead = req->max_readahead;
154 out.flags = 0;
155 out.max_background = 32;
156 out.congestion_threshold = 32;
157 out.max_write = 4096;
158 fuse_reply(fd, hdr->unique, &out, fuse_struct_size);
159
160 return NO_STATUS;
161}
162
163static void fill_attr(fuse_attr* attr, const fuse_data* fd, uint64_t nodeid, uint64_t size,
164 uint32_t mode) {
165 memset(attr, 0, sizeof(*attr));
166 attr->nlink = 1;
167 attr->uid = fd->uid;
168 attr->gid = fd->gid;
169 attr->blksize = 4096;
170
171 attr->ino = nodeid;
172 attr->size = size;
173 attr->blocks = (size == 0) ? 0 : (((size - 1) / attr->blksize) + 1);
174 attr->mode = mode;
175}
176
177static int handle_getattr(void* /* data */, const fuse_data* fd, const fuse_in_header* hdr) {
178 struct fuse_attr_out out;
179 memset(&out, 0, sizeof(out));
180 out.attr_valid = 10;
181
182 if (hdr->nodeid == FUSE_ROOT_ID) {
183 fill_attr(&(out.attr), fd, hdr->nodeid, 4096, S_IFDIR | 0555);
184 } else if (hdr->nodeid == PACKAGE_FILE_ID) {
185 fill_attr(&(out.attr), fd, PACKAGE_FILE_ID, fd->file_size, S_IFREG | 0444);
186 } else if (hdr->nodeid == EXIT_FLAG_ID) {
187 fill_attr(&(out.attr), fd, EXIT_FLAG_ID, 0, S_IFREG | 0);
188 } else {
189 return -ENOENT;
190 }
191
192 fuse_reply(fd, hdr->unique, &out, sizeof(out));
193 return (hdr->nodeid == EXIT_FLAG_ID) ? NO_STATUS_EXIT : NO_STATUS;
194}
195
196static int handle_lookup(void* data, const fuse_data* fd, const fuse_in_header* hdr) {
197 if (data == nullptr) return -ENOENT;
198
199 struct fuse_entry_out out;
200 memset(&out, 0, sizeof(out));
201 out.entry_valid = 10;
202 out.attr_valid = 10;
203
204 std::string filename(static_cast<const char*>(data));
205 if (filename == FUSE_SIDELOAD_HOST_FILENAME) {
206 out.nodeid = PACKAGE_FILE_ID;
207 out.generation = PACKAGE_FILE_ID;
208 fill_attr(&(out.attr), fd, PACKAGE_FILE_ID, fd->file_size, S_IFREG | 0444);
209 } else if (filename == FUSE_SIDELOAD_HOST_EXIT_FLAG) {
210 out.nodeid = EXIT_FLAG_ID;
211 out.generation = EXIT_FLAG_ID;
212 fill_attr(&(out.attr), fd, EXIT_FLAG_ID, 0, S_IFREG | 0);
213 } else {
214 return -ENOENT;
215 }
216
217 fuse_reply(fd, hdr->unique, &out, sizeof(out));
218 return (out.nodeid == EXIT_FLAG_ID) ? NO_STATUS_EXIT : NO_STATUS;
219}
220
221static int handle_open(void* /* data */, const fuse_data* fd, const fuse_in_header* hdr) {
222 if (hdr->nodeid == EXIT_FLAG_ID) return -EPERM;
223 if (hdr->nodeid != PACKAGE_FILE_ID) return -ENOENT;
224
225 struct fuse_open_out out;
226 memset(&out, 0, sizeof(out));
227 out.fh = 10; // an arbitrary number; we always use the same handle
228 fuse_reply(fd, hdr->unique, &out, sizeof(out));
229 return NO_STATUS;
230}
231
232static int handle_flush(void* /* data */, fuse_data* /* fd */, const fuse_in_header* /* hdr */) {
233 return 0;
234}
235
236static int handle_release(void* /* data */, fuse_data* /* fd */, const fuse_in_header* /* hdr */) {
237 return 0;
238}
239
240// Fetch a block from the host into fd->curr_block and fd->block_data.
241// Returns 0 on successful fetch, negative otherwise.
242static int fetch_block(fuse_data* fd, uint32_t block) {
243 if (block == fd->curr_block) {
244 return 0;
245 }
246
247 if (block >= fd->file_blocks) {
248 memset(fd->block_data, 0, fd->block_size);
249 fd->curr_block = block;
250 return 0;
251 }
252
253 size_t fetch_size = fd->block_size;
254 if (block * fd->block_size + fetch_size > fd->file_size) {
255 // If we're reading the last (partial) block of the file, expect a shorter response from the
256 // host, and pad the rest of the block with zeroes.
257 fetch_size = fd->file_size - (block * fd->block_size);
258 memset(fd->block_data + fetch_size, 0, fd->block_size - fetch_size);
259 }
260
261 int result = fd->vtab.read_block(block, fd->block_data, fetch_size);
262 if (result < 0) return result;
263
264 fd->curr_block = block;
265
266 // Verify the hash of the block we just got from the host.
267 //
268 // - If the hash of the just-received data matches the stored hash for the block, accept it.
269 // - If the stored hash is all zeroes, store the new hash and accept the block (this is the first
270 // time we've read this block).
271 // - Otherwise, return -EINVAL for the read.
272
273 uint8_t hash[SHA256_DIGEST_LENGTH];
274#ifdef USE_MINCRYPT
275 SHA256_hash(fd->block_data, fd->block_size, hash);
276#else
277 SHA256(fd->block_data, fd->block_size, hash);
278#endif
279 uint8_t* blockhash = fd->hashes + block * SHA256_DIGEST_LENGTH;
280 if (memcmp(hash, blockhash, SHA256_DIGEST_LENGTH) == 0) {
281 return 0;
282 }
283
284 int i;
285 for (i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
286 if (blockhash[i] != 0) {
287 fd->curr_block = -1;
288 return -EIO;
289 }
290 }
291
292 memcpy(blockhash, hash, SHA256_DIGEST_LENGTH);
293 return 0;
294}
295
296static int handle_read(void* data, fuse_data* fd, const fuse_in_header* hdr) {
297 if (hdr->nodeid != PACKAGE_FILE_ID) return -ENOENT;
298
299 const fuse_read_in* req = static_cast<const fuse_read_in*>(data);
300 uint64_t offset = req->offset;
301 uint32_t size = req->size;
302
303 // The docs on the fuse kernel interface are vague about what to do when a read request extends
304 // past the end of the file. We can return a short read -- the return structure does include a
305 // length field -- but in testing that caused the program using the file to segfault. (I
306 // speculate that this is due to the reading program accessing it via mmap; maybe mmap dislikes
307 // when you return something short of a whole page?) To fix this we zero-pad reads that extend
308 // past the end of the file so we're always returning exactly as many bytes as were requested.
309 // (Users of the mapped file have to know its real length anyway.)
310
311 fuse_out_header outhdr;
312 outhdr.len = sizeof(outhdr) + size;
313 outhdr.error = 0;
314 outhdr.unique = hdr->unique;
315
316 struct iovec vec[3];
317 vec[0].iov_base = &outhdr;
318 vec[0].iov_len = sizeof(outhdr);
319
320 uint32_t block = offset / fd->block_size;
321 int result = fetch_block(fd, block);
322 if (result != 0) return result;
323
324 // Two cases:
325 //
326 // - the read request is entirely within this block. In this case we can reply immediately.
327 //
328 // - the read request goes over into the next block. Note that since we mount the filesystem
329 // with max_read=block_size, a read can never span more than two blocks. In this case we copy
330 // the block to extra_block and issue a fetch for the following block.
331
332 uint32_t block_offset = offset - (block * fd->block_size);
333
334 int vec_used;
335 if (size + block_offset <= fd->block_size) {
336 // First case: the read fits entirely in the first block.
337
338 vec[1].iov_base = fd->block_data + block_offset;
339 vec[1].iov_len = size;
340 vec_used = 2;
341 } else {
342 // Second case: the read spills over into the next block.
343
344 memcpy(fd->extra_block, fd->block_data + block_offset, fd->block_size - block_offset);
345 vec[1].iov_base = fd->extra_block;
346 vec[1].iov_len = fd->block_size - block_offset;
347
348 result = fetch_block(fd, block + 1);
349 if (result != 0) return result;
350 vec[2].iov_base = fd->block_data;
351 vec[2].iov_len = size - vec[1].iov_len;
352 vec_used = 3;
353 }
354
355 if (writev(fd->ffd, vec, vec_used) == -1) {
356 printf("*** READ REPLY FAILED: %s ***\n", strerror(errno));
357 }
358 return NO_STATUS;
359}
360
361int run_fuse_sideload(const provider_vtab& vtab, uint64_t file_size, uint32_t block_size,
362 const char* mount_point) {
363 // If something's already mounted on our mountpoint, try to remove it. (Mostly in case of a
364 // previous abnormal exit.)
365 umount2(mount_point, MNT_FORCE);
366
367 // fs/fuse/inode.c in kernel code uses the greater of 4096 and the passed-in max_read.
368 if (block_size < 4096) {
369 fprintf(stderr, "block size (%u) is too small\n", block_size);
370 return -1;
371 }
372 if (block_size > (1 << 22)) { // 4 MiB
373 fprintf(stderr, "block size (%u) is too large\n", block_size);
374 return -1;
375 }
376
377 fuse_data fd;
378 memset(&fd, 0, sizeof(fd));
379 fd.vtab = vtab;
380 fd.file_size = file_size;
381 fd.block_size = block_size;
382 fd.file_blocks = (file_size == 0) ? 0 : (((file_size - 1) / block_size) + 1);
383
384 int result;
385 if (fd.file_blocks > (1 << 18)) {
386 fprintf(stderr, "file has too many blocks (%u)\n", fd.file_blocks);
387 result = -1;
388 goto done;
389 }
390
391 fd.hashes = (uint8_t*)calloc(fd.file_blocks, SHA256_DIGEST_LENGTH);
392 if (fd.hashes == NULL) {
393 fprintf(stderr, "failed to allocate %d bites for hashes\n",
394 fd.file_blocks * SHA256_DIGEST_LENGTH);
395 result = -1;
396 goto done;
397 }
398
399 fd.uid = getuid();
400 fd.gid = getgid();
401
402 fd.curr_block = -1;
403 fd.block_data = static_cast<uint8_t*>(malloc(block_size));
404 if (fd.block_data == nullptr) {
405 fprintf(stderr, "failed to allocate %d bites for block_data\n", block_size);
406 result = -1;
407 goto done;
408 }
409 fd.extra_block = static_cast<uint8_t*>(malloc(block_size));
410 if (fd.extra_block == nullptr) {
411 fprintf(stderr, "failed to allocate %d bites for extra_block\n", block_size);
412 result = -1;
413 goto done;
414 }
415
416 fd.ffd = open("/dev/fuse", O_RDWR);
417 if (!fd.ffd) {
418 perror("open /dev/fuse");
419 result = -1;
420 goto done;
421 }
422
423 {
424 char opts[256];
425 snprintf(opts, sizeof(opts),
426 ("fd=%d,user_id=%d,group_id=%d,max_read=%u,"
427 "allow_other,rootmode=040000"),
428 fd.ffd, fd.uid, fd.gid, block_size);
429
430 result = mount("/dev/fuse", FUSE_SIDELOAD_HOST_MOUNTPOINT, "fuse",
431 MS_NOSUID | MS_NODEV | MS_RDONLY | MS_NOEXEC, opts);
432 if (result < 0) {
433 perror("mount");
434 goto done;
435 }
436 }
437
438 uint8_t request_buffer[sizeof(fuse_in_header) + PATH_MAX * 8];
439 for (;;) {
440 ssize_t len = TEMP_FAILURE_RETRY(read(fd.ffd, request_buffer, sizeof(request_buffer)));
441 if (len == -1) {
442 perror("read request");
443 if (errno == ENODEV) {
444 result = -1;
445 break;
446 }
447 continue;
448 }
449
450 if (static_cast<size_t>(len) < sizeof(fuse_in_header)) {
451 fprintf(stderr, "request too short: len=%zd\n", len);
452 continue;
453 }
454
455 fuse_in_header* hdr = reinterpret_cast<fuse_in_header*>(request_buffer);
456 void* data = request_buffer + sizeof(fuse_in_header);
457
458 result = -ENOSYS;
459
460 switch (hdr->opcode) {
461 case FUSE_INIT:
462 result = handle_init(data, &fd, hdr);
463 break;
464
465 case FUSE_LOOKUP:
466 result = handle_lookup(data, &fd, hdr);
467 break;
468
469 case FUSE_GETATTR:
470 result = handle_getattr(data, &fd, hdr);
471 break;
472
473 case FUSE_OPEN:
474 result = handle_open(data, &fd, hdr);
475 break;
476
477 case FUSE_READ:
478 result = handle_read(data, &fd, hdr);
479 break;
480
481 case FUSE_FLUSH:
482 result = handle_flush(data, &fd, hdr);
483 break;
484
485 case FUSE_RELEASE:
486 result = handle_release(data, &fd, hdr);
487 break;
488
489 default:
490 fprintf(stderr, "unknown fuse request opcode %d\n", hdr->opcode);
491 break;
492 }
493
494 if (result == NO_STATUS_EXIT) {
495 result = 0;
496 break;
497 }
498
499 if (result != NO_STATUS) {
500 fuse_out_header outhdr;
501 outhdr.len = sizeof(outhdr);
502 outhdr.error = result;
503 outhdr.unique = hdr->unique;
504 TEMP_FAILURE_RETRY(write(fd.ffd, &outhdr, sizeof(outhdr)));
505 }
506 }
507
508done:
509 fd.vtab.close();
510
511 if (umount2(mount_point, MNT_DETACH) == -1) {
512 fprintf(stderr, "fuse_sideload umount failed: %s\n", strerror(errno));
513 }
514
515 free(fd.block_data);
516 free(fd.extra_block);
517
518 return result;
519}
520
521extern "C" int run_old_fuse_sideload(const struct provider_vtab& vtab, void* cookie __unused,
522 uint64_t file_size, uint32_t block_size)
523{
524 return run_fuse_sideload(vtab, file_size, block_size, FUSE_SIDELOAD_HOST_MOUNTPOINT);
525}