summaryrefslogtreecommitdiff
path: root/ext4_utils/ext4_crypt_init_extensions.cpp
blob: 98da8f5c88f2df9ac722f1a443883d41de114669 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#include "ext4_crypt.h"

#include <string>
#include <fstream>
#include <iomanip>
#include <sstream>

#include <sys/mount.h>

#include <errno.h>
#include <sys/stat.h>
#include <cutils/properties.h>
#include <cutils/sockets.h>

// ext4enc:TODO Use include paths
#include "../../core/init/log.h"
#include "../../core/init/util.h"

#include "ext2fs/ext2_fs.h"

static const std::string unencrypted_path = "/unencrypted";
static const std::string keyring = "@s";
static const std::string arbitrary_sequence_number = "42";

static key_serial_t device_keyring = -1;

static std::string vold_command(std::string const& command)
{
    INFO("Running command %s\n", command.c_str());
    int sock = socket_local_client("vold",
                                   ANDROID_SOCKET_NAMESPACE_RESERVED,
                                   SOCK_STREAM);

    if (sock < 0) {
        INFO("Cannot open vold, failing command\n");
        return "";
    }

    class CloseSocket
    {
        int sock_;
    public:
        CloseSocket(int sock) : sock_(sock) {}
        ~CloseSocket() { close(sock_); }
    };

    CloseSocket cs(sock);

    // Use arbitrary sequence number. This should only be used when the
    // framework is down, so this is (mostly) OK.
    std::string actual_command = arbitrary_sequence_number + " " + command;
    if (write(sock, actual_command.c_str(), actual_command.size() + 1) < 0) {
        ERROR("Cannot write command\n");
        return "";
    }

    while (1) {
        struct timeval to;
        to.tv_sec = 10;
        to.tv_usec = 0;

        fd_set read_fds;
        FD_ZERO(&read_fds);
        FD_SET(sock, &read_fds);

        int rc = select(sock + 1, &read_fds, NULL, NULL, &to);
        if (rc < 0) {
            ERROR("Error in select %s\n", strerror(errno));
            return "";
        } else if (!rc) {
            ERROR("Timeout\n");
            return "";
        } else if (FD_ISSET(sock, &read_fds)) {
            char buffer[4096];
            memset(buffer, 0, sizeof(buffer));
            rc = read(sock, buffer, sizeof(buffer));
            if (rc <= 0) {
                if (rc == 0) {
                    ERROR("Lost connection to Vold - did it crash?\n");
                } else {
                    ERROR("Error reading data (%s)\n", strerror(errno));
                }
                return "";
            }

            // We don't truly know that this is the correct result. However,
            // since this will only be used when the framework is down,
            // it should be OK unless someone is running vdc at the same time.
            // Worst case we force a reboot in the very rare synchronization
            // error
            return std::string(buffer, rc);
        }
    }
}

int e4crypt_create_device_key(const char* dir)
{
    // Make sure folder exists. Use make_dir to set selinux permissions.
    INFO("Creating test device key\n");
    std::string path = std::string() + dir + unencrypted_path;
    if (make_dir(path.c_str(), 0700) && errno != EEXIST) {
        ERROR("Failed to create %s with error %s\n",
              path.c_str(), strerror(errno));
        return -1;
    }

    // Open key if it exists
    std::string key_path = path + "/key";
    std::ifstream key(key_path.c_str(), std::ifstream::binary);

    if (!key.good()) {
        // Create new key if it doesn't
        std::ofstream new_key(key_path.c_str(), std::ofstream::binary);
        if (!new_key) {
            ERROR("Failed to open %s\n", key_path.c_str());
            return -1;
        }

        std::ifstream urandom("/dev/urandom", std::ifstream::binary);
        if (!urandom) {
            ERROR("Failed to open /dev/urandom\n");
            return -1;
        }

        char key_material[32];
        urandom.read(key_material, 32);
        if (!urandom) {
            ERROR("Failed to read random bytes\n");
            return -1;
        }

        new_key.write(key_material, 32);
        if (!new_key) {
            ERROR("Failed to write key material");
            return -1;
        }
    }

    remove((std::string(dir) + "/ref").c_str());
    return 0;
}

int e4crypt_install_keyring()
{
    device_keyring = add_key("keyring",
                             "e4crypt",
                             0,
                             0,
                             KEY_SPEC_SESSION_KEYRING);

    if (device_keyring == -1) {
        ERROR("Failed to create keyring\n");
        return -1;
    }

    INFO("Keyring created wth id %d in process %d\n", device_keyring, getpid());

    // ext4enc:TODO set correct permissions
    long result = keyctl_setperm(device_keyring, 0x3f3f3f3f);
    if (result) {
        ERROR("KEYCTL_SETPERM failed with error %ld\n", result);
        return -1;
    }

    return 0;
}

int e4crypt_install_key(const char* dir)
{
    std::string path = std::string() + dir + unencrypted_path;

    // Open key if it exists
    std::string key_path = path + "/key";
    std::ifstream key(key_path.c_str(), std::ifstream::binary);
    if (!key.good()) {
        ERROR("Failed to open key %s\n", key_path.c_str());
        return -1;
    }

    char keyblob[256];
    key.read(keyblob, sizeof(keyblob));
    std::streamsize keyblob_size = key.gcount();
    if (keyblob_size <= 0) {
        ERROR("Failed to read key data\n");
        return -1;
    }

    // Get password to decrypt as needed
    if (e4crypt_non_default_key(dir)) {
        std::string result = vold_command("cryptfs getpw");
        // result is either
        // 200 0 -1
        // or
        // 200 0 {{sensitive}} 0001020304
        // where 0001020304 is hex encoding of password
        std::istringstream i(result);
        std::string bit;
        i >> bit;
        if (bit != "200") {
            ERROR("Expecting 200\n");
            return -1;
        }

        i >> bit;
        if (bit != arbitrary_sequence_number) {
            ERROR("Expecting %s\n", arbitrary_sequence_number.c_str());
            return -1;
        }

        i >> bit;
        if (bit != "{{sensitive}}") {
            INFO("Not encrypted\n");
            return -1;
        }

        i >> bit;
    }

    // Add key to keyring
    // ext4enc:TODO Include structure from somewhere sensible
    // MUST be in sync with ext4_crypto.c in kernel
    struct ext4_encryption_key {
            uint32_t mode;
            char raw[EXT4_MAX_KEY_SIZE];
            uint32_t size;
    };

    ext4_encryption_key ext4_key = {0, {0}, 0};
    memcpy(ext4_key.raw, keyblob, keyblob_size);
    ext4_key.size = keyblob_size;

    // ext4enc:TODO Use better reference not 1234567890
    key_serial_t key_id = add_key("logon", "ext4-key:1234567890",
                                  (void*)&ext4_key, sizeof(ext4_key),
                                  device_keyring);

    if (key_id == -1) {
        ERROR("Failed to insert key into keyring with error %s\n",
              strerror(errno));
        return -1;
    }

    INFO("Added key %d to keyring %d in process %d\n",
         key_id, device_keyring, getpid());

    // ext4enc:TODO set correct permissions
    long result = keyctl_setperm(key_id, 0x3f3f3f3f);
    if (result) {
        ERROR("KEYCTL_SETPERM failed with error %ld\n", result);
        return -1;
    }

    // Save reference to key so we can set policy later
    std::ofstream(path + "/ref") << "ext4-key:1234567890";
    return 0;
}

int e4crypt_set_directory_policy(const char* dir)
{
    // Only set policy on first level /data directories
    // ext4enc:TODO don't hard code /data/
    if (!dir || strncmp(dir, "/data/", 6) || strchr(dir + 6, '/')) {
        return 0;
    }

    std::ifstream ref_file("/data/unencrypted/ref");
    if (!ref_file) {
        ERROR("Cannot open key reference file\n");
        return -1;
    }

    std::string ref;
    std::getline(ref_file, ref);
    std::string policy = std::string() + keyring + "." + ref;
    INFO("Setting poliy %s\n", policy.c_str());
    if (do_policy_set(dir, policy.c_str())) {
        ERROR("Setting policy on %s failed!", dir);
        return -1;
    }

    return 0;
}