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