Fix return code when passphrase is read from pipe.
[platform/upstream/cryptsetup.git] / lib / setup.c
1 /*
2  * libcryptsetup - cryptsetup library
3  *
4  * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <fcntl.h>
27 #include <errno.h>
28
29 #include "libcryptsetup.h"
30 #include "luks.h"
31 #include "loopaes.h"
32 #include "internal.h"
33 #include "crypto_backend.h"
34
35 struct crypt_device {
36         char *type;
37
38         char *device;
39         char *backing_file;
40         int loop_fd;
41         struct volume_key *volume_key;
42         uint64_t timeout;
43         uint64_t iteration_time;
44         int tries;
45         int password_verify;
46         int rng_type;
47
48         /* used in CRYPT_LUKS1 */
49         struct luks_phdr hdr;
50         uint64_t PBKDF2_per_sec;
51
52         /* used in CRYPT_PLAIN */
53         struct crypt_params_plain plain_hdr;
54         char *plain_cipher;
55         char *plain_cipher_mode;
56         char *plain_uuid;
57
58         /* used in CRYPT_LOOPAES */
59         struct crypt_params_loopaes loopaes_hdr;
60         char *loopaes_cipher;
61         char *loopaes_cipher_mode;
62         char *loopaes_uuid;
63         unsigned int loopaes_key_size;
64
65         /* callbacks definitions */
66         void (*log)(int level, const char *msg, void *usrptr);
67         void *log_usrptr;
68         int (*confirm)(const char *msg, void *usrptr);
69         void *confirm_usrptr;
70         int (*password)(const char *msg, char *buf, size_t length, void *usrptr);
71         void *password_usrptr;
72 };
73
74 /* Log helper */
75 static void (*_default_log)(int level, const char *msg, void *usrptr) = NULL;
76 static int _debug_level = 0;
77
78 void crypt_set_debug_level(int level)
79 {
80         _debug_level = level;
81 }
82
83 int crypt_get_debug_level()
84 {
85         return _debug_level;
86 }
87
88 void crypt_log(struct crypt_device *cd, int level, const char *msg)
89 {
90         if (cd && cd->log)
91                 cd->log(level, msg, cd->log_usrptr);
92         else if (_default_log)
93                 _default_log(level, msg, NULL);
94 }
95
96 void logger(struct crypt_device *cd, int level, const char *file,
97             int line, const char *format, ...)
98 {
99         va_list argp;
100         char *target = NULL;
101
102         va_start(argp, format);
103
104         if (vasprintf(&target, format, argp) > 0) {
105                 if (level >= 0) {
106                         crypt_log(cd, level, target);
107 #ifdef CRYPT_DEBUG
108                 } else if (_debug_level)
109                         printf("# %s:%d %s\n", file ?: "?", line, target);
110 #else
111                 } else if (_debug_level)
112                         printf("# %s\n", target);
113 #endif
114         }
115
116         va_end(argp);
117         free(target);
118 }
119
120 static int init_crypto(struct crypt_device *ctx)
121 {
122         int r;
123
124         r = crypt_random_init(ctx);
125         if (r < 0) {
126                 log_err(ctx, _("Cannot initialize crypto RNG backend.\n"));
127                 return r;
128         }
129
130         r = crypt_backend_init(ctx);
131         if (r < 0)
132                 log_err(ctx, _("Cannot initialize crypto backend.\n"));
133
134         return r;
135 }
136
137 /*
138  * Password processing behaviour matrix of process_key
139  *
140  * from binary file: check if there is sufficently large key material
141  * interactive & from fd: hash if requested, otherwise crop or pad with '0'
142  */
143 static char *process_key(struct crypt_device *cd, const char *hash_name,
144                          const char *key_file, size_t key_size,
145                          const char *pass, size_t passLen)
146 {
147         char *key;
148         int r;
149
150         if (!key_size)
151                 return NULL;
152
153         key = crypt_safe_alloc(key_size);
154         if (!key)
155                 return NULL;
156         memset(key, 0, key_size);
157
158         /* key is coming from binary file */
159         if (key_file && strcmp(key_file, "-")) {
160                 if(passLen < key_size) {
161                         log_err(cd, _("Cannot not read %d bytes from key file %s.\n"),
162                                 key_size, key_file);
163                         crypt_safe_free(key);
164                         return NULL;
165                 }
166                 memcpy(key, pass, key_size);
167                 return key;
168         }
169
170         /* key is coming from tty, fd or binary stdin */
171         if (hash_name) {
172                 r = crypt_plain_hash(cd, hash_name, key, key_size, pass, passLen);
173                 if (r < 0) {
174                         if (r == -ENOENT)
175                                 log_err(cd, _("Hash algorithm %s not supported.\n"),
176                                         hash_name);
177                         else
178                                 log_err(cd, _("Key processing error (using hash %s).\n"),
179                                         hash_name);
180                         crypt_safe_free(key);
181                         return NULL;
182                 }
183         } else if (passLen > key_size) {
184                 memcpy(key, pass, key_size);
185         } else {
186                 memcpy(key, pass, passLen);
187         }
188
189         return key;
190 }
191
192 static int isPLAIN(const char *type)
193 {
194         return (type && !strcmp(CRYPT_PLAIN, type));
195 }
196
197 static int isLUKS(const char *type)
198 {
199         return (type && !strcmp(CRYPT_LUKS1, type));
200 }
201
202 static int isLOOPAES(const char *type)
203 {
204         return (type && !strcmp(CRYPT_LOOPAES, type));
205 }
206
207 /* keyslot helpers */
208 static int keyslot_verify_or_find_empty(struct crypt_device *cd, int *keyslot)
209 {
210         if (*keyslot == CRYPT_ANY_SLOT) {
211                 *keyslot = LUKS_keyslot_find_empty(&cd->hdr);
212                 if (*keyslot < 0) {
213                         log_err(cd, _("All key slots full.\n"));
214                         return -EINVAL;
215                 }
216         }
217
218         switch (LUKS_keyslot_info(&cd->hdr, *keyslot)) {
219                 case CRYPT_SLOT_INVALID:
220                         log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
221                                 *keyslot, LUKS_NUMKEYS - 1);
222                         return -EINVAL;
223                 case CRYPT_SLOT_INACTIVE:
224                         break;
225                 default:
226                         log_err(cd, _("Key slot %d is full, please select another one.\n"),
227                                 *keyslot);
228                         return -EINVAL;
229         }
230
231         return 0;
232 }
233
234 static int verify_other_keyslot(struct crypt_device *cd,
235                                 const char *key_file,
236                                 int keyIndex)
237 {
238         struct volume_key *vk = NULL;
239         crypt_keyslot_info ki;
240         int openedIndex, r;
241         char *password = NULL;
242         size_t passwordLen;
243
244         r = crypt_get_key(_("Enter any remaining LUKS passphrase: "),
245                           &password, &passwordLen, 0, key_file, cd->timeout,
246                           cd->password_verify, cd);
247         if(r < 0)
248                 goto out;
249
250         ki = crypt_keyslot_status(cd, keyIndex);
251         if (ki == CRYPT_SLOT_ACTIVE) /* Not last slot */
252                 LUKS_keyslot_set(&cd->hdr, keyIndex, 0);
253
254         openedIndex = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT,
255                                              password, passwordLen,
256                                              &cd->hdr, &vk, cd);
257
258         if (ki == CRYPT_SLOT_ACTIVE)
259                 LUKS_keyslot_set(&cd->hdr, keyIndex, 1);
260
261         if (openedIndex < 0)
262                 r = -EPERM;
263         else
264                 log_verbose(cd, _("Key slot %d verified.\n"), openedIndex);
265 out:
266         crypt_free_volume_key(vk);
267         crypt_safe_free(password);
268         return r;
269 }
270
271 static int find_keyslot_by_passphrase(struct crypt_device *cd,
272                                       const char *key_file,
273                                       char *message)
274 {
275         struct volume_key *vk = NULL;
276         char *password = NULL;
277         size_t passwordLen;
278         int r;
279
280         r = crypt_get_key(message,&password,&passwordLen, 0, key_file,
281                           cd->timeout, cd->password_verify, cd);
282         if (r < 0)
283                 goto out;
284
285         r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
286                                    passwordLen, &cd->hdr, &vk, cd);
287 out:
288         crypt_free_volume_key(vk);
289         crypt_safe_free(password);
290         return r;
291 }
292
293 static int luks_remove_helper(struct crypt_device *cd,
294                               int key_slot,
295                               const char *other_key_file,
296                               const char *key_file,
297                               int verify)
298 {
299         crypt_keyslot_info ki;
300         int r = -EINVAL;
301
302         if (key_slot == CRYPT_ANY_SLOT) {
303                 key_slot = find_keyslot_by_passphrase(cd, key_file,
304                                 _("Enter LUKS passphrase to be deleted: "));
305                 if(key_slot < 0) {
306                         r = -EPERM;
307                         goto out;
308                 }
309
310                 log_std(cd, _("Key slot %d selected for deletion.\n"), key_slot);
311         }
312
313         ki = crypt_keyslot_status(cd, key_slot);
314         if (ki == CRYPT_SLOT_INVALID) {
315                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
316                         key_slot, LUKS_NUMKEYS - 1);
317                 r = -EINVAL;
318                 goto out;
319         }
320         if (ki <= CRYPT_SLOT_INACTIVE) {
321                 log_err(cd, _("Key %d not active. Can't wipe.\n"), key_slot);
322                 r = -EINVAL;
323                 goto out;
324         }
325
326         if (ki == CRYPT_SLOT_ACTIVE_LAST && cd->confirm &&
327             !(cd->confirm(_("This is the last keyslot."
328                             " Device will become unusable after purging this key."),
329                          cd->confirm_usrptr))) {
330                 r = -EINVAL;
331                 goto out;
332         }
333
334         if(verify)
335                 r = verify_other_keyslot(cd, other_key_file, key_slot);
336         else
337                 r = 0;
338
339         if (!r)
340                 r = crypt_keyslot_destroy(cd, key_slot);
341 out:
342         return (r < 0) ? r : 0;
343 }
344
345 static int create_device_helper(struct crypt_device *cd,
346                                 const char *name,
347                                 const char *hash,
348                                 const char *cipher,
349                                 const char *cipher_mode,
350                                 const char *key_file,
351                                 const char *passphrase,
352                                 size_t passphrase_size,
353                                 size_t key_size,
354                                 uint64_t size,
355                                 uint64_t skip,
356                                 uint64_t offset,
357                                 const char *uuid,
358                                 int read_only,
359                                 unsigned int flags,
360                                 int reload)
361 {
362         crypt_status_info ci;
363         char *dm_cipher = NULL;
364         char *processed_key = NULL;
365         int r;
366
367         if (!name)
368                 return -EINVAL;
369
370         ci = crypt_status(cd, name);
371         if (ci == CRYPT_INVALID)
372                 return -EINVAL;
373
374         if (reload && ci < CRYPT_ACTIVE)
375                 return -EINVAL;
376
377         if (!reload && ci >= CRYPT_ACTIVE) {
378                 log_err(cd, _("Device %s already exists.\n"), name);
379                 return -EEXIST;
380         }
381
382         if (key_size < 0 || key_size > 1024) {
383                 log_err(cd, _("Invalid key size %d.\n"), key_size);
384                 return -EINVAL;
385         }
386
387         r = device_check_and_adjust(cd, cd->device, !reload, &size, &offset, &read_only);
388         if (r)
389                 return r;
390
391         if (cipher_mode && asprintf(&dm_cipher, "%s-%s", cipher, cipher_mode) < 0)
392                 return -ENOMEM;
393
394         processed_key = process_key(cd, hash, key_file, key_size, passphrase, passphrase_size);
395         if (!processed_key) {
396                 r = -ENOENT;
397                 goto out;
398         }
399
400         r = dm_create_device(name, cd->device, dm_cipher ?: cipher, cd->type, uuid, size, skip, offset,
401                              key_size, processed_key, read_only, reload);
402 out:
403         free(dm_cipher);
404         crypt_safe_free(processed_key);
405         return r;
406 }
407
408 static int open_from_hdr_and_vk(struct crypt_device *cd,
409                                 struct volume_key *vk,
410                                 const char *name,
411                                 uint32_t flags)
412 {
413         uint64_t size, offset;
414         char *cipher;
415         int read_only, no_uuid, r;
416
417         size = 0;
418         offset = crypt_get_data_offset(cd);
419         read_only = flags & CRYPT_ACTIVATE_READONLY;
420         no_uuid = flags & CRYPT_ACTIVATE_NO_UUID;
421
422         r = device_check_and_adjust(cd, cd->device, 1, &size, &offset, &read_only);
423         if (r)
424                 return r;
425
426         if (asprintf(&cipher, "%s-%s", crypt_get_cipher(cd),
427                      crypt_get_cipher_mode(cd)) < 0)
428                 r = -ENOMEM;
429         else
430                 r = dm_create_device(name, cd->device, cipher, cd->type,
431                                      no_uuid ? NULL : crypt_get_uuid(cd),
432                                      size, 0, offset, vk->keylength, vk->key,
433                                      read_only, 0);
434         free(cipher);
435         return r;
436 }
437
438 static void log_wrapper(int level, const char *msg, void *usrptr)
439 {
440         void (*xlog)(int level, char *msg) = usrptr;
441         xlog(level, (char *)msg);
442 }
443
444 static int yesDialog_wrapper(const char *msg, void *usrptr)
445 {
446         int (*xyesDialog)(char *msg) = usrptr;
447         return xyesDialog((char*)msg);
448 }
449
450 int crypt_confirm(struct crypt_device *cd, const char *msg)
451 {
452         if (!cd || !cd->confirm)
453                 return 1;
454         else
455                 return cd->confirm(msg, cd->confirm_usrptr);
456 }
457
458 static int key_from_terminal(struct crypt_device *cd, char *msg, char **key,
459                               size_t *key_len, int force_verify)
460 {
461         char *prompt = NULL;
462         int r;
463
464         *key = NULL;
465         if(!msg && asprintf(&prompt, _("Enter passphrase for %s: "),
466                             cd->backing_file ?: cd->device) < 0)
467                 return -ENOMEM;
468
469         if (!msg)
470                 msg = prompt;
471
472         if (cd->password) {
473                 *key = crypt_safe_alloc(DEFAULT_PASSPHRASE_SIZE_MAX);
474                 if (!*key) {
475                         r = -ENOMEM;
476                         goto out;
477                 }
478                 r = cd->password(msg, *key, DEFAULT_PASSPHRASE_SIZE_MAX,
479                                  cd->password_usrptr);
480                 if (r < 0) {
481                         crypt_safe_free(*key);
482                         *key = NULL;
483                 } else
484                         *key_len = r;
485         } else
486                 r = crypt_get_key(msg, key, key_len, 0, NULL, cd->timeout,
487                                   (force_verify || cd->password_verify), cd);
488 out:
489         free(prompt);
490         return (r < 0) ? r: 0;
491 }
492
493 static int volume_key_by_terminal_passphrase(struct crypt_device *cd, int keyslot,
494                                              struct volume_key **vk)
495 {
496         char *passphrase_read = NULL;
497         size_t passphrase_size_read;
498         int r = -EINVAL, eperm = 0, tries = cd->tries;
499
500         *vk = NULL;
501         do {
502                 crypt_free_volume_key(*vk);
503                 *vk = NULL;
504
505                 r = key_from_terminal(cd, NULL, &passphrase_read,
506                                       &passphrase_size_read, 0);
507                 if(r < 0)
508                         goto out;
509
510                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
511                                            passphrase_size_read, &cd->hdr, vk, cd);
512                 if (r == -EPERM)
513                         eperm = 1;
514                 crypt_safe_free(passphrase_read);
515                 passphrase_read = NULL;
516         } while (r == -EPERM && (--tries > 0));
517 out:
518         if (r < 0) {
519                 crypt_free_volume_key(*vk);
520                 *vk = NULL;
521
522                 /* Report wrong passphrase if at least one try failed */
523                 if (eperm && r == -EPIPE)
524                         r = -EPERM;
525         }
526
527         crypt_safe_free(passphrase_read);
528         return r;
529 }
530
531 static int key_from_file(struct crypt_device *cd, char *msg,
532                           char **key, size_t *key_len,
533                           const char *key_file, size_t key_size)
534 {
535         return crypt_get_key(msg, key, key_len, key_size, key_file,
536                              cd->timeout, 0, cd);
537 }
538
539 static int _crypt_init(struct crypt_device **cd,
540                        const char *type,
541                        struct crypt_options *options,
542                        int load, int need_dm)
543 {
544         int init_by_name, r;
545
546         /* if it is plain device and mapping table is being reloaded
547         initialize it by name*/
548         init_by_name = (type && !strcmp(type, CRYPT_PLAIN) && load);
549
550         /* Some of old API calls do not require DM in kernel,
551            fake initialisation by initialise it with kernel_check disabled */
552         if (!need_dm)
553                 (void)dm_init(NULL, 0);
554         if (init_by_name)
555                 r = crypt_init_by_name(cd, options->name);
556         else
557                 r = crypt_init(cd, options->device);
558         if (!need_dm)
559                 dm_exit();
560
561         if (r)
562                 return -EINVAL;
563
564         crypt_set_log_callback(*cd, log_wrapper, options->icb->log);
565         crypt_set_confirm_callback(*cd, yesDialog_wrapper, options->icb->yesDialog);
566
567         crypt_set_timeout(*cd, options->timeout);
568         crypt_set_password_retry(*cd, options->tries);
569         crypt_set_iterarion_time(*cd, options->iteration_time ?: 1000);
570         crypt_set_password_verify(*cd, options->flags & CRYPT_FLAG_VERIFY);
571
572         if (load && !init_by_name)
573                 r = crypt_load(*cd, type, NULL);
574
575         if (!r && type && !(*cd)->type) {
576                 (*cd)->type = strdup(type);
577                 if (!(*cd)->type)
578                         r = -ENOMEM;
579         }
580
581         if (r)
582                 crypt_free(*cd);
583
584         return r;
585 }
586
587 void crypt_set_log_callback(struct crypt_device *cd,
588         void (*log)(int level, const char *msg, void *usrptr),
589         void *usrptr)
590 {
591         if (!cd)
592                 _default_log = log;
593         else {
594                 cd->log = log;
595                 cd->log_usrptr = usrptr;
596         }
597 }
598
599 void crypt_set_confirm_callback(struct crypt_device *cd,
600         int (*confirm)(const char *msg, void *usrptr),
601         void *usrptr)
602 {
603         cd->confirm = confirm;
604         cd->confirm_usrptr = usrptr;
605 }
606
607 void crypt_set_password_callback(struct crypt_device *cd,
608         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
609         void *usrptr)
610 {
611         cd->password = password;
612         cd->password_usrptr = usrptr;
613 }
614
615 /* OPTIONS: name, cipher, device, hash, key_file, key_size, key_slot,
616  *          offset, size, skip, timeout, tries, passphrase_fd (ignored),
617  *          flags, icb */
618 static int crypt_create_and_update_device(struct crypt_options *options, int update)
619 {
620         struct crypt_device *cd = NULL;
621         char *passphrase = NULL;
622         size_t passphrase_size = 0;
623         int r;
624
625         r = _crypt_init(&cd, CRYPT_PLAIN, options, 0, 1);
626         if (r)
627                 return r;
628
629         r = crypt_get_key(_("Enter passphrase: "), &passphrase, &passphrase_size,
630                           options->key_size, options->key_file,
631                           cd->timeout, cd->password_verify, cd);
632         if (!r)
633                 r = create_device_helper(cd, options->name, options->hash,
634                         options->cipher, NULL, options->key_file,
635                         passphrase, passphrase_size,
636                         options->key_size, options->size, options->skip,
637                         options->offset, NULL, options->flags & CRYPT_FLAG_READONLY,
638                         options->flags, update);
639
640         crypt_safe_free(passphrase);
641         crypt_free(cd);
642         return r;
643 }
644
645 int crypt_create_device(struct crypt_options *options)
646 {
647         return crypt_create_and_update_device(options, 0);
648 }
649
650 int crypt_update_device(struct crypt_options *options)
651 {
652         return crypt_create_and_update_device(options, 1);
653 }
654
655 /* OPTIONS: name, size, icb */
656 int crypt_resize_device(struct crypt_options *options)
657 {
658         struct crypt_device *cd = NULL;
659         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
660         char *type = NULL;
661         uint64_t size, skip, offset;
662         int key_size, read_only, r;
663
664         log_dbg("Resizing device %s to %" PRIu64 " sectors.", options->name, options->size);
665
666         if (dm_init(NULL, 1) < 0)
667                 return -ENOSYS;
668
669         r = dm_query_device(options->name, &device, &size, &skip, &offset,
670                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
671         if (r < 0) {
672                 log_err(NULL, _("Device %s is not active.\n"), options->name);
673                 goto out;
674         }
675
676         /* Try to determine type of device from UUID */
677         type = CRYPT_PLAIN;
678         if (uuid) {
679                 if (!strncmp(uuid, CRYPT_PLAIN, strlen(CRYPT_PLAIN))) {
680                         type = CRYPT_PLAIN;
681                         free (uuid);
682                         uuid = NULL;
683                 } else if (!strncmp(uuid, CRYPT_LUKS1, strlen(CRYPT_LUKS1)))
684                         type = CRYPT_LUKS1;
685         }
686
687         if (!options->device)
688                 options->device = device;
689
690         r = _crypt_init(&cd, type, options, 1, 1);
691         if (r)
692                 goto out;
693
694         size = options->size;
695         r = device_check_and_adjust(cd, device, 0, &size, &offset, &read_only);
696         if (r)
697                 goto out;
698
699         r = dm_create_device(options->name, device, cipher, type,
700                              crypt_get_uuid(cd), size, skip, offset,
701                              key_size, key, read_only, 1);
702 out:
703         crypt_safe_free(key);
704         free(cipher);
705         if (options->device == device)
706                 options->device = NULL;
707         free(device);
708         free(uuid);
709         crypt_free(cd);
710         dm_exit();
711         return r;
712 }
713
714 /* OPTIONS: name, icb */
715 int crypt_query_device(struct crypt_options *options)
716 {
717         int read_only, r;
718
719         log_dbg("Query device %s.", options->name);
720
721         if (dm_init(NULL, 1) < 0)
722                 return -ENOSYS;
723
724         r = dm_status_device(options->name);
725         if (r < 0)
726                 goto out;
727
728         r = dm_query_device(options->name, (char **)&options->device, &options->size,
729                             &options->skip, &options->offset, (char **)&options->cipher,
730                             &options->key_size, NULL, &read_only, NULL, NULL);
731         if (r >= 0) {
732                 if (read_only)
733                         options->flags |= CRYPT_FLAG_READONLY;
734
735                 options->flags |= CRYPT_FLAG_FREE_DEVICE;
736                 options->flags |= CRYPT_FLAG_FREE_CIPHER;
737
738                 r = 1;
739         }
740 out:
741         if (r == -ENODEV)
742                 r = 0;
743
744         dm_exit();
745         return r;
746 }
747
748 /* OPTIONS: name, icb */
749 int crypt_remove_device(struct crypt_options *options)
750 {
751         struct crypt_device *cd = NULL;
752         int r;
753
754         r = crypt_init_by_name(&cd, options->name);
755         if (r == 0)
756                 r = crypt_deactivate(cd, options->name);
757
758         crypt_free(cd);
759         return r;
760
761 }
762
763 /* OPTIONS: device, cipher, hash, align_payload, key_size (master key), key_slot
764  *          new_key_file, iteration_time, timeout, flags, icb */
765 int crypt_luksFormat(struct crypt_options *options)
766 {
767         char cipherName[LUKS_CIPHERNAME_L];
768         char cipherMode[LUKS_CIPHERMODE_L];
769         char *password=NULL;
770         size_t passwordLen;
771         struct crypt_device *cd = NULL;
772         struct crypt_params_luks1 cp = {
773                 .hash = options->hash,
774                 .data_alignment = options->align_payload
775         };
776         int r;
777
778         r = crypt_parse_name_and_mode(options->cipher, cipherName, NULL, cipherMode);
779         if(r < 0) {
780                 log_err(cd, _("No known cipher specification pattern detected.\n"));
781                 return r;
782         }
783
784         if ((r = _crypt_init(&cd, CRYPT_LUKS1, options, 0, 1)))
785                 return r;
786
787         if (options->key_slot >= LUKS_NUMKEYS && options->key_slot != CRYPT_ANY_SLOT) {
788                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
789                         options->key_slot, LUKS_NUMKEYS - 1);
790                 r = -EINVAL;
791                 goto out;
792         }
793
794         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen, 0,
795                           options->new_key_file, cd->timeout, cd->password_verify, cd);
796
797         if(r < 0)
798                 goto out;
799
800         r = crypt_format(cd, CRYPT_LUKS1, cipherName, cipherMode,
801                          NULL, NULL, options->key_size, &cp);
802         if (r < 0)
803                 goto out;
804
805         /* Add keyslot using internally stored volume key generated during format */
806         r = crypt_keyslot_add_by_volume_key(cd, options->key_slot, NULL, 0,
807                                             password, passwordLen);
808 out:
809         crypt_free(cd);
810         crypt_safe_free(password);
811         return (r < 0) ? r : 0;
812 }
813
814 /* OPTIONS: name, device, key_size, key_file, timeout, tries, flags, icb */
815 int crypt_luksOpen(struct crypt_options *options)
816 {
817         struct crypt_device *cd = NULL;
818         uint32_t flags = 0;
819         int r;
820
821         if (!options->name)
822                 return -EINVAL;
823
824         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
825         if (r)
826                 return r;
827
828         if (options->flags & CRYPT_FLAG_READONLY)
829                 flags |= CRYPT_ACTIVATE_READONLY;
830
831         if (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS)
832                 flags |= CRYPT_ACTIVATE_NO_UUID;
833
834         if (options->key_file)
835                 r = crypt_activate_by_keyfile(cd, options->name,
836                         CRYPT_ANY_SLOT, options->key_file, 0,
837                         flags);
838         else
839                 r = crypt_activate_by_passphrase(cd, options->name,
840                         CRYPT_ANY_SLOT, options->passphrase,
841                         options->passphrase ? strlen(options->passphrase) : 0,
842                         flags);
843
844         crypt_free(cd);
845         return (r < 0) ? r : 0;
846 }
847
848 /* OPTIONS: device, keys_slot, key_file, timeout, flags, icb */
849 int crypt_luksKillSlot(struct crypt_options *options)
850 {
851         struct crypt_device *cd = NULL;
852         int r;
853
854         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
855         if (r)
856                 return r;
857
858         r = luks_remove_helper(cd, options->key_slot, options->key_file, NULL,
859                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
860
861         crypt_free(cd);
862         return (r < 0) ? r : 0;
863 }
864
865 /* OPTIONS: device, new_key_file, key_file, timeout, flags, icb */
866 int crypt_luksRemoveKey(struct crypt_options *options)
867 {
868         struct crypt_device *cd = NULL;
869         int r;
870
871         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
872         if (r)
873                 return r;
874
875         r = luks_remove_helper(cd, CRYPT_ANY_SLOT, options->key_file, options->new_key_file,
876                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
877
878         crypt_free(cd);
879         return (r < 0) ? r : 0;
880 }
881
882
883 /* OPTIONS: device, new_key_file, key_file, key_slot, flags,
884             iteration_time, timeout, icb */
885 int crypt_luksAddKey(struct crypt_options *options)
886 {
887         struct crypt_device *cd = NULL;
888         int r = -EINVAL;
889
890         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
891         if (r)
892                 return r;
893
894         if (options->key_file || options->new_key_file)
895                 r = crypt_keyslot_add_by_keyfile(cd, options->key_slot,
896                                                  options->key_file, 0,
897                                                  options->new_key_file, 0);
898         else
899                 r = crypt_keyslot_add_by_passphrase(cd, options->key_slot,
900                                                     NULL, 0, NULL, 0);
901
902         crypt_free(cd);
903         return (r < 0) ? r : 0;
904 }
905
906 /* OPTIONS: device, icb */
907 int crypt_luksUUID(struct crypt_options *options)
908 {
909         struct crypt_device *cd = NULL;
910         char *uuid;
911         int r;
912
913         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
914         if (r)
915                 return r;
916
917         uuid = (char *)crypt_get_uuid(cd);
918         log_std(cd, uuid ?: "");
919         log_std(cd, "\n");
920         crypt_free(cd);
921         return 0;
922 }
923
924 /* OPTIONS: device, icb */
925 int crypt_isLuks(struct crypt_options *options)
926 {
927         struct crypt_device *cd = NULL;
928         int r;
929
930         log_dbg("Check device %s for LUKS header.", options->device);
931
932         r = init_crypto(cd);
933         if (r < 0)
934                 return r;
935
936         r = crypt_init(&cd, options->device);
937         if (r < 0)
938                 return -EINVAL;
939
940         /* Do print fail here, no need to crypt_load() */
941         r = LUKS_read_phdr(cd->device, &cd->hdr, 0, cd) ? -EINVAL : 0;
942
943         crypt_free(cd);
944         return r;
945 }
946
947 /* OPTIONS: device, icb */
948 int crypt_luksDump(struct crypt_options *options)
949 {
950         struct crypt_device *cd = NULL;
951         int r;
952
953         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
954         if(r < 0)
955                 return r;
956
957         r = crypt_dump(cd);
958
959         crypt_free(cd);
960         return r;
961 }
962
963 void crypt_get_error(char *buf, size_t size)
964 {
965         const char *error = get_error();
966
967         if (!buf || size < 1)
968                 set_error(NULL);
969         else if (error) {
970                 strncpy(buf, error, size - 1);
971                 buf[size - 1] = '\0';
972                 set_error(NULL);
973         } else
974                 buf[0] = '\0';
975 }
976
977 void crypt_put_options(struct crypt_options *options)
978 {
979         if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
980                 free((char *)options->device);
981                 options->device = NULL;
982                 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
983         }
984         if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
985                 free((char *)options->cipher);
986                 options->cipher = NULL;
987                 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
988         }
989 }
990
991 const char *crypt_get_dir(void)
992 {
993         return dm_get_dir();
994 }
995
996 /////////////////////////////////
997 //
998 // New API
999 //
1000
1001 int crypt_init(struct crypt_device **cd, const char *device)
1002 {
1003         struct crypt_device *h = NULL;
1004         int r, readonly = 0;
1005
1006         if (!cd)
1007                 return -EINVAL;
1008
1009         log_dbg("Allocating crypt device %s context.", device);
1010
1011         if (!(h = malloc(sizeof(struct crypt_device))))
1012                 return -ENOMEM;
1013
1014         memset(h, 0, sizeof(*h));
1015         h->loop_fd = -1;
1016
1017         if (device) {
1018                 r = device_ready(NULL, device, O_RDONLY);
1019                 if (r == -ENOTBLK) {
1020                         h->device = crypt_loop_get_device();
1021                         log_dbg("Not a block device, %s%s.",
1022                                 h->device ? "using free loop device " :
1023                                          "no free loop device found",
1024                                 h->device ?: "");
1025                         if (!h->device) {
1026                                 log_err(NULL, _("Cannot find a free loopback device.\n"));
1027                                 r = -ENOSYS;
1028                                 goto bad;
1029                         }
1030
1031                         /* Keep the loop open, dettached on last close. */
1032                         h->loop_fd = crypt_loop_attach(h->device, device, 0, 1, &readonly);
1033                         if (h->loop_fd == -1) {
1034                                 log_err(NULL, _("Attaching loopback device failed "
1035                                         "(loop device with autoclear flag is required).\n"));
1036                                 r = -EINVAL;
1037                                 goto bad;
1038                         }
1039
1040                         h->backing_file = crypt_loop_backing_file(h->device);
1041                         r = device_ready(NULL, h->device, O_RDONLY);
1042                 }
1043                 if (r < 0) {
1044                         r = -ENOTBLK;
1045                         goto bad;
1046                 }
1047         }
1048
1049         if (!h->device && device && !(h->device = strdup(device))) {
1050                 r = -ENOMEM;
1051                 goto bad;
1052         }
1053
1054         if (dm_init(h, 1) < 0) {
1055                 r = -ENOSYS;
1056                 goto bad;
1057         }
1058
1059         h->iteration_time = 1000;
1060         h->password_verify = 0;
1061         h->tries = 3;
1062         h->rng_type = crypt_random_default_key_rng();
1063         *cd = h;
1064         return 0;
1065 bad:
1066
1067         if (h) {
1068                 if (h->loop_fd != -1)
1069                         close(h->loop_fd);
1070                 free(h->device);
1071                 free(h->backing_file);
1072         }
1073         free(h);
1074         return r;
1075 }
1076
1077 int crypt_init_by_name(struct crypt_device **cd, const char *name)
1078 {
1079         crypt_status_info ci;
1080         struct crypt_active_device cad;
1081         char *device = NULL, *cipher_full = NULL, *device_uuid = NULL;
1082         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
1083         char *key = NULL;
1084         int key_size = 0, key_nums, r;
1085
1086
1087         log_dbg("Allocating crypt device context by device %s.", name);
1088
1089         ci = crypt_status(NULL, name);
1090         if (ci == CRYPT_INVALID)
1091                 return -ENODEV;
1092
1093         if (ci < CRYPT_ACTIVE) {
1094                 log_err(NULL, _("Device %s is not active.\n"), name);
1095                 return -ENODEV;
1096         }
1097
1098         r = dm_query_device(name, &device, &cad.size, &cad.iv_offset, &cad.offset,
1099                             &cipher_full, &key_size, &key, NULL, NULL,
1100                             &device_uuid);
1101         if (r < 0)
1102                 goto out;
1103
1104         *cd = NULL;
1105         r = crypt_init(cd, device);
1106
1107         /* Underlying device disappeared but mapping still active */
1108         if (!device || r == -ENOTBLK)
1109                 log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
1110                             name);
1111
1112         /* Underlying device is not readable but crypt mapping exists */
1113         if (r == -ENOTBLK) {
1114                 free(device);
1115                 device = NULL;
1116                 r = crypt_init(cd, NULL);
1117         }
1118
1119         if (r < 0)
1120                 goto out;
1121
1122         /* Try to initialise basic parameters from active device */
1123
1124         if (!(*cd)->backing_file && device && crypt_loop_device(device) &&
1125             !((*cd)->backing_file = crypt_loop_backing_file(device))) {
1126                 r = -ENOMEM;
1127                 goto out;
1128         }
1129
1130         if (device_uuid) {
1131                 if (!strncmp(CRYPT_PLAIN, device_uuid, sizeof(CRYPT_PLAIN)-1)) {
1132                         (*cd)->type = strdup(CRYPT_PLAIN);
1133                         (*cd)->plain_uuid = strdup(device_uuid);
1134                         (*cd)->plain_hdr.hash = NULL; /* no way to get this */
1135                         (*cd)->plain_hdr.offset = cad.offset;
1136                         (*cd)->plain_hdr.skip = cad.iv_offset;
1137                         (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1138                         if (!(*cd)->volume_key) {
1139                                 r = -ENOMEM;
1140                                 goto out;
1141                         }
1142
1143                         r = crypt_parse_name_and_mode(cipher_full, cipher, NULL, cipher_mode);
1144                         if (!r) {
1145                                 (*cd)->plain_cipher = strdup(cipher);
1146                                 (*cd)->plain_cipher_mode = strdup(cipher_mode);
1147                         }
1148                 } else if (!strncmp(CRYPT_LOOPAES, device_uuid, sizeof(CRYPT_LOOPAES)-1)) {
1149                         (*cd)->type = strdup(CRYPT_LOOPAES);
1150                         (*cd)->loopaes_uuid = strdup(device_uuid);
1151                         (*cd)->loopaes_hdr.offset = cad.offset;
1152
1153                         r = crypt_parse_name_and_mode(cipher_full, cipher,
1154                                                       &key_nums, cipher_mode);
1155                         if (!r) {
1156                                 (*cd)->loopaes_cipher = strdup(cipher);
1157                                 (*cd)->loopaes_cipher_mode = strdup(cipher_mode);
1158                                 /* version 3 uses last key for IV */
1159                                 if (key_size % key_nums)
1160                                         key_nums++;
1161                                 (*cd)->loopaes_key_size = key_size / key_nums;
1162                         }
1163                 } else if (!strncmp(CRYPT_LUKS1, device_uuid, sizeof(CRYPT_LUKS1)-1)) {
1164                         if (device) {
1165                                 if (crypt_load(*cd, CRYPT_LUKS1, NULL) < 0 ||
1166                                     crypt_volume_key_verify(*cd, key, key_size) < 0) {
1167                                         log_dbg("LUKS device header does not match active device.");
1168                                         goto out;
1169                                 }
1170
1171                                 (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1172                                 if (!(*cd)->volume_key) {
1173                                         r = -ENOMEM;
1174                                         goto out;
1175                                 }
1176                         }
1177                 }
1178         } else
1179                 log_dbg("Active device has no UUID set, some parameters are not set.");
1180
1181 out:
1182         if (r < 0) {
1183                 crypt_free(*cd);
1184                 *cd = NULL;
1185         }
1186         crypt_safe_free(key);
1187         free(device);
1188         free(cipher_full);
1189         free(device_uuid);
1190         return r;
1191 }
1192
1193 static int _crypt_format_plain(struct crypt_device *cd,
1194                                const char *cipher,
1195                                const char *cipher_mode,
1196                                const char *uuid,
1197                                size_t volume_key_size,
1198                                struct crypt_params_plain *params)
1199 {
1200         if (!cipher || !cipher_mode) {
1201                 log_err(cd, _("Invalid plain crypt parameters.\n"));
1202                 return -EINVAL;
1203         }
1204
1205         if (volume_key_size > 1024) {
1206                 log_err(cd, _("Invalid key size.\n"));
1207                 return -EINVAL;
1208         }
1209
1210         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
1211         if (!cd->volume_key)
1212                 return -ENOMEM;
1213
1214         cd->plain_cipher = strdup(cipher);
1215         cd->plain_cipher_mode = strdup(cipher_mode);
1216
1217         if (uuid)
1218                 cd->plain_uuid = strdup(uuid);
1219
1220         if (params && params->hash)
1221                 cd->plain_hdr.hash = strdup(params->hash);
1222
1223         cd->plain_hdr.offset = params ? params->offset : 0;
1224         cd->plain_hdr.skip = params ? params->skip : 0;
1225
1226         if (!cd->plain_cipher || !cd->plain_cipher_mode)
1227                 return -ENOMEM;
1228
1229         return 0;
1230 }
1231
1232 static int _crypt_format_luks1(struct crypt_device *cd,
1233                                const char *cipher,
1234                                const char *cipher_mode,
1235                                const char *uuid,
1236                                const char *volume_key,
1237                                size_t volume_key_size,
1238                                struct crypt_params_luks1 *params)
1239 {
1240         int r;
1241         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1242         unsigned long alignment_offset = 0;
1243
1244         if (!cd->device) {
1245                 log_err(cd, _("Can't format LUKS without device.\n"));
1246                 return -EINVAL;
1247         }
1248
1249         if (volume_key)
1250                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1251                                                       volume_key);
1252         else
1253                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1254
1255         if(!cd->volume_key)
1256                 return -ENOMEM;
1257
1258         if (params && params->data_alignment)
1259                 required_alignment = params->data_alignment * SECTOR_SIZE;
1260         else
1261                 get_topology_alignment(cd->device, &required_alignment,
1262                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1263
1264         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
1265                                (params && params->hash) ? params->hash : "sha1",
1266                                uuid, LUKS_STRIPES,
1267                                required_alignment / SECTOR_SIZE,
1268                                alignment_offset / SECTOR_SIZE,
1269                                cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1270         if(r < 0)
1271                 return r;
1272
1273         /* Wipe first 8 sectors - fs magic numbers etc. */
1274         r = wipe_device_header(cd->device, 8);
1275         if(r < 0) {
1276                 if (r == -EBUSY)
1277                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
1278                                 cd->device);
1279                 else
1280                         log_err(cd, _("Cannot wipe header on device %s.\n"),
1281                                 cd->device);
1282
1283                 return r;
1284         }
1285
1286         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
1287
1288         return r;
1289 }
1290
1291 static int _crypt_format_loopaes(struct crypt_device *cd,
1292                                  const char *cipher,
1293                                  const char *uuid,
1294                                  size_t volume_key_size,
1295                                  struct crypt_params_loopaes *params)
1296 {
1297         if (!cd->device) {
1298                 log_err(cd, _("Can't format LOOPAES without device.\n"));
1299                 return -EINVAL;
1300         }
1301
1302         if (volume_key_size > 1024) {
1303                 log_err(cd, _("Invalid key size.\n"));
1304                 return -EINVAL;
1305         }
1306
1307         cd->loopaes_key_size = volume_key_size;
1308
1309         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1310
1311         if (uuid)
1312                 cd->loopaes_uuid = strdup(uuid);
1313
1314         if (params && params->hash)
1315                 cd->loopaes_hdr.hash = strdup(params->hash);
1316
1317         cd->loopaes_hdr.offset = params ? params->offset : 0;
1318         cd->loopaes_hdr.skip = params ? params->skip : 0;
1319
1320         return 0;
1321 }
1322
1323 int crypt_format(struct crypt_device *cd,
1324         const char *type,
1325         const char *cipher,
1326         const char *cipher_mode,
1327         const char *uuid,
1328         const char *volume_key,
1329         size_t volume_key_size,
1330         void *params)
1331 {
1332         int r;
1333
1334         if (!type)
1335                 return -EINVAL;
1336
1337         log_dbg("Formatting device %s as type %s.", cd->device ?: "(none)", type);
1338
1339         r = init_crypto(cd);
1340         if (r < 0)
1341                 return r;
1342
1343         if (isPLAIN(type))
1344                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1345                                         uuid, volume_key_size, params);
1346         else if (isLUKS(type))
1347                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1348                                         uuid, volume_key, volume_key_size, params);
1349         else if (isLOOPAES(type))
1350                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1351         else {
1352                 /* FIXME: allow plugins here? */
1353                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1354                 r = -EINVAL;
1355         }
1356
1357         if (!r && !(cd->type = strdup(type)))
1358                 r = -ENOMEM;
1359
1360         if (r < 0) {
1361                 crypt_free_volume_key(cd->volume_key);
1362                 cd->volume_key = NULL;
1363         }
1364
1365         return r;
1366 }
1367
1368 int crypt_load(struct crypt_device *cd,
1369                const char *requested_type,
1370                void *params)
1371 {
1372         struct luks_phdr hdr;
1373         int r;
1374
1375         log_dbg("Trying to load %s crypt type from device %s.",
1376                 requested_type ?: "any", cd->device ?: "(none)");
1377
1378         if (!cd->device)
1379                 return -EINVAL;
1380
1381         if (requested_type && !isLUKS(requested_type))
1382                 return -EINVAL;
1383
1384         r = init_crypto(cd);
1385         if (r < 0)
1386                 return r;
1387
1388         r = LUKS_read_phdr(cd->device, &hdr, 1, cd);
1389
1390         if (!r) {
1391                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
1392                 cd->type = strdup(CRYPT_LUKS1);
1393                 if (!cd->type)
1394                         r = -ENOMEM;
1395         }
1396
1397         return r;
1398 }
1399
1400 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1401 {
1402         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
1403         uint64_t size, skip, offset;
1404         int key_size, read_only, r;
1405
1406         /* Device context type must be initialised */
1407         if (!cd->type || !crypt_get_uuid(cd))
1408                 return -EINVAL;
1409
1410         r = dm_query_device(name, &device, &size, &skip, &offset,
1411                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
1412         if (r < 0) {
1413                 log_err(NULL, _("Device %s is not active.\n"), name);
1414                 goto out;
1415         }
1416
1417         if (!uuid) {
1418                 r = -EINVAL;
1419                 goto out;
1420         }
1421
1422         r = device_check_and_adjust(cd, device, 0, &new_size, &offset, &read_only);
1423         if (r)
1424                 goto out;
1425
1426         if (new_size == size) {
1427                 log_dbg("Device has already requested size %" PRIu64
1428                         " sectors.", size);
1429                 r = 0;
1430                 goto out;
1431         }
1432
1433         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1434
1435         r = dm_create_device(name, device, cipher, cd->type,
1436                              crypt_get_uuid(cd), new_size, skip, offset,
1437                              key_size, key, read_only, 1);
1438 out:
1439         crypt_safe_free(key);
1440         free(cipher);
1441         free(device);
1442         free(uuid);
1443
1444         return r;
1445 }
1446
1447 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1448 {
1449         if (!isLUKS(cd->type)) {
1450                 log_err(cd, _("This operation is not supported for this device type.\n"));
1451                 return  -EINVAL;
1452         }
1453
1454         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1455                 log_dbg("UUID is the same as requested (%s) for device %s.",
1456                         uuid, cd->device);
1457                 return 0;
1458         }
1459
1460         if (uuid)
1461                 log_dbg("Requested new UUID change to %s for %s.", uuid, cd->device);
1462         else
1463                 log_dbg("Requested new UUID refresh for %s.", cd->device);
1464
1465         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1466                 return -EPERM;
1467
1468         return LUKS_hdr_uuid_set(cd->device, &cd->hdr, uuid, cd);
1469 }
1470
1471 int crypt_header_backup(struct crypt_device *cd,
1472                         const char *requested_type,
1473                         const char *backup_file)
1474 {
1475         int r;
1476
1477         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1478                 return -EINVAL;
1479
1480         r = init_crypto(cd);
1481         if (r < 0)
1482                 return r;
1483
1484         log_dbg("Requested header backup of device %s (%s) to "
1485                 "file %s.", cd->device, requested_type, backup_file);
1486
1487         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
1488 }
1489
1490 int crypt_header_restore(struct crypt_device *cd,
1491                          const char *requested_type,
1492                          const char *backup_file)
1493 {
1494         int r;
1495
1496         if (requested_type && !isLUKS(requested_type))
1497                 return -EINVAL;
1498
1499         /* Some hash functions need initialized gcrypt library */
1500         r = init_crypto(cd);
1501         if (r < 0)
1502                 return r;
1503
1504         log_dbg("Requested header restore to device %s (%s) from "
1505                 "file %s.", cd->device, requested_type, backup_file);
1506
1507         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
1508 }
1509
1510 void crypt_free(struct crypt_device *cd)
1511 {
1512         if (cd) {
1513                 log_dbg("Releasing crypt device %s context.", cd->device);
1514
1515                 if (cd->loop_fd != -1)
1516                         close(cd->loop_fd);
1517
1518                 dm_exit();
1519                 crypt_free_volume_key(cd->volume_key);
1520
1521                 free(cd->device);
1522                 free(cd->backing_file);
1523                 free(cd->type);
1524
1525                 /* used in plain device only */
1526                 free((char*)cd->plain_hdr.hash);
1527                 free(cd->plain_cipher);
1528                 free(cd->plain_cipher_mode);
1529                 free(cd->plain_uuid);
1530
1531                 free(cd);
1532         }
1533 }
1534
1535 int crypt_suspend(struct crypt_device *cd,
1536                   const char *name)
1537 {
1538         crypt_status_info ci;
1539         int r, suspended = 0;
1540
1541         log_dbg("Suspending volume %s.", name);
1542
1543         ci = crypt_status(NULL, name);
1544         if (ci < CRYPT_ACTIVE) {
1545                 log_err(cd, _("Volume %s is not active.\n"), name);
1546                 return -EINVAL;
1547         }
1548
1549         if (!cd && dm_init(NULL, 1) < 0)
1550                 return -ENOSYS;
1551
1552         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1553                             NULL, NULL, NULL, NULL, &suspended, NULL);
1554         if (r < 0)
1555                 goto out;
1556
1557         if (suspended) {
1558                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1559                 r = -EINVAL;
1560                 goto out;
1561         }
1562
1563         r = dm_suspend_and_wipe_key(name);
1564         if (r == -ENOTSUP)
1565                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1566         else if (r)
1567                 log_err(cd, "Error during suspending device %s.\n", name);
1568 out:
1569         if (!cd)
1570                 dm_exit();
1571         return r;
1572 }
1573
1574 int crypt_resume_by_passphrase(struct crypt_device *cd,
1575                                const char *name,
1576                                int keyslot,
1577                                const char *passphrase,
1578                                size_t passphrase_size)
1579 {
1580         struct volume_key *vk = NULL;
1581         int r, suspended = 0;
1582
1583         log_dbg("Resuming volume %s.", name);
1584
1585         if (!isLUKS(cd->type)) {
1586                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1587                 r = -EINVAL;
1588                 goto out;
1589         }
1590
1591         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1592                             NULL, NULL, NULL, NULL, &suspended, NULL);
1593         if (r < 0)
1594                 return r;
1595
1596         if (!suspended) {
1597                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1598                 return -EINVAL;
1599         }
1600
1601         if (passphrase) {
1602                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1603                                            passphrase_size, &cd->hdr, &vk, cd);
1604         } else
1605                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1606
1607         if (r >= 0) {
1608                 keyslot = r;
1609                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1610                 if (r == -ENOTSUP)
1611                         log_err(cd, "Resume is not supported for device %s.\n", name);
1612                 else if (r)
1613                         log_err(cd, "Error during resuming device %s.\n", name);
1614         } else
1615                 r = keyslot;
1616 out:
1617         crypt_free_volume_key(vk);
1618         return r < 0 ? r : keyslot;
1619 }
1620
1621 int crypt_resume_by_keyfile(struct crypt_device *cd,
1622                             const char *name,
1623                             int keyslot,
1624                             const char *keyfile,
1625                             size_t keyfile_size)
1626 {
1627         struct volume_key *vk = NULL;
1628         char *passphrase_read = NULL;
1629         size_t passphrase_size_read;
1630         int r, suspended = 0;
1631
1632         log_dbg("Resuming volume %s.", name);
1633
1634         if (!isLUKS(cd->type)) {
1635                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1636                 r = -EINVAL;
1637                 goto out;
1638         }
1639
1640         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1641                             NULL, NULL, NULL, NULL, &suspended, NULL);
1642         if (r < 0)
1643                 return r;
1644
1645         if (!suspended) {
1646                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1647                 return -EINVAL;
1648         }
1649
1650         if (!keyfile)
1651                 return -EINVAL;
1652
1653         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1654                           &passphrase_size_read, keyfile, keyfile_size);
1655         if (r < 0)
1656                 goto out;
1657
1658         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1659                                    passphrase_size_read, &cd->hdr, &vk, cd);
1660         if (r < 0)
1661                 goto out;
1662
1663         keyslot = r;
1664         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1665         if (r)
1666                 log_err(cd, "Error during resuming device %s.\n", name);
1667 out:
1668         crypt_safe_free(passphrase_read);
1669         crypt_free_volume_key(vk);
1670         return r < 0 ? r : keyslot;
1671 }
1672
1673 // slot manipulation
1674 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1675         int keyslot, // -1 any
1676         const char *passphrase, // NULL -> terminal
1677         size_t passphrase_size,
1678         const char *new_passphrase, // NULL -> terminal
1679         size_t new_passphrase_size)
1680 {
1681         struct volume_key *vk = NULL;
1682         char *password = NULL, *new_password = NULL;
1683         size_t passwordLen, new_passwordLen;
1684         int r;
1685
1686         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1687                 "new passphrase %sprovided.",
1688                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1689
1690         if (!isLUKS(cd->type)) {
1691                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1692                 return -EINVAL;
1693         }
1694
1695         r = keyslot_verify_or_find_empty(cd, &keyslot);
1696         if (r)
1697                 return r;
1698
1699         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1700                 /* No slots used, try to use pre-generated key in header */
1701                 if (cd->volume_key) {
1702                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1703                         r = vk ? 0 : -ENOMEM;
1704                 } else {
1705                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1706                         return -EINVAL;
1707                 }
1708         } else if (passphrase) {
1709                 /* Passphrase provided, use it to unlock existing keyslot */
1710                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1711                                            passphrase_size, &cd->hdr, &vk, cd);
1712         } else {
1713                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1714                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1715                                       &password, &passwordLen, 0);
1716                 if (r < 0)
1717                         goto out;
1718
1719                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1720                                            passwordLen, &cd->hdr, &vk, cd);
1721                 crypt_safe_free(password);
1722         }
1723
1724         if(r < 0)
1725                 goto out;
1726
1727         if (new_passphrase) {
1728                 new_password = (char *)new_passphrase;
1729                 new_passwordLen = new_passphrase_size;
1730         } else {
1731                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1732                                       &new_password, &new_passwordLen, 1);
1733                 if(r < 0)
1734                         goto out;
1735         }
1736
1737         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1738                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1739         if(r < 0) goto out;
1740
1741         r = 0;
1742 out:
1743         if (!new_passphrase)
1744                 crypt_safe_free(new_password);
1745         crypt_free_volume_key(vk);
1746         return r ?: keyslot;
1747 }
1748
1749 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1750         int keyslot,
1751         const char *keyfile,
1752         size_t keyfile_size,
1753         const char *new_keyfile,
1754         size_t new_keyfile_size)
1755 {
1756         struct volume_key *vk = NULL;
1757         char *password = NULL; size_t passwordLen;
1758         char *new_password = NULL; size_t new_passwordLen;
1759         int r;
1760
1761         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1762                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1763
1764         if (!isLUKS(cd->type)) {
1765                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1766                 return -EINVAL;
1767         }
1768
1769         r = keyslot_verify_or_find_empty(cd, &keyslot);
1770         if (r)
1771                 return r;
1772
1773         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1774                 /* No slots used, try to use pre-generated key in header */
1775                 if (cd->volume_key) {
1776                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1777                         r = vk ? 0 : -ENOMEM;
1778                 } else {
1779                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1780                         return -EINVAL;
1781                 }
1782         } else {
1783                 /* Read password from file of (if NULL) from terminal */
1784                 if (keyfile)
1785                         r = key_from_file(cd, _("Enter any passphrase: "),
1786                                           &password, &passwordLen,
1787                                           keyfile, keyfile_size);
1788                 else
1789                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1790                                               &password, &passwordLen, 0);
1791                 if (r < 0)
1792                         goto out;
1793
1794                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1795                                            &cd->hdr, &vk, cd);
1796         }
1797
1798         if(r < 0)
1799                 goto out;
1800
1801         if (new_keyfile)
1802                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1803                                   &new_password, &new_passwordLen, new_keyfile,
1804                                   new_keyfile_size);
1805         else
1806                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1807                                       &new_password, &new_passwordLen, 1);
1808         if (r < 0)
1809                 goto out;
1810
1811         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1812                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1813 out:
1814         crypt_safe_free(password);
1815         crypt_safe_free(new_password);
1816         crypt_free_volume_key(vk);
1817         return r < 0 ? r : keyslot;
1818 }
1819
1820 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1821         int keyslot,
1822         const char *volume_key,
1823         size_t volume_key_size,
1824         const char *passphrase,
1825         size_t passphrase_size)
1826 {
1827         struct volume_key *vk = NULL;
1828         int r = -EINVAL;
1829         char *new_password = NULL; size_t new_passwordLen;
1830
1831         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1832
1833         if (!isLUKS(cd->type)) {
1834                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1835                 return -EINVAL;
1836         }
1837
1838         if (volume_key)
1839                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1840         else if (cd->volume_key)
1841                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1842
1843         if (!vk)
1844                 return -ENOMEM;
1845
1846         r = LUKS_verify_volume_key(&cd->hdr, vk);
1847         if (r < 0) {
1848                 log_err(cd, _("Volume key does not match the volume.\n"));
1849                 goto out;
1850         }
1851
1852         r = keyslot_verify_or_find_empty(cd, &keyslot);
1853         if (r)
1854                 goto out;
1855
1856         if (!passphrase) {
1857                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1858                                       &new_password, &new_passwordLen, 1);
1859                 if (r < 0)
1860                         goto out;
1861                 passphrase = new_password;
1862                 passphrase_size = new_passwordLen;
1863         }
1864
1865         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1866                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1867 out:
1868         crypt_safe_free(new_password);
1869         crypt_free_volume_key(vk);
1870         return (r < 0) ? r : keyslot;
1871 }
1872
1873 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1874 {
1875         crypt_keyslot_info ki;
1876
1877         log_dbg("Destroying keyslot %d.", keyslot);
1878
1879         if (!isLUKS(cd->type)) {
1880                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1881                 return -EINVAL;
1882         }
1883
1884         ki = crypt_keyslot_status(cd, keyslot);
1885         if (ki == CRYPT_SLOT_INVALID) {
1886                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1887                 return -EINVAL;
1888         }
1889
1890         if (ki == CRYPT_SLOT_INACTIVE) {
1891                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1892                 return -EINVAL;
1893         }
1894
1895         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1896 }
1897
1898 // activation/deactivation of device mapping
1899 int crypt_activate_by_passphrase(struct crypt_device *cd,
1900         const char *name,
1901         int keyslot,
1902         const char *passphrase,
1903         size_t passphrase_size,
1904         uint32_t flags)
1905 {
1906         crypt_status_info ci;
1907         struct volume_key *vk = NULL;
1908         char *read_passphrase = NULL;
1909         size_t passphraseLen = 0;
1910         int r;
1911
1912         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1913                 name ? "Activating" : "Checking", name ?: "",
1914                 keyslot, passphrase ? "" : "[none] ");
1915
1916         if (name) {
1917                 ci = crypt_status(NULL, name);
1918                 if (ci == CRYPT_INVALID)
1919                         return -EINVAL;
1920                 else if (ci >= CRYPT_ACTIVE) {
1921                         log_err(cd, _("Device %s already exists.\n"), name);
1922                         return -EEXIST;
1923                 }
1924         }
1925
1926         /* plain, use hashed passphrase */
1927         if (isPLAIN(cd->type)) {
1928                 if (!passphrase) {
1929                         r = key_from_terminal(cd, NULL, &read_passphrase,
1930                                               &passphraseLen, 0);
1931                         if (r < 0)
1932                                 goto out;
1933                         passphrase = read_passphrase;
1934                         passphrase_size = passphraseLen;
1935                 }
1936                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1937                                          cd->plain_cipher, cd->plain_cipher_mode,
1938                                          NULL, passphrase, passphrase_size,
1939                                          cd->volume_key->keylength, 0,
1940                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
1941                                          cd->plain_uuid,
1942                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1943                 keyslot = 0;
1944         } else if (isLUKS(cd->type)) {
1945                 /* provided passphrase, do not retry */
1946                 if (passphrase) {
1947                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1948                                                    passphrase_size, &cd->hdr, &vk, cd);
1949                 } else
1950                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1951
1952                 if (r >= 0) {
1953                         keyslot = r;
1954                         if (name)
1955                                 r = open_from_hdr_and_vk(cd, vk, name, flags);
1956                 }
1957         } else
1958                 r = -EINVAL;
1959 out:
1960         crypt_safe_free(read_passphrase);
1961         crypt_free_volume_key(vk);
1962
1963         return r < 0  ? r : keyslot;
1964 }
1965
1966 int crypt_activate_by_keyfile(struct crypt_device *cd,
1967         const char *name,
1968         int keyslot,
1969         const char *keyfile,
1970         size_t keyfile_size,
1971         uint32_t flags)
1972 {
1973         crypt_status_info ci;
1974         struct volume_key *vk = NULL;
1975         char *passphrase_read = NULL;
1976         size_t passphrase_size_read;
1977         unsigned int key_count = 0;
1978         int r;
1979
1980         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1981                 name ?: "", keyslot, keyfile ?: "[none]");
1982
1983         if (name) {
1984                 ci = crypt_status(NULL, name);
1985                 if (ci == CRYPT_INVALID)
1986                         return -EINVAL;
1987                 else if (ci >= CRYPT_ACTIVE) {
1988                         log_err(cd, _("Device %s already exists.\n"), name);
1989                         return -EEXIST;
1990                 }
1991         }
1992
1993         if (!keyfile)
1994                 return -EINVAL;
1995
1996         if (isPLAIN(cd->type)) {
1997                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1998                                   &passphrase_size_read, keyfile, keyfile_size);
1999                 if (r < 0)
2000                         goto out;
2001                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
2002                                          cd->plain_cipher, cd->plain_cipher_mode,
2003                                          NULL, passphrase_read, passphrase_size_read,
2004                                          cd->volume_key->keylength, 0,
2005                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
2006                                          cd->plain_uuid,
2007                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
2008         } else if (isLUKS(cd->type)) {
2009                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
2010                           &passphrase_size_read, keyfile, keyfile_size);
2011                 if (r < 0)
2012                         goto out;
2013                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
2014                                            passphrase_size_read, &cd->hdr, &vk, cd);
2015                 if (r < 0)
2016                         goto out;
2017                 keyslot = r;
2018
2019                 if (name) {
2020                         r = open_from_hdr_and_vk(cd, vk, name, flags);
2021                         if (r < 0)
2022                                 goto out;
2023                 }
2024                 r = keyslot;
2025         } else if (isLOOPAES(cd->type)) {
2026                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
2027                                   keyfile, keyfile_size);
2028                 if (r < 0)
2029                         goto out;
2030                 r = LOOPAES_parse_keyfile(cd, &vk, &key_count,
2031                                           passphrase_read, passphrase_size_read);
2032                 if (r < 0)
2033                         goto out;
2034                 if (name)
2035                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
2036                                              key_count, vk,
2037                                              cd->loopaes_hdr.offset,
2038                                              cd->loopaes_hdr.skip,
2039                                              flags);
2040         } else
2041                 r = -EINVAL;
2042
2043 out:
2044         crypt_safe_free(passphrase_read);
2045         crypt_free_volume_key(vk);
2046
2047         return r;
2048 }
2049
2050 int crypt_activate_by_volume_key(struct crypt_device *cd,
2051         const char *name,
2052         const char *volume_key,
2053         size_t volume_key_size,
2054         uint32_t flags)
2055 {
2056         crypt_status_info ci;
2057         struct volume_key *vk;
2058         int r;
2059
2060         log_dbg("Activating volume %s by volume key.", name);
2061
2062         /* use key directly, no hash */
2063         if (isPLAIN(cd->type)) {
2064                 if (!volume_key || !volume_key_size || !cd->volume_key ||
2065                         volume_key_size != cd->volume_key->keylength) {
2066                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
2067                         return -EINVAL;
2068                 }
2069
2070                 return create_device_helper(cd, name, NULL,
2071                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
2072                         cd->volume_key->keylength, 0, cd->plain_hdr.skip,
2073                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
2074         }
2075
2076         if (!isLUKS(cd->type)) {
2077                 log_err(cd, _("Device type is not properly initialised.\n"));
2078                 return -EINVAL;
2079         }
2080
2081         if (name) {
2082                 ci = crypt_status(NULL, name);
2083                 if (ci == CRYPT_INVALID)
2084                         return -EINVAL;
2085                 else if (ci >= CRYPT_ACTIVE) {
2086                         log_err(cd, _("Device %s already exists.\n"), name);
2087                         return -EEXIST;
2088                 }
2089         }
2090
2091         /* If key is not provided, try to use internal key */
2092         if (!volume_key) {
2093                 if (!cd->volume_key) {
2094                         log_err(cd, _("Volume key does not match the volume.\n"));
2095                         return -EINVAL;
2096                 }
2097                 volume_key_size = cd->volume_key->keylength;
2098                 volume_key = cd->volume_key->key;
2099         }
2100
2101         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2102         if (!vk)
2103                 return -ENOMEM;
2104         r = LUKS_verify_volume_key(&cd->hdr, vk);
2105
2106         if (r == -EPERM)
2107                 log_err(cd, _("Volume key does not match the volume.\n"));
2108
2109         if (!r && name)
2110                 r = open_from_hdr_and_vk(cd, vk, name, flags);
2111
2112         crypt_free_volume_key(vk);
2113
2114         return r;
2115 }
2116
2117 int crypt_deactivate(struct crypt_device *cd, const char *name)
2118 {
2119         int r;
2120
2121         if (!name)
2122                 return -EINVAL;
2123
2124         log_dbg("Deactivating volume %s.", name);
2125
2126         if (!cd && dm_init(NULL, 1) < 0)
2127                 return -ENOSYS;
2128
2129         switch (crypt_status(cd, name)) {
2130                 case CRYPT_ACTIVE:
2131                         r = dm_remove_device(name, 0, 0);
2132                         break;
2133                 case CRYPT_BUSY:
2134                         log_err(cd, _("Device %s is busy.\n"), name);
2135                         r = -EBUSY;
2136                         break;
2137                 case CRYPT_INACTIVE:
2138                         log_err(cd, _("Device %s is not active.\n"), name);
2139                         r = -ENODEV;
2140                         break;
2141                 default:
2142                         log_err(cd, _("Invalid device %s.\n"), name);
2143                         r = -EINVAL;
2144         }
2145
2146         if (!cd)
2147                 dm_exit();
2148
2149         return r;
2150 }
2151
2152 int crypt_volume_key_get(struct crypt_device *cd,
2153         int keyslot,
2154         char *volume_key,
2155         size_t *volume_key_size,
2156         const char *passphrase,
2157         size_t passphrase_size)
2158 {
2159         struct volume_key *vk;
2160         char *processed_key = NULL;
2161         int r, key_len;
2162
2163         key_len = crypt_get_volume_key_size(cd);
2164         if (key_len > *volume_key_size) {
2165                 log_err(cd, _("Volume key buffer too small.\n"));
2166                 return -ENOMEM;
2167         }
2168
2169         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2170                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
2171                                             passphrase, passphrase_size);
2172                 if (!processed_key) {
2173                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2174                         return -EINVAL;
2175                 }
2176                 memcpy(volume_key, processed_key, key_len);
2177                 *volume_key_size = key_len;
2178                 crypt_safe_free(processed_key);
2179                 return 0;
2180         }
2181
2182         if (isLUKS(cd->type)) {
2183                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
2184                                         passphrase_size, &cd->hdr, &vk, cd);
2185
2186                 if (r >= 0) {
2187                         memcpy(volume_key, vk->key, vk->keylength);
2188                         *volume_key_size = vk->keylength;
2189                 }
2190
2191                 crypt_free_volume_key(vk);
2192                 return r;
2193         }
2194
2195         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2196         return -EINVAL;
2197 }
2198
2199 int crypt_volume_key_verify(struct crypt_device *cd,
2200         const char *volume_key,
2201         size_t volume_key_size)
2202 {
2203         struct volume_key *vk;
2204         int r;
2205
2206         if (!isLUKS(cd->type)) {
2207                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2208                 return -EINVAL;
2209         }
2210
2211         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2212         if (!vk)
2213                 return -ENOMEM;
2214
2215         r = LUKS_verify_volume_key(&cd->hdr, vk);
2216
2217         if (r == -EPERM)
2218                 log_err(cd, _("Volume key does not match the volume.\n"));
2219
2220         crypt_free_volume_key(vk);
2221
2222         return r;
2223 }
2224
2225 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2226 {
2227         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2228         cd->timeout = timeout_sec;
2229 }
2230
2231 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2232 {
2233         log_dbg("Password retry count set to %d.", tries);
2234         cd->tries = tries;
2235 }
2236
2237 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2238 {
2239         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2240         cd->iteration_time = iteration_time_ms;
2241 }
2242
2243 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2244 {
2245         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2246         cd->password_verify = password_verify ? 1 : 0;
2247 }
2248
2249 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2250 {
2251         switch (rng_type) {
2252         case CRYPT_RNG_URANDOM:
2253         case CRYPT_RNG_RANDOM:
2254                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2255                 cd->rng_type = rng_type;
2256         }
2257 }
2258
2259 int crypt_get_rng_type(struct crypt_device *cd)
2260 {
2261         if (!cd)
2262                 return -EINVAL;
2263
2264         return cd->rng_type;
2265 }
2266
2267 int crypt_memory_lock(struct crypt_device *cd, int lock)
2268 {
2269         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2270 }
2271
2272 // reporting
2273 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2274 {
2275         int r;
2276
2277         if (!cd && dm_init(NULL, 1) < 0)
2278                 return CRYPT_INVALID;
2279
2280         r = dm_status_device(name);
2281
2282         if (!cd)
2283                 dm_exit();
2284
2285         if (r < 0 && r != -ENODEV)
2286                 return CRYPT_INVALID;
2287
2288         if (r == 0)
2289                 return CRYPT_ACTIVE;
2290
2291         if (r > 0)
2292                 return CRYPT_BUSY;
2293
2294         return CRYPT_INACTIVE;
2295 }
2296
2297 static void hexprintICB(struct crypt_device *cd, char *d, int n)
2298 {
2299         int i;
2300         for(i = 0; i < n; i++)
2301                 log_std(cd, "%02hhx ", (char)d[i]);
2302 }
2303
2304 int crypt_dump(struct crypt_device *cd)
2305 {
2306         int i;
2307         if (!isLUKS(cd->type)) { //FIXME
2308                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2309                 return -EINVAL;
2310         }
2311
2312         log_std(cd, "LUKS header information for %s\n\n", cd->device);
2313         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2314         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2315         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2316         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2317         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2318         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2319         log_std(cd, "MK digest:     \t");
2320         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
2321         log_std(cd, "\n");
2322         log_std(cd, "MK salt:       \t");
2323         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
2324         log_std(cd, "\n               \t");
2325         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2326         log_std(cd, "\n");
2327         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2328         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2329         for(i = 0; i < LUKS_NUMKEYS; i++) {
2330                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2331                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2332                         log_std(cd, "\tIterations:         \t%d\n",
2333                                 cd->hdr.keyblock[i].passwordIterations);
2334                         log_std(cd, "\tSalt:               \t");
2335                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
2336                                     LUKS_SALTSIZE/2);
2337                         log_std(cd, "\n\t                      \t");
2338                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
2339                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2340                         log_std(cd, "\n");
2341
2342                         log_std(cd, "\tKey material offset:\t%d\n",
2343                                 cd->hdr.keyblock[i].keyMaterialOffset);
2344                         log_std(cd, "\tAF stripes:            \t%d\n",
2345                                 cd->hdr.keyblock[i].stripes);
2346                 }
2347                 else 
2348                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2349         }
2350
2351         return 0;
2352 }
2353
2354 const char *crypt_get_cipher(struct crypt_device *cd)
2355 {
2356         if (isPLAIN(cd->type))
2357                 return cd->plain_cipher;
2358
2359         if (isLUKS(cd->type))
2360                 return cd->hdr.cipherName;
2361
2362         if (isLOOPAES(cd->type))
2363                 return cd->loopaes_cipher;
2364
2365         return NULL;
2366 }
2367
2368 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2369 {
2370         if (isPLAIN(cd->type))
2371                 return cd->plain_cipher_mode;
2372
2373         if (isLUKS(cd->type))
2374                 return cd->hdr.cipherMode;
2375
2376         if (isLOOPAES(cd->type))
2377                 return cd->loopaes_cipher_mode;
2378
2379         return NULL;
2380 }
2381
2382 const char *crypt_get_uuid(struct crypt_device *cd)
2383 {
2384         if (isLUKS(cd->type))
2385                 return cd->hdr.uuid;
2386
2387         if (isPLAIN(cd->type))
2388                 return cd->plain_uuid;
2389
2390         if (isLOOPAES(cd->type))
2391                 return cd->loopaes_uuid;
2392
2393         return NULL;
2394 }
2395
2396 const char *crypt_get_device_name(struct crypt_device *cd)
2397 {
2398         return cd->device;
2399 }
2400
2401 int crypt_get_volume_key_size(struct crypt_device *cd)
2402 {
2403         if (isPLAIN(cd->type) && cd->volume_key)
2404                 return cd->volume_key->keylength;
2405
2406         if (isLUKS(cd->type))
2407                 return cd->hdr.keyBytes;
2408
2409         if (isLOOPAES(cd->type))
2410                 return cd->loopaes_key_size;
2411
2412         return 0;
2413 }
2414
2415 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2416 {
2417         if (isPLAIN(cd->type))
2418                 return cd->plain_hdr.offset;
2419
2420         if (isLUKS(cd->type))
2421                 return cd->hdr.payloadOffset;
2422
2423         if (isLOOPAES(cd->type))
2424                 return cd->loopaes_hdr.offset;
2425
2426         return 0;
2427 }
2428
2429 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2430 {
2431         if (!isLUKS(cd->type)) {
2432                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2433                 return CRYPT_SLOT_INVALID;
2434         }
2435
2436         return LUKS_keyslot_info(&cd->hdr, keyslot);
2437 }
2438
2439 int crypt_keyslot_max(const char *type)
2440 {
2441         if (type && isLUKS(type))
2442                 return LUKS_NUMKEYS;
2443
2444         return -EINVAL;
2445 }
2446
2447 const char *crypt_get_type(struct crypt_device *cd)
2448 {
2449         return cd->type;
2450 }
2451
2452 int crypt_get_active_device(struct crypt_device *cd,
2453                             const char *name,
2454                             struct crypt_active_device *cad)
2455 {
2456         int r, readonly;
2457
2458         r = dm_query_device(name, NULL, &cad->size, &cad->iv_offset, &cad->offset,
2459                             NULL, NULL, NULL, &readonly, NULL, NULL);
2460         if (r < 0)
2461                 return r;
2462
2463         cad->flags = readonly ? CRYPT_ACTIVATE_READONLY : 0;
2464
2465         return 0;
2466 }