Remove unused paramater.
[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, 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                 crypt_safe_free(passphrase_read);
513                 passphrase_read = NULL;
514         } while (r == -EPERM && (--tries > 0));
515 out:
516         if (r < 0) {
517                 crypt_free_volume_key(*vk);
518                 *vk = NULL;
519         }
520
521         crypt_safe_free(passphrase_read);
522         return r;
523 }
524
525 static int key_from_file(struct crypt_device *cd, char *msg,
526                           char **key, size_t *key_len,
527                           const char *key_file, size_t key_size)
528 {
529         return crypt_get_key(msg, key, key_len, key_size, key_file,
530                              cd->timeout, 0, cd);
531 }
532
533 static int _crypt_init(struct crypt_device **cd,
534                        const char *type,
535                        struct crypt_options *options,
536                        int load, int need_dm)
537 {
538         int init_by_name, r;
539
540         /* if it is plain device and mapping table is being reloaded
541         initialize it by name*/
542         init_by_name = (type && !strcmp(type, CRYPT_PLAIN) && load);
543
544         /* Some of old API calls do not require DM in kernel,
545            fake initialisation by initialise it with kernel_check disabled */
546         if (!need_dm)
547                 (void)dm_init(NULL, 0);
548         if (init_by_name)
549                 r = crypt_init_by_name(cd, options->name);
550         else
551                 r = crypt_init(cd, options->device);
552         if (!need_dm)
553                 dm_exit();
554
555         if (r)
556                 return -EINVAL;
557
558         crypt_set_log_callback(*cd, log_wrapper, options->icb->log);
559         crypt_set_confirm_callback(*cd, yesDialog_wrapper, options->icb->yesDialog);
560
561         crypt_set_timeout(*cd, options->timeout);
562         crypt_set_password_retry(*cd, options->tries);
563         crypt_set_iterarion_time(*cd, options->iteration_time ?: 1000);
564         crypt_set_password_verify(*cd, options->flags & CRYPT_FLAG_VERIFY);
565
566         if (load && !init_by_name)
567                 r = crypt_load(*cd, type, NULL);
568
569         if (!r && type && !(*cd)->type) {
570                 (*cd)->type = strdup(type);
571                 if (!(*cd)->type)
572                         r = -ENOMEM;
573         }
574
575         if (r)
576                 crypt_free(*cd);
577
578         return r;
579 }
580
581 void crypt_set_log_callback(struct crypt_device *cd,
582         void (*log)(int level, const char *msg, void *usrptr),
583         void *usrptr)
584 {
585         if (!cd)
586                 _default_log = log;
587         else {
588                 cd->log = log;
589                 cd->log_usrptr = usrptr;
590         }
591 }
592
593 void crypt_set_confirm_callback(struct crypt_device *cd,
594         int (*confirm)(const char *msg, void *usrptr),
595         void *usrptr)
596 {
597         cd->confirm = confirm;
598         cd->confirm_usrptr = usrptr;
599 }
600
601 void crypt_set_password_callback(struct crypt_device *cd,
602         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
603         void *usrptr)
604 {
605         cd->password = password;
606         cd->password_usrptr = usrptr;
607 }
608
609 /* OPTIONS: name, cipher, device, hash, key_file, key_size, key_slot,
610  *          offset, size, skip, timeout, tries, passphrase_fd (ignored),
611  *          flags, icb */
612 static int crypt_create_and_update_device(struct crypt_options *options, int update)
613 {
614         struct crypt_device *cd = NULL;
615         char *passphrase = NULL;
616         size_t passphrase_size = 0;
617         int r;
618
619         r = _crypt_init(&cd, CRYPT_PLAIN, options, 0, 1);
620         if (r)
621                 return r;
622
623         r = crypt_get_key(_("Enter passphrase: "), &passphrase, &passphrase_size,
624                           options->key_size, options->key_file,
625                           cd->timeout, cd->password_verify, cd);
626         if (!r)
627                 r = create_device_helper(cd, options->name, options->hash,
628                         options->cipher, NULL, options->key_file,
629                         passphrase, passphrase_size,
630                         options->key_size, options->size, options->skip,
631                         options->offset, NULL, options->flags & CRYPT_FLAG_READONLY,
632                         options->flags, update);
633
634         crypt_safe_free(passphrase);
635         crypt_free(cd);
636         return r;
637 }
638
639 int crypt_create_device(struct crypt_options *options)
640 {
641         return crypt_create_and_update_device(options, 0);
642 }
643
644 int crypt_update_device(struct crypt_options *options)
645 {
646         return crypt_create_and_update_device(options, 1);
647 }
648
649 /* OPTIONS: name, size, icb */
650 int crypt_resize_device(struct crypt_options *options)
651 {
652         struct crypt_device *cd = NULL;
653         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
654         char *type = NULL;
655         uint64_t size, skip, offset;
656         int key_size, read_only, r;
657
658         log_dbg("Resizing device %s to %" PRIu64 " sectors.", options->name, options->size);
659
660         if (dm_init(NULL, 1) < 0)
661                 return -ENOSYS;
662
663         r = dm_query_device(options->name, &device, &size, &skip, &offset,
664                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
665         if (r < 0) {
666                 log_err(NULL, _("Device %s is not active.\n"), options->name);
667                 goto out;
668         }
669
670         /* Try to determine type of device from UUID */
671         type = CRYPT_PLAIN;
672         if (uuid) {
673                 if (!strncmp(uuid, CRYPT_PLAIN, strlen(CRYPT_PLAIN))) {
674                         type = CRYPT_PLAIN;
675                         free (uuid);
676                         uuid = NULL;
677                 } else if (!strncmp(uuid, CRYPT_LUKS1, strlen(CRYPT_LUKS1)))
678                         type = CRYPT_LUKS1;
679         }
680
681         if (!options->device)
682                 options->device = device;
683
684         r = _crypt_init(&cd, type, options, 1, 1);
685         if (r)
686                 goto out;
687
688         size = options->size;
689         r = device_check_and_adjust(cd, device, 0, &size, &offset, &read_only);
690         if (r)
691                 goto out;
692
693         r = dm_create_device(options->name, device, cipher, type,
694                              crypt_get_uuid(cd), size, skip, offset,
695                              key_size, key, read_only, 1);
696 out:
697         crypt_safe_free(key);
698         free(cipher);
699         if (options->device == device)
700                 options->device = NULL;
701         free(device);
702         free(uuid);
703         crypt_free(cd);
704         dm_exit();
705         return r;
706 }
707
708 /* OPTIONS: name, icb */
709 int crypt_query_device(struct crypt_options *options)
710 {
711         int read_only, r;
712
713         log_dbg("Query device %s.", options->name);
714
715         if (dm_init(NULL, 1) < 0)
716                 return -ENOSYS;
717
718         r = dm_status_device(options->name);
719         if (r < 0)
720                 goto out;
721
722         r = dm_query_device(options->name, (char **)&options->device, &options->size,
723                             &options->skip, &options->offset, (char **)&options->cipher,
724                             &options->key_size, NULL, &read_only, NULL, NULL);
725         if (r >= 0) {
726                 if (read_only)
727                         options->flags |= CRYPT_FLAG_READONLY;
728
729                 options->flags |= CRYPT_FLAG_FREE_DEVICE;
730                 options->flags |= CRYPT_FLAG_FREE_CIPHER;
731
732                 r = 1;
733         }
734 out:
735         if (r == -ENODEV)
736                 r = 0;
737
738         dm_exit();
739         return r;
740 }
741
742 /* OPTIONS: name, icb */
743 int crypt_remove_device(struct crypt_options *options)
744 {
745         struct crypt_device *cd = NULL;
746         int r;
747
748         r = crypt_init_by_name(&cd, options->name);
749         if (r == 0)
750                 r = crypt_deactivate(cd, options->name);
751
752         crypt_free(cd);
753         return r;
754
755 }
756
757 /* OPTIONS: device, cipher, hash, align_payload, key_size (master key), key_slot
758  *          new_key_file, iteration_time, timeout, flags, icb */
759 int crypt_luksFormat(struct crypt_options *options)
760 {
761         char cipherName[LUKS_CIPHERNAME_L];
762         char cipherMode[LUKS_CIPHERMODE_L];
763         char *password=NULL;
764         size_t passwordLen;
765         struct crypt_device *cd = NULL;
766         struct crypt_params_luks1 cp = {
767                 .hash = options->hash,
768                 .data_alignment = options->align_payload
769         };
770         int r;
771
772         r = crypt_parse_name_and_mode(options->cipher, cipherName, NULL, cipherMode);
773         if(r < 0) {
774                 log_err(cd, _("No known cipher specification pattern detected.\n"));
775                 return r;
776         }
777
778         if ((r = _crypt_init(&cd, CRYPT_LUKS1, options, 0, 1)))
779                 return r;
780
781         if (options->key_slot >= LUKS_NUMKEYS && options->key_slot != CRYPT_ANY_SLOT) {
782                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
783                         options->key_slot, LUKS_NUMKEYS - 1);
784                 r = -EINVAL;
785                 goto out;
786         }
787
788         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen, 0,
789                           options->new_key_file, cd->timeout, cd->password_verify, cd);
790
791         if(r < 0)
792                 goto out;
793
794         r = crypt_format(cd, CRYPT_LUKS1, cipherName, cipherMode,
795                          NULL, NULL, options->key_size, &cp);
796         if (r < 0)
797                 goto out;
798
799         /* Add keyslot using internally stored volume key generated during format */
800         r = crypt_keyslot_add_by_volume_key(cd, options->key_slot, NULL, 0,
801                                             password, passwordLen);
802 out:
803         crypt_free(cd);
804         crypt_safe_free(password);
805         return (r < 0) ? r : 0;
806 }
807
808 /* OPTIONS: name, device, key_size, key_file, timeout, tries, flags, icb */
809 int crypt_luksOpen(struct crypt_options *options)
810 {
811         struct crypt_device *cd = NULL;
812         uint32_t flags = 0;
813         int r;
814
815         if (!options->name)
816                 return -EINVAL;
817
818         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
819         if (r)
820                 return r;
821
822         if (options->flags & CRYPT_FLAG_READONLY)
823                 flags |= CRYPT_ACTIVATE_READONLY;
824
825         if (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS)
826                 flags |= CRYPT_ACTIVATE_NO_UUID;
827
828         if (options->key_file)
829                 r = crypt_activate_by_keyfile(cd, options->name,
830                         CRYPT_ANY_SLOT, options->key_file, 0,
831                         flags);
832         else
833                 r = crypt_activate_by_passphrase(cd, options->name,
834                         CRYPT_ANY_SLOT, options->passphrase,
835                         options->passphrase ? strlen(options->passphrase) : 0,
836                         flags);
837
838         crypt_free(cd);
839         return (r < 0) ? r : 0;
840 }
841
842 /* OPTIONS: device, keys_slot, key_file, timeout, flags, icb */
843 int crypt_luksKillSlot(struct crypt_options *options)
844 {
845         struct crypt_device *cd = NULL;
846         int r;
847
848         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
849         if (r)
850                 return r;
851
852         r = luks_remove_helper(cd, options->key_slot, options->key_file, NULL,
853                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
854
855         crypt_free(cd);
856         return (r < 0) ? r : 0;
857 }
858
859 /* OPTIONS: device, new_key_file, key_file, timeout, flags, icb */
860 int crypt_luksRemoveKey(struct crypt_options *options)
861 {
862         struct crypt_device *cd = NULL;
863         int r;
864
865         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
866         if (r)
867                 return r;
868
869         r = luks_remove_helper(cd, CRYPT_ANY_SLOT, options->key_file, options->new_key_file,
870                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
871
872         crypt_free(cd);
873         return (r < 0) ? r : 0;
874 }
875
876
877 /* OPTIONS: device, new_key_file, key_file, key_slot, flags,
878             iteration_time, timeout, icb */
879 int crypt_luksAddKey(struct crypt_options *options)
880 {
881         struct crypt_device *cd = NULL;
882         int r = -EINVAL;
883
884         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
885         if (r)
886                 return r;
887
888         if (options->key_file || options->new_key_file)
889                 r = crypt_keyslot_add_by_keyfile(cd, options->key_slot,
890                                                  options->key_file, 0,
891                                                  options->new_key_file, 0);
892         else
893                 r = crypt_keyslot_add_by_passphrase(cd, options->key_slot,
894                                                     NULL, 0, NULL, 0);
895
896         crypt_free(cd);
897         return (r < 0) ? r : 0;
898 }
899
900 /* OPTIONS: device, icb */
901 int crypt_luksUUID(struct crypt_options *options)
902 {
903         struct crypt_device *cd = NULL;
904         char *uuid;
905         int r;
906
907         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
908         if (r)
909                 return r;
910
911         uuid = (char *)crypt_get_uuid(cd);
912         log_std(cd, uuid ?: "");
913         log_std(cd, "\n");
914         crypt_free(cd);
915         return 0;
916 }
917
918 /* OPTIONS: device, icb */
919 int crypt_isLuks(struct crypt_options *options)
920 {
921         struct crypt_device *cd = NULL;
922         int r;
923
924         log_dbg("Check device %s for LUKS header.", options->device);
925
926         r = init_crypto(cd);
927         if (r < 0)
928                 return r;
929
930         r = crypt_init(&cd, options->device);
931         if (r < 0)
932                 return -EINVAL;
933
934         /* Do print fail here, no need to crypt_load() */
935         r = LUKS_read_phdr(cd->device, &cd->hdr, 0, cd) ? -EINVAL : 0;
936
937         crypt_free(cd);
938         return r;
939 }
940
941 /* OPTIONS: device, icb */
942 int crypt_luksDump(struct crypt_options *options)
943 {
944         struct crypt_device *cd = NULL;
945         int r;
946
947         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
948         if(r < 0)
949                 return r;
950
951         r = crypt_dump(cd);
952
953         crypt_free(cd);
954         return r;
955 }
956
957 void crypt_get_error(char *buf, size_t size)
958 {
959         const char *error = get_error();
960
961         if (!buf || size < 1)
962                 set_error(NULL);
963         else if (error) {
964                 strncpy(buf, error, size - 1);
965                 buf[size - 1] = '\0';
966                 set_error(NULL);
967         } else
968                 buf[0] = '\0';
969 }
970
971 void crypt_put_options(struct crypt_options *options)
972 {
973         if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
974                 free((char *)options->device);
975                 options->device = NULL;
976                 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
977         }
978         if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
979                 free((char *)options->cipher);
980                 options->cipher = NULL;
981                 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
982         }
983 }
984
985 const char *crypt_get_dir(void)
986 {
987         return dm_get_dir();
988 }
989
990 /////////////////////////////////
991 //
992 // New API
993 //
994
995 int crypt_init(struct crypt_device **cd, const char *device)
996 {
997         struct crypt_device *h = NULL;
998         int r, readonly = 0;
999
1000         if (!cd)
1001                 return -EINVAL;
1002
1003         log_dbg("Allocating crypt device %s context.", device);
1004
1005         if (!(h = malloc(sizeof(struct crypt_device))))
1006                 return -ENOMEM;
1007
1008         memset(h, 0, sizeof(*h));
1009         h->loop_fd = -1;
1010
1011         if (device) {
1012                 r = device_ready(NULL, device, O_RDONLY);
1013                 if (r == -ENOTBLK) {
1014                         h->device = crypt_loop_get_device();
1015                         log_dbg("Not a block device, %s%s.",
1016                                 h->device ? "using free loop device " :
1017                                          "no free loop device found",
1018                                 h->device ?: "");
1019                         if (!h->device) {
1020                                 log_err(NULL, _("Cannot find a free loopback device.\n"));
1021                                 r = -ENOSYS;
1022                                 goto bad;
1023                         }
1024
1025                         /* Keep the loop open, dettached on last close. */
1026                         h->loop_fd = crypt_loop_attach(h->device, device, 0, 1, &readonly);
1027                         if (h->loop_fd == -1) {
1028                                 log_err(NULL, _("Attaching loopback device failed "
1029                                         "(loop device with autoclear flag is required).\n"));
1030                                 r = -EINVAL;
1031                                 goto bad;
1032                         }
1033
1034                         h->backing_file = crypt_loop_backing_file(h->device);
1035                         r = device_ready(NULL, h->device, O_RDONLY);
1036                 }
1037                 if (r < 0) {
1038                         r = -ENOTBLK;
1039                         goto bad;
1040                 }
1041         }
1042
1043         if (!h->device && device && !(h->device = strdup(device))) {
1044                 r = -ENOMEM;
1045                 goto bad;
1046         }
1047
1048         if (dm_init(h, 1) < 0) {
1049                 r = -ENOSYS;
1050                 goto bad;
1051         }
1052
1053         h->iteration_time = 1000;
1054         h->password_verify = 0;
1055         h->tries = 3;
1056         h->rng_type = crypt_random_default_key_rng();
1057         *cd = h;
1058         return 0;
1059 bad:
1060
1061         if (h) {
1062                 if (h->loop_fd != -1)
1063                         close(h->loop_fd);
1064                 free(h->device);
1065                 free(h->backing_file);
1066         }
1067         free(h);
1068         return r;
1069 }
1070
1071 int crypt_init_by_name(struct crypt_device **cd, const char *name)
1072 {
1073         crypt_status_info ci;
1074         struct crypt_active_device cad;
1075         char *device = NULL, *cipher_full = NULL, *device_uuid = NULL;
1076         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
1077         char *key = NULL;
1078         int key_size = 0, key_nums, r;
1079
1080
1081         log_dbg("Allocating crypt device context by device %s.", name);
1082
1083         ci = crypt_status(NULL, name);
1084         if (ci == CRYPT_INVALID)
1085                 return -ENODEV;
1086
1087         if (ci < CRYPT_ACTIVE) {
1088                 log_err(NULL, _("Device %s is not active.\n"), name);
1089                 return -ENODEV;
1090         }
1091
1092         r = dm_query_device(name, &device, &cad.size, &cad.iv_offset, &cad.offset,
1093                             &cipher_full, &key_size, &key, NULL, NULL,
1094                             &device_uuid);
1095         if (r < 0)
1096                 goto out;
1097
1098         *cd = NULL;
1099         r = crypt_init(cd, device);
1100
1101         /* Underlying device disappeared but mapping still active */
1102         if (!device || r == -ENOTBLK)
1103                 log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
1104                             name);
1105
1106         /* Underlying device is not readable but crypt mapping exists */
1107         if (r == -ENOTBLK) {
1108                 free(device);
1109                 device = NULL;
1110                 r = crypt_init(cd, NULL);
1111         }
1112
1113         if (r < 0)
1114                 goto out;
1115
1116         /* Try to initialise basic parameters from active device */
1117
1118         if (!(*cd)->backing_file && device && crypt_loop_device(device) &&
1119             !((*cd)->backing_file = crypt_loop_backing_file(device))) {
1120                 r = -ENOMEM;
1121                 goto out;
1122         }
1123
1124         if (device_uuid) {
1125                 if (!strncmp(CRYPT_PLAIN, device_uuid, sizeof(CRYPT_PLAIN)-1)) {
1126                         (*cd)->type = strdup(CRYPT_PLAIN);
1127                         (*cd)->plain_uuid = strdup(device_uuid);
1128                         (*cd)->plain_hdr.hash = NULL; /* no way to get this */
1129                         (*cd)->plain_hdr.offset = cad.offset;
1130                         (*cd)->plain_hdr.skip = cad.iv_offset;
1131                         (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1132                         if (!(*cd)->volume_key) {
1133                                 r = -ENOMEM;
1134                                 goto out;
1135                         }
1136
1137                         r = crypt_parse_name_and_mode(cipher_full, cipher, NULL, cipher_mode);
1138                         if (!r) {
1139                                 (*cd)->plain_cipher = strdup(cipher);
1140                                 (*cd)->plain_cipher_mode = strdup(cipher_mode);
1141                         }
1142                 } else if (!strncmp(CRYPT_LOOPAES, device_uuid, sizeof(CRYPT_LOOPAES)-1)) {
1143                         (*cd)->type = strdup(CRYPT_LOOPAES);
1144                         (*cd)->loopaes_uuid = strdup(device_uuid);
1145                         (*cd)->loopaes_hdr.offset = cad.offset;
1146
1147                         r = crypt_parse_name_and_mode(cipher_full, cipher,
1148                                                       &key_nums, cipher_mode);
1149                         if (!r) {
1150                                 (*cd)->loopaes_cipher = strdup(cipher);
1151                                 (*cd)->loopaes_cipher_mode = strdup(cipher_mode);
1152                                 /* version 3 uses last key for IV */
1153                                 if (key_size % key_nums)
1154                                         key_nums++;
1155                                 (*cd)->loopaes_key_size = key_size / key_nums;
1156                         }
1157                 } else if (!strncmp(CRYPT_LUKS1, device_uuid, sizeof(CRYPT_LUKS1)-1)) {
1158                         if (device) {
1159                                 if (crypt_load(*cd, CRYPT_LUKS1, NULL) < 0 ||
1160                                     crypt_volume_key_verify(*cd, key, key_size) < 0) {
1161                                         log_dbg("LUKS device header does not match active device.");
1162                                         goto out;
1163                                 }
1164
1165                                 (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1166                                 if (!(*cd)->volume_key) {
1167                                         r = -ENOMEM;
1168                                         goto out;
1169                                 }
1170                         }
1171                 }
1172         } else
1173                 log_dbg("Active device has no UUID set, some parameters are not set.");
1174
1175 out:
1176         if (r < 0) {
1177                 crypt_free(*cd);
1178                 *cd = NULL;
1179         }
1180         crypt_safe_free(key);
1181         free(device);
1182         free(cipher_full);
1183         free(device_uuid);
1184         return r;
1185 }
1186
1187 static int _crypt_format_plain(struct crypt_device *cd,
1188                                const char *cipher,
1189                                const char *cipher_mode,
1190                                const char *uuid,
1191                                size_t volume_key_size,
1192                                struct crypt_params_plain *params)
1193 {
1194         if (!cipher || !cipher_mode) {
1195                 log_err(cd, _("Invalid plain crypt parameters.\n"));
1196                 return -EINVAL;
1197         }
1198
1199         if (volume_key_size > 1024) {
1200                 log_err(cd, _("Invalid key size.\n"));
1201                 return -EINVAL;
1202         }
1203
1204         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
1205         if (!cd->volume_key)
1206                 return -ENOMEM;
1207
1208         cd->plain_cipher = strdup(cipher);
1209         cd->plain_cipher_mode = strdup(cipher_mode);
1210
1211         if (uuid)
1212                 cd->plain_uuid = strdup(uuid);
1213
1214         if (params && params->hash)
1215                 cd->plain_hdr.hash = strdup(params->hash);
1216
1217         cd->plain_hdr.offset = params ? params->offset : 0;
1218         cd->plain_hdr.skip = params ? params->skip : 0;
1219
1220         if (!cd->plain_cipher || !cd->plain_cipher_mode)
1221                 return -ENOMEM;
1222
1223         return 0;
1224 }
1225
1226 static int _crypt_format_luks1(struct crypt_device *cd,
1227                                const char *cipher,
1228                                const char *cipher_mode,
1229                                const char *uuid,
1230                                const char *volume_key,
1231                                size_t volume_key_size,
1232                                struct crypt_params_luks1 *params)
1233 {
1234         int r;
1235         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1236         unsigned long alignment_offset = 0;
1237
1238         if (!cd->device) {
1239                 log_err(cd, _("Can't format LUKS without device.\n"));
1240                 return -EINVAL;
1241         }
1242
1243         if (volume_key)
1244                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1245                                                       volume_key);
1246         else
1247                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1248
1249         if(!cd->volume_key)
1250                 return -ENOMEM;
1251
1252         if (params && params->data_alignment)
1253                 required_alignment = params->data_alignment * SECTOR_SIZE;
1254         else
1255                 get_topology_alignment(cd->device, &required_alignment,
1256                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1257
1258         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
1259                                (params && params->hash) ? params->hash : "sha1",
1260                                uuid, LUKS_STRIPES,
1261                                required_alignment / SECTOR_SIZE,
1262                                alignment_offset / SECTOR_SIZE,
1263                                cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1264         if(r < 0)
1265                 return r;
1266
1267         /* Wipe first 8 sectors - fs magic numbers etc. */
1268         r = wipe_device_header(cd->device, 8);
1269         if(r < 0) {
1270                 if (r == -EBUSY)
1271                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
1272                                 cd->device);
1273                 else
1274                         log_err(cd, _("Cannot wipe header on device %s.\n"),
1275                                 cd->device);
1276
1277                 return r;
1278         }
1279
1280         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
1281
1282         return r;
1283 }
1284
1285 static int _crypt_format_loopaes(struct crypt_device *cd,
1286                                  const char *cipher,
1287                                  const char *uuid,
1288                                  size_t volume_key_size,
1289                                  struct crypt_params_loopaes *params)
1290 {
1291         if (!cd->device) {
1292                 log_err(cd, _("Can't format LOOPAES without device.\n"));
1293                 return -EINVAL;
1294         }
1295
1296         if (volume_key_size > 1024) {
1297                 log_err(cd, _("Invalid key size.\n"));
1298                 return -EINVAL;
1299         }
1300
1301         cd->loopaes_key_size = volume_key_size;
1302
1303         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1304
1305         if (uuid)
1306                 cd->loopaes_uuid = strdup(uuid);
1307
1308         if (params && params->hash)
1309                 cd->loopaes_hdr.hash = strdup(params->hash);
1310
1311         cd->loopaes_hdr.offset = params ? params->offset : 0;
1312         cd->loopaes_hdr.skip = params ? params->skip : 0;
1313
1314         return 0;
1315 }
1316
1317 int crypt_format(struct crypt_device *cd,
1318         const char *type,
1319         const char *cipher,
1320         const char *cipher_mode,
1321         const char *uuid,
1322         const char *volume_key,
1323         size_t volume_key_size,
1324         void *params)
1325 {
1326         int r;
1327
1328         if (!type)
1329                 return -EINVAL;
1330
1331         log_dbg("Formatting device %s as type %s.", cd->device ?: "(none)", type);
1332
1333         r = init_crypto(cd);
1334         if (r < 0)
1335                 return r;
1336
1337         if (isPLAIN(type))
1338                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1339                                         uuid, volume_key_size, params);
1340         else if (isLUKS(type))
1341                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1342                                         uuid, volume_key, volume_key_size, params);
1343         else if (isLOOPAES(type))
1344                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1345         else {
1346                 /* FIXME: allow plugins here? */
1347                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1348                 r = -EINVAL;
1349         }
1350
1351         if (!r && !(cd->type = strdup(type)))
1352                 r = -ENOMEM;
1353
1354         if (r < 0) {
1355                 crypt_free_volume_key(cd->volume_key);
1356                 cd->volume_key = NULL;
1357         }
1358
1359         return r;
1360 }
1361
1362 int crypt_load(struct crypt_device *cd,
1363                const char *requested_type,
1364                void *params)
1365 {
1366         struct luks_phdr hdr;
1367         int r;
1368
1369         log_dbg("Trying to load %s crypt type from device %s.",
1370                 requested_type ?: "any", cd->device ?: "(none)");
1371
1372         if (!cd->device)
1373                 return -EINVAL;
1374
1375         if (requested_type && !isLUKS(requested_type))
1376                 return -EINVAL;
1377
1378         r = init_crypto(cd);
1379         if (r < 0)
1380                 return r;
1381
1382         r = LUKS_read_phdr(cd->device, &hdr, 1, cd);
1383
1384         if (!r) {
1385                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
1386                 cd->type = strdup(CRYPT_LUKS1);
1387                 if (!cd->type)
1388                         r = -ENOMEM;
1389         }
1390
1391         return r;
1392 }
1393
1394 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1395 {
1396         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
1397         uint64_t size, skip, offset;
1398         int key_size, read_only, r;
1399
1400         /* Device context type must be initialised */
1401         if (!cd->type || !crypt_get_uuid(cd))
1402                 return -EINVAL;
1403
1404         r = dm_query_device(name, &device, &size, &skip, &offset,
1405                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
1406         if (r < 0) {
1407                 log_err(NULL, _("Device %s is not active.\n"), name);
1408                 goto out;
1409         }
1410
1411         if (!uuid) {
1412                 r = -EINVAL;
1413                 goto out;
1414         }
1415
1416         r = device_check_and_adjust(cd, device, 0, &new_size, &offset, &read_only);
1417         if (r)
1418                 goto out;
1419
1420         if (new_size == size) {
1421                 log_dbg("Device has already requested size %" PRIu64
1422                         " sectors.", size);
1423                 r = 0;
1424                 goto out;
1425         }
1426
1427         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1428
1429         r = dm_create_device(name, device, cipher, cd->type,
1430                              crypt_get_uuid(cd), new_size, skip, offset,
1431                              key_size, key, read_only, 1);
1432 out:
1433         crypt_safe_free(key);
1434         free(cipher);
1435         free(device);
1436         free(uuid);
1437
1438         return r;
1439 }
1440
1441 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1442 {
1443         if (!isLUKS(cd->type)) {
1444                 log_err(cd, _("This operation is not supported for this device type.\n"));
1445                 return  -EINVAL;
1446         }
1447
1448         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1449                 log_dbg("UUID is the same as requested (%s) for device %s.",
1450                         uuid, cd->device);
1451                 return 0;
1452         }
1453
1454         if (uuid)
1455                 log_dbg("Requested new UUID change to %s for %s.", uuid, cd->device);
1456         else
1457                 log_dbg("Requested new UUID refresh for %s.", cd->device);
1458
1459         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1460                 return -EPERM;
1461
1462         return LUKS_hdr_uuid_set(cd->device, &cd->hdr, uuid, cd);
1463 }
1464
1465 int crypt_header_backup(struct crypt_device *cd,
1466                         const char *requested_type,
1467                         const char *backup_file)
1468 {
1469         int r;
1470
1471         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1472                 return -EINVAL;
1473
1474         r = init_crypto(cd);
1475         if (r < 0)
1476                 return r;
1477
1478         log_dbg("Requested header backup of device %s (%s) to "
1479                 "file %s.", cd->device, requested_type, backup_file);
1480
1481         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
1482 }
1483
1484 int crypt_header_restore(struct crypt_device *cd,
1485                          const char *requested_type,
1486                          const char *backup_file)
1487 {
1488         int r;
1489
1490         if (requested_type && !isLUKS(requested_type))
1491                 return -EINVAL;
1492
1493         /* Some hash functions need initialized gcrypt library */
1494         r = init_crypto(cd);
1495         if (r < 0)
1496                 return r;
1497
1498         log_dbg("Requested header restore to device %s (%s) from "
1499                 "file %s.", cd->device, requested_type, backup_file);
1500
1501         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
1502 }
1503
1504 void crypt_free(struct crypt_device *cd)
1505 {
1506         if (cd) {
1507                 log_dbg("Releasing crypt device %s context.", cd->device);
1508
1509                 if (cd->loop_fd != -1)
1510                         close(cd->loop_fd);
1511
1512                 dm_exit();
1513                 crypt_free_volume_key(cd->volume_key);
1514
1515                 free(cd->device);
1516                 free(cd->backing_file);
1517                 free(cd->type);
1518
1519                 /* used in plain device only */
1520                 free((char*)cd->plain_hdr.hash);
1521                 free(cd->plain_cipher);
1522                 free(cd->plain_cipher_mode);
1523                 free(cd->plain_uuid);
1524
1525                 free(cd);
1526         }
1527 }
1528
1529 int crypt_suspend(struct crypt_device *cd,
1530                   const char *name)
1531 {
1532         crypt_status_info ci;
1533         int r, suspended = 0;
1534
1535         log_dbg("Suspending volume %s.", name);
1536
1537         ci = crypt_status(NULL, name);
1538         if (ci < CRYPT_ACTIVE) {
1539                 log_err(cd, _("Volume %s is not active.\n"), name);
1540                 return -EINVAL;
1541         }
1542
1543         if (!cd && dm_init(NULL, 1) < 0)
1544                 return -ENOSYS;
1545
1546         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1547                             NULL, NULL, NULL, NULL, &suspended, NULL);
1548         if (r < 0)
1549                 goto out;
1550
1551         if (suspended) {
1552                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1553                 r = -EINVAL;
1554                 goto out;
1555         }
1556
1557         r = dm_suspend_and_wipe_key(name);
1558         if (r == -ENOTSUP)
1559                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1560         else if (r)
1561                 log_err(cd, "Error during suspending device %s.\n", name);
1562 out:
1563         if (!cd)
1564                 dm_exit();
1565         return r;
1566 }
1567
1568 int crypt_resume_by_passphrase(struct crypt_device *cd,
1569                                const char *name,
1570                                int keyslot,
1571                                const char *passphrase,
1572                                size_t passphrase_size)
1573 {
1574         struct volume_key *vk = NULL;
1575         int r, suspended = 0;
1576
1577         log_dbg("Resuming volume %s.", name);
1578
1579         if (!isLUKS(cd->type)) {
1580                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1581                 r = -EINVAL;
1582                 goto out;
1583         }
1584
1585         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1586                             NULL, NULL, NULL, NULL, &suspended, NULL);
1587         if (r < 0)
1588                 return r;
1589
1590         if (!suspended) {
1591                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1592                 return -EINVAL;
1593         }
1594
1595         if (passphrase) {
1596                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1597                                            passphrase_size, &cd->hdr, &vk, cd);
1598         } else
1599                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1600
1601         if (r >= 0) {
1602                 keyslot = r;
1603                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1604                 if (r == -ENOTSUP)
1605                         log_err(cd, "Resume is not supported for device %s.\n", name);
1606                 else if (r)
1607                         log_err(cd, "Error during resuming device %s.\n", name);
1608         } else
1609                 r = keyslot;
1610 out:
1611         crypt_free_volume_key(vk);
1612         return r < 0 ? r : keyslot;
1613 }
1614
1615 int crypt_resume_by_keyfile(struct crypt_device *cd,
1616                             const char *name,
1617                             int keyslot,
1618                             const char *keyfile,
1619                             size_t keyfile_size)
1620 {
1621         struct volume_key *vk = NULL;
1622         char *passphrase_read = NULL;
1623         size_t passphrase_size_read;
1624         int r, suspended = 0;
1625
1626         log_dbg("Resuming volume %s.", name);
1627
1628         if (!isLUKS(cd->type)) {
1629                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1630                 r = -EINVAL;
1631                 goto out;
1632         }
1633
1634         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1635                             NULL, NULL, NULL, NULL, &suspended, NULL);
1636         if (r < 0)
1637                 return r;
1638
1639         if (!suspended) {
1640                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1641                 return -EINVAL;
1642         }
1643
1644         if (!keyfile)
1645                 return -EINVAL;
1646
1647         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1648                           &passphrase_size_read, keyfile, keyfile_size);
1649         if (r < 0)
1650                 goto out;
1651
1652         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1653                                    passphrase_size_read, &cd->hdr, &vk, cd);
1654         if (r < 0)
1655                 goto out;
1656
1657         keyslot = r;
1658         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1659         if (r)
1660                 log_err(cd, "Error during resuming device %s.\n", name);
1661 out:
1662         crypt_safe_free(passphrase_read);
1663         crypt_free_volume_key(vk);
1664         return r < 0 ? r : keyslot;
1665 }
1666
1667 // slot manipulation
1668 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1669         int keyslot, // -1 any
1670         const char *passphrase, // NULL -> terminal
1671         size_t passphrase_size,
1672         const char *new_passphrase, // NULL -> terminal
1673         size_t new_passphrase_size)
1674 {
1675         struct volume_key *vk = NULL;
1676         char *password = NULL, *new_password = NULL;
1677         size_t passwordLen, new_passwordLen;
1678         int r;
1679
1680         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1681                 "new passphrase %sprovided.",
1682                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1683
1684         if (!isLUKS(cd->type)) {
1685                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1686                 return -EINVAL;
1687         }
1688
1689         r = keyslot_verify_or_find_empty(cd, &keyslot);
1690         if (r)
1691                 return r;
1692
1693         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1694                 /* No slots used, try to use pre-generated key in header */
1695                 if (cd->volume_key) {
1696                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1697                         r = vk ? 0 : -ENOMEM;
1698                 } else {
1699                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1700                         return -EINVAL;
1701                 }
1702         } else if (passphrase) {
1703                 /* Passphrase provided, use it to unlock existing keyslot */
1704                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1705                                            passphrase_size, &cd->hdr, &vk, cd);
1706         } else {
1707                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1708                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1709                                       &password, &passwordLen, 0);
1710                 if (r < 0)
1711                         goto out;
1712
1713                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1714                                            passwordLen, &cd->hdr, &vk, cd);
1715                 crypt_safe_free(password);
1716         }
1717
1718         if(r < 0)
1719                 goto out;
1720
1721         if (new_passphrase) {
1722                 new_password = (char *)new_passphrase;
1723                 new_passwordLen = new_passphrase_size;
1724         } else {
1725                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1726                                       &new_password, &new_passwordLen, 1);
1727                 if(r < 0)
1728                         goto out;
1729         }
1730
1731         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1732                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1733         if(r < 0) goto out;
1734
1735         r = 0;
1736 out:
1737         if (!new_passphrase)
1738                 crypt_safe_free(new_password);
1739         crypt_free_volume_key(vk);
1740         return r ?: keyslot;
1741 }
1742
1743 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1744         int keyslot,
1745         const char *keyfile,
1746         size_t keyfile_size,
1747         const char *new_keyfile,
1748         size_t new_keyfile_size)
1749 {
1750         struct volume_key *vk = NULL;
1751         char *password = NULL; size_t passwordLen;
1752         char *new_password = NULL; size_t new_passwordLen;
1753         int r;
1754
1755         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1756                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1757
1758         if (!isLUKS(cd->type)) {
1759                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1760                 return -EINVAL;
1761         }
1762
1763         r = keyslot_verify_or_find_empty(cd, &keyslot);
1764         if (r)
1765                 return r;
1766
1767         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1768                 /* No slots used, try to use pre-generated key in header */
1769                 if (cd->volume_key) {
1770                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1771                         r = vk ? 0 : -ENOMEM;
1772                 } else {
1773                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1774                         return -EINVAL;
1775                 }
1776         } else {
1777                 /* Read password from file of (if NULL) from terminal */
1778                 if (keyfile)
1779                         r = key_from_file(cd, _("Enter any passphrase: "),
1780                                           &password, &passwordLen,
1781                                           keyfile, keyfile_size);
1782                 else
1783                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1784                                               &password, &passwordLen, 0);
1785                 if (r < 0)
1786                         goto out;
1787
1788                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1789                                            &cd->hdr, &vk, cd);
1790         }
1791
1792         if(r < 0)
1793                 goto out;
1794
1795         if (new_keyfile)
1796                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1797                                   &new_password, &new_passwordLen, new_keyfile,
1798                                   new_keyfile_size);
1799         else
1800                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1801                                       &new_password, &new_passwordLen, 1);
1802         if (r < 0)
1803                 goto out;
1804
1805         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1806                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1807 out:
1808         crypt_safe_free(password);
1809         crypt_safe_free(new_password);
1810         crypt_free_volume_key(vk);
1811         return r < 0 ? r : keyslot;
1812 }
1813
1814 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1815         int keyslot,
1816         const char *volume_key,
1817         size_t volume_key_size,
1818         const char *passphrase,
1819         size_t passphrase_size)
1820 {
1821         struct volume_key *vk = NULL;
1822         int r = -EINVAL;
1823         char *new_password = NULL; size_t new_passwordLen;
1824
1825         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1826
1827         if (!isLUKS(cd->type)) {
1828                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1829                 return -EINVAL;
1830         }
1831
1832         if (volume_key)
1833                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1834         else if (cd->volume_key)
1835                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1836
1837         if (!vk)
1838                 return -ENOMEM;
1839
1840         r = LUKS_verify_volume_key(&cd->hdr, vk);
1841         if (r < 0) {
1842                 log_err(cd, _("Volume key does not match the volume.\n"));
1843                 goto out;
1844         }
1845
1846         r = keyslot_verify_or_find_empty(cd, &keyslot);
1847         if (r)
1848                 goto out;
1849
1850         if (!passphrase) {
1851                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1852                                       &new_password, &new_passwordLen, 1);
1853                 if (r < 0)
1854                         goto out;
1855                 passphrase = new_password;
1856                 passphrase_size = new_passwordLen;
1857         }
1858
1859         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1860                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1861 out:
1862         crypt_safe_free(new_password);
1863         crypt_free_volume_key(vk);
1864         return (r < 0) ? r : keyslot;
1865 }
1866
1867 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1868 {
1869         crypt_keyslot_info ki;
1870
1871         log_dbg("Destroying keyslot %d.", keyslot);
1872
1873         if (!isLUKS(cd->type)) {
1874                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1875                 return -EINVAL;
1876         }
1877
1878         ki = crypt_keyslot_status(cd, keyslot);
1879         if (ki == CRYPT_SLOT_INVALID) {
1880                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1881                 return -EINVAL;
1882         }
1883
1884         if (ki == CRYPT_SLOT_INACTIVE) {
1885                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1886                 return -EINVAL;
1887         }
1888
1889         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1890 }
1891
1892 // activation/deactivation of device mapping
1893 int crypt_activate_by_passphrase(struct crypt_device *cd,
1894         const char *name,
1895         int keyslot,
1896         const char *passphrase,
1897         size_t passphrase_size,
1898         uint32_t flags)
1899 {
1900         crypt_status_info ci;
1901         struct volume_key *vk = NULL;
1902         char *read_passphrase = NULL;
1903         size_t passphraseLen = 0;
1904         int r;
1905
1906         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1907                 name ? "Activating" : "Checking", name ?: "",
1908                 keyslot, passphrase ? "" : "[none] ");
1909
1910         if (name) {
1911                 ci = crypt_status(NULL, name);
1912                 if (ci == CRYPT_INVALID)
1913                         return -EINVAL;
1914                 else if (ci >= CRYPT_ACTIVE) {
1915                         log_err(cd, _("Device %s already exists.\n"), name);
1916                         return -EEXIST;
1917                 }
1918         }
1919
1920         /* plain, use hashed passphrase */
1921         if (isPLAIN(cd->type)) {
1922                 if (!passphrase) {
1923                         r = key_from_terminal(cd, NULL, &read_passphrase,
1924                                               &passphraseLen, 0);
1925                         if (r < 0)
1926                                 goto out;
1927                         passphrase = read_passphrase;
1928                         passphrase_size = passphraseLen;
1929                 }
1930                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1931                                          cd->plain_cipher, cd->plain_cipher_mode,
1932                                          NULL, passphrase, passphrase_size,
1933                                          cd->volume_key->keylength, 0,
1934                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
1935                                          cd->plain_uuid,
1936                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1937                 keyslot = 0;
1938         } else if (isLUKS(cd->type)) {
1939                 /* provided passphrase, do not retry */
1940                 if (passphrase) {
1941                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1942                                                    passphrase_size, &cd->hdr, &vk, cd);
1943                 } else
1944                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1945
1946                 if (r >= 0) {
1947                         keyslot = r;
1948                         if (name)
1949                                 r = open_from_hdr_and_vk(cd, vk, name, flags);
1950                 }
1951         } else
1952                 r = -EINVAL;
1953 out:
1954         crypt_safe_free(read_passphrase);
1955         crypt_free_volume_key(vk);
1956
1957         return r < 0  ? r : keyslot;
1958 }
1959
1960 int crypt_activate_by_keyfile(struct crypt_device *cd,
1961         const char *name,
1962         int keyslot,
1963         const char *keyfile,
1964         size_t keyfile_size,
1965         uint32_t flags)
1966 {
1967         crypt_status_info ci;
1968         struct volume_key *vk = NULL;
1969         char *passphrase_read = NULL;
1970         size_t passphrase_size_read;
1971         unsigned int key_count = 0;
1972         int r;
1973
1974         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1975                 name ?: "", keyslot, keyfile ?: "[none]");
1976
1977         if (name) {
1978                 ci = crypt_status(NULL, name);
1979                 if (ci == CRYPT_INVALID)
1980                         return -EINVAL;
1981                 else if (ci >= CRYPT_ACTIVE) {
1982                         log_err(cd, _("Device %s already exists.\n"), name);
1983                         return -EEXIST;
1984                 }
1985         }
1986
1987         if (!keyfile)
1988                 return -EINVAL;
1989
1990         if (isPLAIN(cd->type)) {
1991                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1992                                   &passphrase_size_read, keyfile, keyfile_size);
1993                 if (r < 0)
1994                         goto out;
1995                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1996                                          cd->plain_cipher, cd->plain_cipher_mode,
1997                                          NULL, passphrase_read, passphrase_size_read,
1998                                          cd->volume_key->keylength, 0,
1999                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
2000                                          cd->plain_uuid,
2001                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
2002         } else if (isLUKS(cd->type)) {
2003                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
2004                           &passphrase_size_read, keyfile, keyfile_size);
2005                 if (r < 0)
2006                         goto out;
2007                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
2008                                            passphrase_size_read, &cd->hdr, &vk, cd);
2009                 if (r < 0)
2010                         goto out;
2011                 keyslot = r;
2012
2013                 if (name) {
2014                         r = open_from_hdr_and_vk(cd, vk, name, flags);
2015                         if (r < 0)
2016                                 goto out;
2017                 }
2018                 r = keyslot;
2019         } else if (isLOOPAES(cd->type)) {
2020                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
2021                                   keyfile, keyfile_size);
2022                 if (r < 0)
2023                         goto out;
2024                 r = LOOPAES_parse_keyfile(cd, &vk, &key_count,
2025                                           passphrase_read, passphrase_size_read);
2026                 if (r < 0)
2027                         goto out;
2028                 if (name)
2029                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
2030                                              key_count, vk,
2031                                              cd->loopaes_hdr.offset,
2032                                              cd->loopaes_hdr.skip,
2033                                              flags);
2034         } else
2035                 r = -EINVAL;
2036
2037 out:
2038         crypt_safe_free(passphrase_read);
2039         crypt_free_volume_key(vk);
2040
2041         return r;
2042 }
2043
2044 int crypt_activate_by_volume_key(struct crypt_device *cd,
2045         const char *name,
2046         const char *volume_key,
2047         size_t volume_key_size,
2048         uint32_t flags)
2049 {
2050         crypt_status_info ci;
2051         struct volume_key *vk;
2052         int r;
2053
2054         log_dbg("Activating volume %s by volume key.", name);
2055
2056         /* use key directly, no hash */
2057         if (isPLAIN(cd->type)) {
2058                 if (!volume_key || !volume_key_size || !cd->volume_key ||
2059                         volume_key_size != cd->volume_key->keylength) {
2060                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
2061                         return -EINVAL;
2062                 }
2063
2064                 return create_device_helper(cd, name, NULL,
2065                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
2066                         cd->volume_key->keylength, 0, cd->plain_hdr.skip,
2067                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
2068         }
2069
2070         if (!isLUKS(cd->type)) {
2071                 log_err(cd, _("Device type is not properly initialised.\n"));
2072                 return -EINVAL;
2073         }
2074
2075         if (name) {
2076                 ci = crypt_status(NULL, name);
2077                 if (ci == CRYPT_INVALID)
2078                         return -EINVAL;
2079                 else if (ci >= CRYPT_ACTIVE) {
2080                         log_err(cd, _("Device %s already exists.\n"), name);
2081                         return -EEXIST;
2082                 }
2083         }
2084
2085         /* If key is not provided, try to use internal key */
2086         if (!volume_key) {
2087                 if (!cd->volume_key) {
2088                         log_err(cd, _("Volume key does not match the volume.\n"));
2089                         return -EINVAL;
2090                 }
2091                 volume_key_size = cd->volume_key->keylength;
2092                 volume_key = cd->volume_key->key;
2093         }
2094
2095         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2096         if (!vk)
2097                 return -ENOMEM;
2098         r = LUKS_verify_volume_key(&cd->hdr, vk);
2099
2100         if (r == -EPERM)
2101                 log_err(cd, _("Volume key does not match the volume.\n"));
2102
2103         if (!r && name)
2104                 r = open_from_hdr_and_vk(cd, vk, name, flags);
2105
2106         crypt_free_volume_key(vk);
2107
2108         return r;
2109 }
2110
2111 int crypt_deactivate(struct crypt_device *cd, const char *name)
2112 {
2113         int r;
2114
2115         if (!name)
2116                 return -EINVAL;
2117
2118         log_dbg("Deactivating volume %s.", name);
2119
2120         if (!cd && dm_init(NULL, 1) < 0)
2121                 return -ENOSYS;
2122
2123         switch (crypt_status(cd, name)) {
2124                 case CRYPT_ACTIVE:
2125                         r = dm_remove_device(name, 0, 0);
2126                         break;
2127                 case CRYPT_BUSY:
2128                         log_err(cd, _("Device %s is busy.\n"), name);
2129                         r = -EBUSY;
2130                         break;
2131                 case CRYPT_INACTIVE:
2132                         log_err(cd, _("Device %s is not active.\n"), name);
2133                         r = -ENODEV;
2134                         break;
2135                 default:
2136                         log_err(cd, _("Invalid device %s.\n"), name);
2137                         r = -EINVAL;
2138         }
2139
2140         if (!cd)
2141                 dm_exit();
2142
2143         return r;
2144 }
2145
2146 int crypt_volume_key_get(struct crypt_device *cd,
2147         int keyslot,
2148         char *volume_key,
2149         size_t *volume_key_size,
2150         const char *passphrase,
2151         size_t passphrase_size)
2152 {
2153         struct volume_key *vk;
2154         char *processed_key = NULL;
2155         int r, key_len;
2156
2157         key_len = crypt_get_volume_key_size(cd);
2158         if (key_len > *volume_key_size) {
2159                 log_err(cd, _("Volume key buffer too small.\n"));
2160                 return -ENOMEM;
2161         }
2162
2163         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2164                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
2165                                             passphrase, passphrase_size);
2166                 if (!processed_key) {
2167                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2168                         return -EINVAL;
2169                 }
2170                 memcpy(volume_key, processed_key, key_len);
2171                 *volume_key_size = key_len;
2172                 crypt_safe_free(processed_key);
2173                 return 0;
2174         }
2175
2176         if (isLUKS(cd->type)) {
2177                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
2178                                         passphrase_size, &cd->hdr, &vk, cd);
2179
2180                 if (r >= 0) {
2181                         memcpy(volume_key, vk->key, vk->keylength);
2182                         *volume_key_size = vk->keylength;
2183                 }
2184
2185                 crypt_free_volume_key(vk);
2186                 return r;
2187         }
2188
2189         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2190         return -EINVAL;
2191 }
2192
2193 int crypt_volume_key_verify(struct crypt_device *cd,
2194         const char *volume_key,
2195         size_t volume_key_size)
2196 {
2197         struct volume_key *vk;
2198         int r;
2199
2200         if (!isLUKS(cd->type)) {
2201                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2202                 return -EINVAL;
2203         }
2204
2205         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2206         if (!vk)
2207                 return -ENOMEM;
2208
2209         r = LUKS_verify_volume_key(&cd->hdr, vk);
2210
2211         if (r == -EPERM)
2212                 log_err(cd, _("Volume key does not match the volume.\n"));
2213
2214         crypt_free_volume_key(vk);
2215
2216         return r;
2217 }
2218
2219 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2220 {
2221         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2222         cd->timeout = timeout_sec;
2223 }
2224
2225 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2226 {
2227         log_dbg("Password retry count set to %d.", tries);
2228         cd->tries = tries;
2229 }
2230
2231 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2232 {
2233         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2234         cd->iteration_time = iteration_time_ms;
2235 }
2236
2237 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2238 {
2239         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2240         cd->password_verify = password_verify ? 1 : 0;
2241 }
2242
2243 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2244 {
2245         switch (rng_type) {
2246         case CRYPT_RNG_URANDOM:
2247         case CRYPT_RNG_RANDOM:
2248                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2249                 cd->rng_type = rng_type;
2250         }
2251 }
2252
2253 int crypt_get_rng_type(struct crypt_device *cd)
2254 {
2255         if (!cd)
2256                 return -EINVAL;
2257
2258         return cd->rng_type;
2259 }
2260
2261 int crypt_memory_lock(struct crypt_device *cd, int lock)
2262 {
2263         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2264 }
2265
2266 // reporting
2267 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2268 {
2269         int r;
2270
2271         if (!cd && dm_init(NULL, 1) < 0)
2272                 return CRYPT_INVALID;
2273
2274         r = dm_status_device(name);
2275
2276         if (!cd)
2277                 dm_exit();
2278
2279         if (r < 0 && r != -ENODEV)
2280                 return CRYPT_INVALID;
2281
2282         if (r == 0)
2283                 return CRYPT_ACTIVE;
2284
2285         if (r > 0)
2286                 return CRYPT_BUSY;
2287
2288         return CRYPT_INACTIVE;
2289 }
2290
2291 static void hexprintICB(struct crypt_device *cd, char *d, int n)
2292 {
2293         int i;
2294         for(i = 0; i < n; i++)
2295                 log_std(cd, "%02hhx ", (char)d[i]);
2296 }
2297
2298 int crypt_dump(struct crypt_device *cd)
2299 {
2300         int i;
2301         if (!isLUKS(cd->type)) { //FIXME
2302                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2303                 return -EINVAL;
2304         }
2305
2306         log_std(cd, "LUKS header information for %s\n\n", cd->device);
2307         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2308         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2309         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2310         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2311         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2312         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2313         log_std(cd, "MK digest:     \t");
2314         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
2315         log_std(cd, "\n");
2316         log_std(cd, "MK salt:       \t");
2317         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
2318         log_std(cd, "\n               \t");
2319         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2320         log_std(cd, "\n");
2321         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2322         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2323         for(i = 0; i < LUKS_NUMKEYS; i++) {
2324                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2325                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2326                         log_std(cd, "\tIterations:         \t%d\n",
2327                                 cd->hdr.keyblock[i].passwordIterations);
2328                         log_std(cd, "\tSalt:               \t");
2329                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
2330                                     LUKS_SALTSIZE/2);
2331                         log_std(cd, "\n\t                      \t");
2332                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
2333                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2334                         log_std(cd, "\n");
2335
2336                         log_std(cd, "\tKey material offset:\t%d\n",
2337                                 cd->hdr.keyblock[i].keyMaterialOffset);
2338                         log_std(cd, "\tAF stripes:            \t%d\n",
2339                                 cd->hdr.keyblock[i].stripes);
2340                 }
2341                 else 
2342                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2343         }
2344
2345         return 0;
2346 }
2347
2348 const char *crypt_get_cipher(struct crypt_device *cd)
2349 {
2350         if (isPLAIN(cd->type))
2351                 return cd->plain_cipher;
2352
2353         if (isLUKS(cd->type))
2354                 return cd->hdr.cipherName;
2355
2356         if (isLOOPAES(cd->type))
2357                 return cd->loopaes_cipher;
2358
2359         return NULL;
2360 }
2361
2362 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2363 {
2364         if (isPLAIN(cd->type))
2365                 return cd->plain_cipher_mode;
2366
2367         if (isLUKS(cd->type))
2368                 return cd->hdr.cipherMode;
2369
2370         if (isLOOPAES(cd->type))
2371                 return cd->loopaes_cipher_mode;
2372
2373         return NULL;
2374 }
2375
2376 const char *crypt_get_uuid(struct crypt_device *cd)
2377 {
2378         if (isLUKS(cd->type))
2379                 return cd->hdr.uuid;
2380
2381         if (isPLAIN(cd->type))
2382                 return cd->plain_uuid;
2383
2384         if (isLOOPAES(cd->type))
2385                 return cd->loopaes_uuid;
2386
2387         return NULL;
2388 }
2389
2390 const char *crypt_get_device_name(struct crypt_device *cd)
2391 {
2392         return cd->device;
2393 }
2394
2395 int crypt_get_volume_key_size(struct crypt_device *cd)
2396 {
2397         if (isPLAIN(cd->type) && cd->volume_key)
2398                 return cd->volume_key->keylength;
2399
2400         if (isLUKS(cd->type))
2401                 return cd->hdr.keyBytes;
2402
2403         if (isLOOPAES(cd->type))
2404                 return cd->loopaes_key_size;
2405
2406         return 0;
2407 }
2408
2409 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2410 {
2411         if (isPLAIN(cd->type))
2412                 return cd->plain_hdr.offset;
2413
2414         if (isLUKS(cd->type))
2415                 return cd->hdr.payloadOffset;
2416
2417         if (isLOOPAES(cd->type))
2418                 return cd->loopaes_hdr.offset;
2419
2420         return 0;
2421 }
2422
2423 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2424 {
2425         if (!isLUKS(cd->type)) {
2426                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2427                 return CRYPT_SLOT_INVALID;
2428         }
2429
2430         return LUKS_keyslot_info(&cd->hdr, keyslot);
2431 }
2432
2433 int crypt_keyslot_max(const char *type)
2434 {
2435         if (type && isLUKS(type))
2436                 return LUKS_NUMKEYS;
2437
2438         return -EINVAL;
2439 }
2440
2441 const char *crypt_get_type(struct crypt_device *cd)
2442 {
2443         return cd->type;
2444 }
2445
2446 int crypt_get_active_device(struct crypt_device *cd,
2447                             const char *name,
2448                             struct crypt_active_device *cad)
2449 {
2450         int r, readonly;
2451
2452         r = dm_query_device(name, NULL, &cad->size, &cad->iv_offset, &cad->offset,
2453                             NULL, NULL, NULL, &readonly, NULL, NULL);
2454         if (r < 0)
2455                 return r;
2456
2457         cad->flags = readonly ? CRYPT_ACTIVATE_READONLY : 0;
2458
2459         return 0;
2460 }