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#include <string>
18
19#include <stdio.h>
20#include <stdlib.h>
21#include <errno.h>
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <fcntl.h>
25#include <linux/fs.h>
26#include <linux/fiemap.h>
27
28#define LOG_TAG "secdiscard"
29#include "cutils/log.h"
30
31// Deliberately limit ourselves to wiping small files.
32#define MAX_WIPE_LENGTH 4096
33#define INIT_BUFFER_SIZE 2048
34
35static void usage(char *progname);
36static void destroy_key(const std::string &path);
37static int file_device_range(const std::string &path, uint64_t range[2]);
38static int open_block_device_for_path(const std::string &path);
39static int read_file_as_string_atomically(const std::string &path, std::string &contents);
40static int find_block_device_for_path(
41    const std::string &mounts,
42    const std::string &path,
43    std::string &block_device);
44
45int main(int argc, char **argv) {
46    if (argc != 2 || argv[1][0] != '/') {
47        usage(argv[0]);
48        return -1;
49    }
50    SLOGD("Running: %s %s", argv[0], argv[1]);
51    std::string target(argv[1]);
52    destroy_key(target);
53    if (unlink(argv[1]) != 0 && errno != ENOENT) {
54        SLOGE("Unable to delete %s: %s",
55            argv[1], strerror(errno));
56        return -1;
57    }
58    return 0;
59}
60
61static void usage(char *progname) {
62    fprintf(stderr, "Usage: %s <absolute path>\n", progname);
63}
64
65// BLKSECDISCARD all content in "path", if it's small enough.
66static void destroy_key(const std::string &path) {
67    uint64_t range[2];
68    if (file_device_range(path, range) < 0) {
69        return;
70    }
71    int fs_fd = open_block_device_for_path(path);
72    if (fs_fd < 0) {
73        return;
74    }
75    if (ioctl(fs_fd, BLKSECDISCARD, range) != 0) {
76        SLOGE("Unable to BLKSECDISCARD %s: %s", path.c_str(), strerror(errno));
77        close(fs_fd);
78        return;
79    }
80    close(fs_fd);
81    SLOGD("Discarded %s", path.c_str());
82}
83
84// Find a short range that completely covers the file.
85// If there isn't one, return -1, otherwise 0.
86static int file_device_range(const std::string &path, uint64_t range[2])
87{
88    int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
89    if (fd < 0) {
90        if (errno == ENOENT) {
91            SLOGD("Unable to open %s: %s", path.c_str(), strerror(errno));
92        } else {
93            SLOGE("Unable to open %s: %s", path.c_str(), strerror(errno));
94        }
95        return -1;
96    }
97    alignas(struct fiemap) char fiemap_buffer[offsetof(struct fiemap, fm_extents[1])];
98    memset(fiemap_buffer, 0, sizeof(fiemap_buffer));
99    struct fiemap *fiemap = (struct fiemap *)fiemap_buffer;
100    fiemap->fm_start = 0;
101    fiemap->fm_length = UINT64_MAX;
102    fiemap->fm_flags = 0;
103    fiemap->fm_extent_count = 1;
104    fiemap->fm_mapped_extents = 0;
105    if (ioctl(fd, FS_IOC_FIEMAP, fiemap) != 0) {
106        SLOGE("Unable to FIEMAP %s: %s", path.c_str(), strerror(errno));
107        close(fd);
108        return -1;
109    }
110    close(fd);
111    if (fiemap->fm_mapped_extents != 1) {
112        SLOGE("Expecting one extent, got %d in %s", fiemap->fm_mapped_extents, path.c_str());
113        return -1;
114    }
115    struct fiemap_extent *extent = &fiemap->fm_extents[0];
116    if (!(extent->fe_flags & FIEMAP_EXTENT_LAST)) {
117        SLOGE("First extent was not the last in %s", path.c_str());
118        return -1;
119    }
120    if (extent->fe_flags &
121            (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC | FIEMAP_EXTENT_NOT_ALIGNED)) {
122        SLOGE("Extent has unexpected flags %ulx: %s", extent->fe_flags, path.c_str());
123        return -1;
124    }
125    if (extent->fe_length > MAX_WIPE_LENGTH) {
126        SLOGE("Extent too big, %llu bytes in %s", extent->fe_length, path.c_str());
127        return -1;
128    }
129    range[0] = extent->fe_physical;
130    range[1] = extent->fe_length;
131    return 0;
132}
133
134// Given a file path, look for the corresponding
135// block device in /proc/mounts and open it.
136static int open_block_device_for_path(const std::string &path)
137{
138    std::string mountsfile("/proc/mounts");
139    std::string mounts;
140    if (read_file_as_string_atomically(mountsfile, mounts) < 0) {
141        return -1;
142    }
143    std::string block_device;
144    if (find_block_device_for_path(mounts, path, block_device) < 0) {
145        return -1;
146    }
147    SLOGD("For path %s block device is %s", path.c_str(), block_device.c_str());
148    int res = open(block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC);
149    if (res < 0) {
150        SLOGE("Failed to open device %s: %s", block_device.c_str(), strerror(errno));
151        return -1;
152    }
153    return res;
154}
155
156// Read a file into a buffer in a single gulp, for atomicity.
157// Null-terminate the buffer.
158// Retry until the buffer is big enough.
159static int read_file_as_string_atomically(const std::string &path, std::string &contents)
160{
161    ssize_t buffer_size = INIT_BUFFER_SIZE;
162    while (true) {
163        int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
164        if (fd < 0) {
165            SLOGE("Failed to open %s: %s", path.c_str(), strerror(errno));
166            return -1;
167        }
168        contents.resize(buffer_size);
169        ssize_t read_size = read(fd, &contents[0], buffer_size);
170        if (read_size < 0) {
171            SLOGE("Failed to read from %s: %s", path.c_str(), strerror(errno));
172            close(fd);
173            return -1;
174        }
175        close(fd);
176        if (read_size < buffer_size) {
177            contents.resize(read_size);
178            return 0;
179        }
180        SLOGD("%s too big for buffer of size %zu", path.c_str(), buffer_size);
181        buffer_size <<= 1;
182    }
183}
184
185// Search a string representing the contents of /proc/mounts
186// for the mount point of a particular file by prefix matching
187// and return the corresponding block device.
188static int find_block_device_for_path(
189    const std::string &mounts,
190    const std::string &path,
191    std::string &block_device)
192{
193    auto line_begin = mounts.begin();
194    size_t best_prefix = 0;
195    std::string::const_iterator line_end;
196    while (line_begin != mounts.end()) {
197        line_end = std::find(line_begin, mounts.end(), '\n');
198        if (line_end == mounts.end()) {
199            break;
200        }
201        auto device_end = std::find(line_begin, line_end, ' ');
202        if (device_end == line_end) {
203            break;
204        }
205        auto mountpoint_begin = device_end + 1;
206        auto mountpoint_end = std::find(mountpoint_begin, line_end, ' ');
207        if (mountpoint_end == line_end) {
208            break;
209        }
210        if (std::find(line_begin, mountpoint_end, '\\') != mountpoint_end) {
211            // We don't correctly handle escape sequences, and we don't expect
212            // to encounter any, so fail if we do.
213            break;
214        }
215        size_t mountpoint_len = mountpoint_end - mountpoint_begin;
216        if (mountpoint_len > best_prefix &&
217                mountpoint_len < path.length() &&
218                path[mountpoint_len] == '/' &&
219                std::equal(mountpoint_begin, mountpoint_end, path.begin())) {
220            block_device = std::string(line_begin, device_end);
221            best_prefix = mountpoint_len;
222        }
223        line_begin = line_end + 1;
224    }
225    // All of the "break"s above are fatal parse errors.
226    if (line_begin != mounts.end()) {
227        auto bad_line = std::string(line_begin, line_end);
228        SLOGE("Unable to parse line in %s: %s", path.c_str(), bad_line.c_str());
229        return -1;
230    }
231    if (best_prefix == 0) {
232        SLOGE("No prefix found for path: %s", path.c_str());
233        return -1;
234    }
235    return 0;
236}
237