chiark / gitweb /
locale: unify some code between fedora and altlinux
[elogind.git] / src / cryptsetup.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <string.h>
23 #include <errno.h>
24 #include <sys/mman.h>
25
26 #include <libcryptsetup.h>
27 #include <libudev.h>
28
29 #include "log.h"
30 #include "util.h"
31 #include "ask-password-api.h"
32
33 static const char *opt_type = NULL; /* LUKS1 or PLAIN */
34 static char *opt_cipher = NULL;
35 static unsigned opt_key_size = 0;
36 static char *opt_hash = NULL;
37 static unsigned opt_tries = 0;
38 static bool opt_readonly = false;
39 static bool opt_verify = false;
40 static usec_t opt_timeout = 0;
41
42 /* Options Debian's crypttab knows we don't:
43
44     offset=
45     skip=
46     precheck=
47     check=
48     checkargs=
49     noearly=
50     loud=
51     keyscript=
52 */
53
54 static int parse_one_option(const char *option) {
55         assert(option);
56
57         /* Handled outside of this tool */
58         if (streq(option, "noauto"))
59                 return 0;
60
61         if (startswith(option, "cipher=")) {
62                 char *t;
63
64                 if (!(t = strdup(option+7)))
65                         return -ENOMEM;
66
67                 free(opt_cipher);
68                 opt_cipher = t;
69
70         } else if (startswith(option, "size=")) {
71
72                 if (safe_atou(option+5, &opt_key_size) < 0) {
73                         log_error("size= parse failure, ignoring.");
74                         return 0;
75                 }
76
77         } else if (startswith(option, "hash=")) {
78                 char *t;
79
80                 if (!(t = strdup(option+5)))
81                         return -ENOMEM;
82
83                 free(opt_hash);
84                 opt_hash = t;
85
86         } else if (startswith(option, "tries=")) {
87
88                 if (safe_atou(option+6, &opt_tries) < 0) {
89                         log_error("tries= parse failure, ignoring.");
90                         return 0;
91                 }
92
93         } else if (streq(option, "readonly"))
94                 opt_readonly = true;
95         else if (streq(option, "verify"))
96                 opt_verify = true;
97         else if (streq(option, "luks"))
98                 opt_type = CRYPT_LUKS1;
99         else if (streq(option, "plain") ||
100                  streq(option, "swap") ||
101                  streq(option, "tmp"))
102                 opt_type = CRYPT_PLAIN;
103         else if (startswith(option, "timeout=")) {
104
105                 if (parse_usec(option+8, &opt_timeout) < 0) {
106                         log_error("timeout= parse failure, ignoring.");
107                         return 0;
108                 }
109
110         } else
111                 log_error("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
112
113         return 0;
114 }
115
116 static int parse_options(const char *options) {
117         char *state;
118         char *w;
119         size_t l;
120
121         assert(options);
122
123         FOREACH_WORD_SEPARATOR(w, l, options, ",", state) {
124                 char *o;
125                 int r;
126
127                 if (!(o = strndup(w, l)))
128                         return -ENOMEM;
129
130                 r = parse_one_option(o);
131                 free(o);
132
133                 if (r < 0)
134                         return r;
135         }
136
137         return 0;
138 }
139
140 static void log_glue(int level, const char *msg, void *usrptr) {
141         log_debug("%s", msg);
142 }
143
144 static char *disk_description(const char *path) {
145         struct udev *udev = NULL;
146         struct udev_device *device = NULL;
147         struct stat st;
148         char *description = NULL;
149         const char *model;
150
151         assert(path);
152
153         if (stat(path, &st) < 0)
154                 return NULL;
155
156         if (!S_ISBLK(st.st_mode))
157                 return NULL;
158
159         if (!(udev = udev_new()))
160                 return NULL;
161
162         if (!(device = udev_device_new_from_devnum(udev, 'b', st.st_rdev)))
163                 goto finish;
164
165         if ((model = udev_device_get_property_value(device, "ID_MODEL_FROM_DATABASE")) ||
166             (model = udev_device_get_property_value(device, "ID_MODEL")))
167                 description = strdup(model);
168
169 finish:
170         if (device)
171                 udev_device_unref(device);
172
173         if (udev)
174                 udev_unref(udev);
175
176         return description;
177 }
178
179 int main(int argc, char *argv[]) {
180         int r = EXIT_FAILURE;
181         struct crypt_device *cd = NULL;
182         char *password = NULL, *truncated_cipher = NULL;
183         const char *cipher = NULL, *cipher_mode = NULL, *hash = NULL, *name = NULL;
184         char *description = NULL;
185
186         if (argc < 3) {
187                 log_error("This program requires at least two arguments.");
188                 return EXIT_FAILURE;
189         }
190
191         log_set_target(LOG_TARGET_AUTO);
192         log_parse_environment();
193         log_open();
194
195         if (streq(argv[1], "attach")) {
196                 uint32_t flags = 0;
197                 int k;
198                 unsigned try;
199                 const char *key_file = NULL;
200                 usec_t until;
201                 crypt_status_info status;
202
203                 if (argc < 4) {
204                         log_error("attach requires at least two arguments.");
205                         goto finish;
206                 }
207
208                 if (argc >= 5 &&
209                     argv[4][0] &&
210                     !streq(argv[4], "-") &&
211                     !streq(argv[4], "none")) {
212
213                         if (!path_is_absolute(argv[4]))
214                                 log_error("Password file path %s is not absolute. Ignoring.", argv[4]);
215                         else
216                                 key_file = argv[4];
217                 }
218
219                 if (argc >= 6 && argv[5][0] && !streq(argv[5], "-"))
220                         parse_options(argv[5]);
221
222                 /* A delicious drop of snake oil */
223                 mlockall(MCL_FUTURE);
224
225                 description = disk_description(argv[3]);
226                 name = description ? description : argv[2];
227
228                 if ((k = crypt_init(&cd, argv[3]))) {
229                         log_error("crypt_init() failed: %s", strerror(-k));
230                         goto finish;
231                 }
232
233                 crypt_set_log_callback(cd, log_glue, NULL);
234
235                 status = crypt_status(cd, argv[2]);
236                 if (status == CRYPT_ACTIVE || status == CRYPT_BUSY) {
237                         log_info("Volume %s already active.", argv[2]);
238                         r = EXIT_SUCCESS;
239                         goto finish;
240                 }
241
242                 if (opt_readonly)
243                         flags |= CRYPT_ACTIVATE_READONLY;
244
245                 until = now(CLOCK_MONOTONIC) + (opt_timeout > 0 ? opt_timeout : 60 * USEC_PER_SEC);
246
247                 opt_tries = opt_tries > 0 ? opt_tries : 3;
248                 opt_key_size = (opt_key_size > 0 ? opt_key_size : 256);
249                 hash = opt_hash ? opt_hash : "ripemd160";
250
251                 if (opt_cipher) {
252                         size_t l;
253
254                         l = strcspn(opt_cipher, "-");
255
256                         if (!(truncated_cipher = strndup(opt_cipher, l))) {
257                                 log_error("Out of memory");
258                                 goto finish;
259                         }
260
261                         cipher = truncated_cipher;
262                         cipher_mode = opt_cipher[l] ? opt_cipher+l+1 : "plain";
263                 } else {
264                         cipher = "aes";
265                         cipher_mode = "cbc-essiv:sha256";
266                 }
267
268                 for (try = 0; try < opt_tries; try++) {
269                         bool pass_volume_key = false;
270
271                         free(password);
272                         password = NULL;
273
274                         if (!key_file) {
275                                 char *text;
276
277                                 if (asprintf(&text, "Please enter passphrase for disk %s!", name) < 0) {
278                                         log_error("Out of memory");
279                                         goto finish;
280                                 }
281
282                                 k = ask_password_auto(text, "drive-harddisk", until, &password);
283                                 free(text);
284
285                                 if (k < 0) {
286                                         log_error("Failed to query password: %s", strerror(-k));
287                                         goto finish;
288                                 }
289
290                                 if (opt_verify) {
291                                         char *password2 = NULL;
292
293                                         if (asprintf(&text, "Please enter passphrase for disk %s! (verification)", name) < 0) {
294                                                 log_error("Out of memory");
295                                                 goto finish;
296                                         }
297
298                                         k = ask_password_auto(text, "drive-harddisk", until, &password2);
299                                         free(text);
300
301                                         if (k < 0) {
302                                                 log_error("Failed to query verification password: %s", strerror(-k));
303                                                 goto finish;
304                                         }
305
306                                         if (!streq(password, password2)) {
307                                                 log_warning("Passwords did not match, retrying.");
308                                                 free(password2);
309                                                 continue;
310                                         }
311
312                                         free(password2);
313                                 }
314
315                                 if (strlen(password)+1 < opt_key_size) {
316                                         char *c;
317
318                                         /* Pad password if necessary */
319
320                                         if (!(c = new(char, opt_key_size))) {
321                                                 log_error("Out of memory.");
322                                                 goto finish;
323                                         }
324
325                                         strncpy(c, password, opt_key_size);
326                                         free(password);
327                                         password = c;
328                                 }
329                         }
330
331                         if (!opt_type || streq(opt_type, CRYPT_LUKS1))
332                                 k = crypt_load(cd, CRYPT_LUKS1, NULL);
333
334                         if ((!opt_type && k < 0) || streq_ptr(opt_type, CRYPT_PLAIN)) {
335                                 struct crypt_params_plain params;
336
337                                 zero(params);
338                                 params.hash = hash;
339
340                                 /* In contrast to what the name
341                                  * crypt_setup() might suggest this
342                                  * doesn't actually format anything,
343                                  * it just configures encryption
344                                  * parameters when used for plain
345                                  * mode. */
346                                 k = crypt_format(cd, CRYPT_PLAIN,
347                                                  cipher,
348                                                  cipher_mode,
349                                                  NULL,
350                                                  NULL,
351                                                  opt_key_size / 8,
352                                                  &params);
353
354                                 pass_volume_key = streq(hash, "plain");
355                         }
356
357                         if (k < 0) {
358                                 log_error("Loading of cryptographic parameters failed: %s", strerror(-k));
359                                 goto finish;
360                         }
361
362                         log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
363                                  crypt_get_cipher(cd),
364                                  crypt_get_cipher_mode(cd),
365                                  crypt_get_volume_key_size(cd)*8,
366                                  argv[3]);
367
368                         if (key_file)
369                                 k = crypt_activate_by_keyfile(cd, argv[2], CRYPT_ANY_SLOT, key_file, opt_key_size, flags);
370                         else if (pass_volume_key)
371                                 k = crypt_activate_by_volume_key(cd, argv[2], password, opt_key_size, flags);
372                         else
373                                 k = crypt_activate_by_passphrase(cd, argv[2], CRYPT_ANY_SLOT, password, strlen(password), flags);
374
375                         if (k >= 0)
376                                 break;
377
378                         if (k != -EPERM) {
379                                 log_error("Failed to activate: %s", strerror(-k));
380                                 goto finish;
381                         }
382
383                         log_warning("Invalid passphrase.");
384                 }
385
386                 if (try >= opt_tries) {
387                         log_error("Too many attempts.");
388                         r = EXIT_FAILURE;
389                         goto finish;
390                 }
391
392         } else if (streq(argv[1], "detach")) {
393                 int k;
394
395                 if ((k = crypt_init_by_name(&cd, argv[2]))) {
396                         log_error("crypt_init() failed: %s", strerror(-k));
397                         goto finish;
398                 }
399
400                 crypt_set_log_callback(cd, log_glue, NULL);
401
402                 if ((k = crypt_deactivate(cd, argv[2])) < 0) {
403                         log_error("Failed to deactivate: %s", strerror(-k));
404                         goto finish;
405                 }
406
407         } else {
408                 log_error("Unknown verb %s.", argv[1]);
409                 goto finish;
410         }
411
412         r = EXIT_SUCCESS;
413
414 finish:
415
416         if (cd)
417                 crypt_free(cd);
418
419         free(opt_cipher);
420         free(opt_hash);
421
422         free(truncated_cipher);
423
424         free(password);
425
426         free(description);
427
428         return r;
429 }