ext4_crypt_init_extensions.cpp revision ea2ec8875c9b024613d3ec5270bca6247c06d6bd
1#define TAG "ext4_utils"
2
3#include "ext4_crypt.h"
4
5#include <string>
6#include <fstream>
7#include <iomanip>
8#include <sstream>
9
10#include <errno.h>
11#include <sys/mount.h>
12#include <sys/stat.h>
13
14#include <cutils/klog.h>
15#include <cutils/properties.h>
16#include <cutils/sockets.h>
17#include <poll.h>
18
19#include "unencrypted_properties.h"
20
21// ext4enc:TODO Include structure from somewhere sensible
22// MUST be in sync with ext4_crypto.c in kernel
23#define EXT4_MAX_KEY_SIZE 76
24struct ext4_encryption_key {
25        uint32_t mode;
26        char raw[EXT4_MAX_KEY_SIZE];
27        uint32_t size;
28};
29
30static const std::string keyring = "@s";
31static const std::string arbitrary_sequence_number = "42";
32static const int vold_command_timeout_ms = 10 * 1000;
33
34static key_serial_t device_keyring = -1;
35
36static std::string vold_command(std::string const& command)
37{
38    KLOG_INFO(TAG, "Running command %s\n", command.c_str());
39    int sock = socket_local_client("vold",
40                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
41                                   SOCK_STREAM);
42
43    if (sock < 0) {
44        KLOG_INFO(TAG, "Cannot open vold, failing command\n");
45        return "";
46    }
47
48    class CloseSocket
49    {
50        int sock_;
51    public:
52        CloseSocket(int sock) : sock_(sock) {}
53        ~CloseSocket() { close(sock_); }
54    };
55
56    CloseSocket cs(sock);
57
58    // Use arbitrary sequence number. This should only be used when the
59    // framework is down, so this is (mostly) OK.
60    std::string actual_command = arbitrary_sequence_number + " " + command;
61    if (write(sock, actual_command.c_str(), actual_command.size() + 1) < 0) {
62        KLOG_ERROR(TAG, "Cannot write command\n");
63        return "";
64    }
65
66    struct pollfd poll_sock = {sock, POLLIN, 0};
67
68    int rc = poll(&poll_sock, 1, vold_command_timeout_ms);
69    if (rc < 0) {
70        KLOG_ERROR(TAG, "Error in poll %s\n", strerror(errno));
71        return "";
72    }
73    if (!(poll_sock.revents & POLLIN)) {
74        KLOG_ERROR(TAG, "Timeout\n");
75        return "";
76    }
77    char buffer[4096];
78    memset(buffer, 0, sizeof(buffer));
79    rc = read(sock, buffer, sizeof(buffer));
80    if (rc <= 0) {
81        if (rc == 0) {
82            KLOG_ERROR(TAG, "Lost connection to Vold - did it crash?\n");
83        } else {
84            KLOG_ERROR(TAG, "Error reading data (%s)\n", strerror(errno));
85        }
86        return "";
87    }
88
89    // We don't truly know that this is the correct result. However,
90    // since this will only be used when the framework is down,
91    // it should be OK unless someone is running vdc at the same time.
92    // Worst case we force a reboot in the very rare synchronization
93    // error
94    return std::string(buffer, rc);
95}
96
97int e4crypt_create_device_key(const char* dir,
98                              int ensure_dir_exists(const char*))
99{
100    // Make sure folder exists. Use make_dir to set selinux permissions.
101    KLOG_INFO(TAG, "Creating test device key\n");
102    UnencryptedProperties props(dir);
103    if (ensure_dir_exists(props.GetPath().c_str())) {
104        KLOG_ERROR(TAG, "Failed to create %s with error %s\n",
105                   props.GetPath().c_str(), strerror(errno));
106        return -1;
107    }
108
109    if (props.Get<std::string>(properties::key).empty()) {
110        // Create new key since it doesn't already exist
111        std::ifstream urandom("/dev/urandom", std::ifstream::binary);
112        if (!urandom) {
113            KLOG_ERROR(TAG, "Failed to open /dev/urandom\n");
114            return -1;
115        }
116
117        // ext4enc:TODO Don't hardcode 32
118        std::string key_material(32, '\0');
119        urandom.read(&key_material[0], key_material.length());
120        if (!urandom) {
121            KLOG_ERROR(TAG, "Failed to read random bytes\n");
122            return -1;
123        }
124
125        if (!props.Set(properties::key, key_material)) {
126            KLOG_ERROR(TAG, "Failed to write key material\n");
127            return -1;
128        }
129    }
130
131    if (!props.Remove(properties::ref)) {
132        KLOG_ERROR(TAG, "Failed to remove key ref\n");
133        return -1;
134    }
135
136    return 0;
137}
138
139int e4crypt_install_keyring()
140{
141    device_keyring = add_key("keyring",
142                             "e4crypt",
143                             0,
144                             0,
145                             KEY_SPEC_SESSION_KEYRING);
146
147    if (device_keyring == -1) {
148        KLOG_ERROR(TAG, "Failed to create keyring\n");
149        return -1;
150    }
151
152    KLOG_INFO(TAG, "Keyring created wth id %d in process %d\n",
153              device_keyring, getpid());
154
155    // ext4enc:TODO set correct permissions
156    long result = keyctl_setperm(device_keyring, 0x3f3f3f3f);
157    if (result) {
158        KLOG_ERROR(TAG, "KEYCTL_SETPERM failed with error %ld\n", result);
159        return -1;
160    }
161
162    return 0;
163}
164
165int e4crypt_install_key(const char* dir)
166{
167    UnencryptedProperties props(dir);
168    auto key = props.Get<std::string>(properties::key);
169
170    // Get password to decrypt as needed
171    if (e4crypt_non_default_key(dir)) {
172        std::string result = vold_command("cryptfs getpw");
173        // result is either
174        // 200 0 -1
175        // or
176        // 200 0 {{sensitive}} 0001020304
177        // where 0001020304 is hex encoding of password
178        std::istringstream i(result);
179        std::string bit;
180        i >> bit;
181        if (bit != "200") {
182            KLOG_ERROR(TAG, "Expecting 200\n");
183            return -1;
184        }
185
186        i >> bit;
187        if (bit != arbitrary_sequence_number) {
188            KLOG_ERROR(TAG, "Expecting %s\n", arbitrary_sequence_number.c_str());
189            return -1;
190        }
191
192        i >> bit;
193        if (bit != "{{sensitive}}") {
194            KLOG_INFO(TAG, "Not encrypted\n");
195            return -1;
196        }
197
198        i >> bit;
199    }
200
201    // Add key to keyring
202    ext4_encryption_key ext4_key = {0, {0}, 0};
203    if (key.length() > sizeof(ext4_key.raw)) {
204        KLOG_ERROR(TAG, "Key too long\n");
205        return -1;
206    }
207
208    ext4_key.mode = 0;
209    memcpy(ext4_key.raw, &key[0], key.length());
210    ext4_key.size = key.length();
211
212    // ext4enc:TODO Use better reference not 1234567890
213    key_serial_t key_id = add_key("logon", "ext4-key:1234567890",
214                                  (void*)&ext4_key, sizeof(ext4_key),
215                                  device_keyring);
216
217    if (key_id == -1) {
218        KLOG_ERROR(TAG, "Failed to insert key into keyring with error %s\n",
219                   strerror(errno));
220        return -1;
221    }
222
223    KLOG_INFO(TAG, "Added key %d to keyring %d in process %d\n",
224              key_id, device_keyring, getpid());
225
226    // ext4enc:TODO set correct permissions
227    long result = keyctl_setperm(key_id, 0x3f3f3f3f);
228    if (result) {
229        KLOG_ERROR(TAG, "KEYCTL_SETPERM failed with error %ld\n", result);
230        return -1;
231    }
232
233    // Save reference to key so we can set policy later
234    if (!props.Set(properties::ref, "ext4-key:1234567890")) {
235        KLOG_ERROR(TAG, "Cannot save key reference\n");
236        return -1;
237    }
238
239    return 0;
240}
241
242int e4crypt_set_directory_policy(const char* dir)
243{
244    // Only set policy on first level /data directories
245    // To make this less restrictive, consider using a policy file.
246    // However this is overkill for as long as the policy is simply
247    // to apply a global policy to all /data folders created via makedir
248    if (!dir || strncmp(dir, "/data/", 6) || strchr(dir + 6, '/')) {
249        return 0;
250    }
251
252    UnencryptedProperties props("/data");
253    std::string ref = props.Get<std::string>(properties::ref);
254    std::string policy = keyring + "." + ref;
255    KLOG_INFO(TAG, "Setting policy %s\n", policy.c_str());
256    int result = do_policy_set(dir, policy.c_str());
257    if (result) {
258        KLOG_ERROR(TAG, "Setting policy on %s failed!\n", dir);
259        return -1;
260    }
261
262    return 0;
263}
264