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