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