chiark / gitweb /
506ce9b5c9086bf3d4fec4cd0431affc5bc139ba
[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 #include <mntent.h>
26
27 #include <libcryptsetup.h>
28 #include <libudev.h>
29
30 #include "log.h"
31 #include "util.h"
32 #include "strv.h"
33 #include "ask-password-api.h"
34
35 static const char *opt_type = NULL; /* LUKS1 or PLAIN */
36 static char *opt_cipher = NULL;
37 static unsigned opt_key_size = 0;
38 static char *opt_hash = NULL;
39 static unsigned opt_tries = 0;
40 static bool opt_readonly = false;
41 static bool opt_verify = false;
42 static usec_t opt_timeout = 0;
43
44 /* Options Debian's crypttab knows we don't:
45
46     offset=
47     skip=
48     precheck=
49     check=
50     checkargs=
51     noearly=
52     loud=
53     keyscript=
54 */
55
56 static int parse_one_option(const char *option) {
57         assert(option);
58
59         /* Handled outside of this tool */
60         if (streq(option, "noauto"))
61                 return 0;
62
63         if (startswith(option, "cipher=")) {
64                 char *t;
65
66                 if (!(t = strdup(option+7)))
67                         return -ENOMEM;
68
69                 free(opt_cipher);
70                 opt_cipher = t;
71
72         } else if (startswith(option, "size=")) {
73
74                 if (safe_atou(option+5, &opt_key_size) < 0) {
75                         log_error("size= parse failure, ignoring.");
76                         return 0;
77                 }
78
79         } else if (startswith(option, "hash=")) {
80                 char *t;
81
82                 if (!(t = strdup(option+5)))
83                         return -ENOMEM;
84
85                 free(opt_hash);
86                 opt_hash = t;
87
88         } else if (startswith(option, "tries=")) {
89
90                 if (safe_atou(option+6, &opt_tries) < 0) {
91                         log_error("tries= parse failure, ignoring.");
92                         return 0;
93                 }
94
95         } else if (streq(option, "readonly"))
96                 opt_readonly = true;
97         else if (streq(option, "verify"))
98                 opt_verify = true;
99         else if (streq(option, "luks"))
100                 opt_type = CRYPT_LUKS1;
101         else if (streq(option, "plain") ||
102                  streq(option, "swap") ||
103                  streq(option, "tmp"))
104                 opt_type = CRYPT_PLAIN;
105         else if (startswith(option, "timeout=")) {
106
107                 if (parse_usec(option+8, &opt_timeout) < 0) {
108                         log_error("timeout= parse failure, ignoring.");
109                         return 0;
110                 }
111
112         } else
113                 log_error("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
114
115         return 0;
116 }
117
118 static int parse_options(const char *options) {
119         char *state;
120         char *w;
121         size_t l;
122
123         assert(options);
124
125         FOREACH_WORD_SEPARATOR(w, l, options, ",", state) {
126                 char *o;
127                 int r;
128
129                 if (!(o = strndup(w, l)))
130                         return -ENOMEM;
131
132                 r = parse_one_option(o);
133                 free(o);
134
135                 if (r < 0)
136                         return r;
137         }
138
139         return 0;
140 }
141
142 static void log_glue(int level, const char *msg, void *usrptr) {
143         log_debug("%s", msg);
144 }
145
146 static char *disk_description(const char *path) {
147         struct udev *udev = NULL;
148         struct udev_device *device = NULL;
149         struct stat st;
150         char *description = NULL;
151         const char *model;
152
153         assert(path);
154
155         if (stat(path, &st) < 0)
156                 return NULL;
157
158         if (!S_ISBLK(st.st_mode))
159                 return NULL;
160
161         if (!(udev = udev_new()))
162                 return NULL;
163
164         if (!(device = udev_device_new_from_devnum(udev, 'b', st.st_rdev)))
165                 goto finish;
166
167         if ((model = udev_device_get_property_value(device, "ID_MODEL_FROM_DATABASE")) ||
168             (model = udev_device_get_property_value(device, "ID_MODEL")) ||
169             (model = udev_device_get_property_value(device, "DM_NAME")))
170                 description = strdup(model);
171
172 finish:
173         if (device)
174                 udev_device_unref(device);
175
176         if (udev)
177                 udev_unref(udev);
178
179         return description;
180 }
181
182 static char *disk_mount_point(const char *label) {
183         char *mp = NULL, *device = NULL;
184         FILE *f = NULL;
185         struct mntent *m;
186
187         /* Yeah, we don't support native systemd unit files here for now */
188
189         if (asprintf(&device, "/dev/mapper/%s", label) < 0)
190                 goto finish;
191
192         if (!(f = setmntent("/etc/fstab", "r")))
193                 goto finish;
194
195         while ((m = getmntent(f)))
196                 if (path_equal(m->mnt_fsname, device)) {
197                         mp = strdup(m->mnt_dir);
198                         break;
199                 }
200
201 finish:
202         if (f)
203                 endmntent(f);
204
205         free(device);
206
207         return mp;
208 }
209
210 int main(int argc, char *argv[]) {
211         int r = EXIT_FAILURE;
212         struct crypt_device *cd = NULL;
213         char **passwords = NULL, *truncated_cipher = NULL;
214         const char *cipher = NULL, *cipher_mode = NULL, *hash = NULL, *name = NULL;
215         char *description = NULL, *name_buffer = NULL, *mount_point = NULL;
216
217         if (argc < 3) {
218                 log_error("This program requires at least two arguments.");
219                 return EXIT_FAILURE;
220         }
221
222         log_set_target(LOG_TARGET_AUTO);
223         log_parse_environment();
224         log_open();
225
226         if (streq(argv[1], "attach")) {
227                 uint32_t flags = 0;
228                 int k;
229                 unsigned try;
230                 const char *key_file = NULL;
231                 usec_t until;
232                 crypt_status_info status;
233
234                 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
235
236                 if (argc < 4) {
237                         log_error("attach requires at least two arguments.");
238                         goto finish;
239                 }
240
241                 if (argc >= 5 &&
242                     argv[4][0] &&
243                     !streq(argv[4], "-") &&
244                     !streq(argv[4], "none")) {
245
246                         if (!path_is_absolute(argv[4]))
247                                 log_error("Password file path %s is not absolute. Ignoring.", argv[4]);
248                         else
249                                 key_file = argv[4];
250                 }
251
252                 if (argc >= 6 && argv[5][0] && !streq(argv[5], "-"))
253                         parse_options(argv[5]);
254
255                 /* A delicious drop of snake oil */
256                 mlockall(MCL_FUTURE);
257
258                 description = disk_description(argv[3]);
259                 mount_point = disk_mount_point(argv[2]);
260
261                 if (description && streq(argv[2], description)) {
262                         /* If the description string is simply the
263                          * volume name, then let's not show this
264                          * twice */
265                         free(description);
266                         description = NULL;
267                 }
268
269                 if (mount_point && description)
270                         asprintf(&name_buffer, "%s (%s) on %s", description, argv[2], mount_point);
271                 else if (mount_point)
272                         asprintf(&name_buffer, "%s on %s", argv[2], mount_point);
273                 else if (description)
274                         asprintf(&name_buffer, "%s (%s)", description, argv[2]);
275
276                 name = name_buffer ? name_buffer : argv[2];
277
278                 if ((k = crypt_init(&cd, argv[3]))) {
279                         log_error("crypt_init() failed: %s", strerror(-k));
280                         goto finish;
281                 }
282
283                 crypt_set_log_callback(cd, log_glue, NULL);
284
285                 status = crypt_status(cd, argv[2]);
286                 if (status == CRYPT_ACTIVE || status == CRYPT_BUSY) {
287                         log_info("Volume %s already active.", argv[2]);
288                         r = EXIT_SUCCESS;
289                         goto finish;
290                 }
291
292                 if (opt_readonly)
293                         flags |= CRYPT_ACTIVATE_READONLY;
294
295                 until = now(CLOCK_MONOTONIC) + (opt_timeout > 0 ? opt_timeout : 60 * USEC_PER_SEC);
296
297                 opt_tries = opt_tries > 0 ? opt_tries : 3;
298                 opt_key_size = (opt_key_size > 0 ? opt_key_size : 256);
299                 hash = opt_hash ? opt_hash : "ripemd160";
300
301                 if (opt_cipher) {
302                         size_t l;
303
304                         l = strcspn(opt_cipher, "-");
305
306                         if (!(truncated_cipher = strndup(opt_cipher, l))) {
307                                 log_error("Out of memory");
308                                 goto finish;
309                         }
310
311                         cipher = truncated_cipher;
312                         cipher_mode = opt_cipher[l] ? opt_cipher+l+1 : "plain";
313                 } else {
314                         cipher = "aes";
315                         cipher_mode = "cbc-essiv:sha256";
316                 }
317
318                 for (try = 0; try < opt_tries; try++) {
319                         bool pass_volume_key = false;
320
321                         strv_free(passwords);
322                         passwords = NULL;
323
324                         if (!key_file) {
325                                 char *text;
326                                 char **p;
327
328                                 if (asprintf(&text, "Please enter passphrase for disk %s!", name) < 0) {
329                                         log_error("Out of memory");
330                                         goto finish;
331                                 }
332
333                                 k = ask_password_auto(text, "drive-harddisk", until, try == 0 && !opt_verify, &passwords);
334                                 free(text);
335
336                                 if (k < 0) {
337                                         log_error("Failed to query password: %s", strerror(-k));
338                                         goto finish;
339                                 }
340
341                                 if (opt_verify) {
342                                         char **passwords2 = NULL;
343
344                                         assert(strv_length(passwords) == 1);
345
346                                         if (asprintf(&text, "Please enter passphrase for disk %s! (verification)", name) < 0) {
347                                                 log_error("Out of memory");
348                                                 goto finish;
349                                         }
350
351                                         k = ask_password_auto(text, "drive-harddisk", until, false, &passwords2);
352                                         free(text);
353
354                                         if (k < 0) {
355                                                 log_error("Failed to query verification password: %s", strerror(-k));
356                                                 goto finish;
357                                         }
358
359                                         assert(strv_length(passwords2) == 1);
360
361                                         if (!streq(passwords[0], passwords2[0])) {
362                                                 log_warning("Passwords did not match, retrying.");
363                                                 strv_free(passwords2);
364                                                 continue;
365                                         }
366
367                                         strv_free(passwords2);
368                                 }
369
370                                 strv_uniq(passwords);
371
372                                 STRV_FOREACH(p, passwords) {
373                                         char *c;
374
375                                         if (strlen(*p)+1 >= opt_key_size)
376                                                 continue;
377
378                                         /* Pad password if necessary */
379                                         if (!(c = new(char, opt_key_size))) {
380                                                 log_error("Out of memory.");
381                                                 goto finish;
382                                         }
383
384                                         strncpy(c, *p, opt_key_size);
385                                         free(*p);
386                                         *p = c;
387                                 }
388                         }
389
390                         if (!opt_type || streq(opt_type, CRYPT_LUKS1))
391                                 k = crypt_load(cd, CRYPT_LUKS1, NULL);
392
393                         if ((!opt_type && k < 0) || streq_ptr(opt_type, CRYPT_PLAIN)) {
394                                 struct crypt_params_plain params;
395
396                                 zero(params);
397                                 params.hash = hash;
398
399                                 /* In contrast to what the name
400                                  * crypt_setup() might suggest this
401                                  * doesn't actually format anything,
402                                  * it just configures encryption
403                                  * parameters when used for plain
404                                  * mode. */
405                                 k = crypt_format(cd, CRYPT_PLAIN,
406                                                  cipher,
407                                                  cipher_mode,
408                                                  NULL,
409                                                  NULL,
410                                                  opt_key_size / 8,
411                                                  &params);
412
413                                 pass_volume_key = streq(hash, "plain");
414                         }
415
416                         if (k < 0) {
417                                 log_error("Loading of cryptographic parameters failed: %s", strerror(-k));
418                                 goto finish;
419                         }
420
421                         log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
422                                  crypt_get_cipher(cd),
423                                  crypt_get_cipher_mode(cd),
424                                  crypt_get_volume_key_size(cd)*8,
425                                  argv[3]);
426
427                         if (key_file)
428                                 k = crypt_activate_by_keyfile(cd, argv[2], CRYPT_ANY_SLOT, key_file, opt_key_size, flags);
429                         else {
430                                 char **p;
431
432                                 STRV_FOREACH(p, passwords) {
433
434                                         if (pass_volume_key)
435                                                 k = crypt_activate_by_volume_key(cd, argv[2], *p, opt_key_size, flags);
436                                         else
437                                                 k = crypt_activate_by_passphrase(cd, argv[2], CRYPT_ANY_SLOT, *p, strlen(*p), flags);
438
439                                         if (k >= 0)
440                                                 break;
441                                 }
442                         }
443
444                         if (k >= 0)
445                                 break;
446
447                         if (k != -EPERM) {
448                                 log_error("Failed to activate: %s", strerror(-k));
449                                 goto finish;
450                         }
451
452                         log_warning("Invalid passphrase.");
453                 }
454
455                 if (try >= opt_tries) {
456                         log_error("Too many attempts.");
457                         r = EXIT_FAILURE;
458                         goto finish;
459                 }
460
461         } else if (streq(argv[1], "detach")) {
462                 int k;
463
464                 if ((k = crypt_init_by_name(&cd, argv[2]))) {
465                         log_error("crypt_init() failed: %s", strerror(-k));
466                         goto finish;
467                 }
468
469                 crypt_set_log_callback(cd, log_glue, NULL);
470
471                 if ((k = crypt_deactivate(cd, argv[2])) < 0) {
472                         log_error("Failed to deactivate: %s", strerror(-k));
473                         goto finish;
474                 }
475
476         } else {
477                 log_error("Unknown verb %s.", argv[1]);
478                 goto finish;
479         }
480
481         r = EXIT_SUCCESS;
482
483 finish:
484
485         if (cd)
486                 crypt_free(cd);
487
488         free(opt_cipher);
489         free(opt_hash);
490
491         free(truncated_cipher);
492
493         strv_free(passwords);
494
495         free(description);
496         free(mount_point);
497         free(name_buffer);
498
499         return r;
500 }