Separate loop handling from internal code.
[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                                 r = -ENOSYS;
989                                 goto bad;
990                         }
991
992                         /* Keep the loop open, dettached on last close. */
993                         h->loop_fd = crypt_loop_attach(h->device, device, 0, &readonly);
994                         if (h->loop_fd == -1) {
995                                 log_dbg("Attaching loop failed.");
996                                 r = -EINVAL;
997                                 goto bad;
998                         }
999
1000                         h->backing_file = crypt_loop_backing_file(h->device);
1001                         r = device_ready(NULL, h->device, O_RDONLY);
1002                 }
1003                 if (r < 0) {
1004                         r = -ENOTBLK;
1005                         goto bad;
1006                 }
1007         }
1008
1009         if (!h->device && device && !(h->device = strdup(device))) {
1010                 r = -ENOMEM;
1011                 goto bad;
1012         }
1013
1014         if (dm_init(h, 1) < 0) {
1015                 r = -ENOSYS;
1016                 goto bad;
1017         }
1018
1019         h->iteration_time = 1000;
1020         h->password_verify = 0;
1021         h->tries = 3;
1022         h->rng_type = crypt_random_default_key_rng();
1023         *cd = h;
1024         return 0;
1025 bad:
1026
1027         if (h) {
1028                 if (h->loop_fd != -1)
1029                         close(h->loop_fd);
1030                 free(h->device);
1031                 free(h->backing_file);
1032         }
1033         free(h);
1034         return r;
1035 }
1036
1037 int crypt_init_by_name(struct crypt_device **cd, const char *name)
1038 {
1039         crypt_status_info ci;
1040         struct crypt_active_device cad;
1041         char *device = NULL, *cipher_full = NULL, *device_uuid = NULL;
1042         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
1043         char *key = NULL;
1044         int key_size = 0, key_nums, r;
1045
1046
1047         log_dbg("Allocating crypt device context by device %s.", name);
1048
1049         ci = crypt_status(NULL, name);
1050         if (ci == CRYPT_INVALID)
1051                 return -ENODEV;
1052
1053         if (ci < CRYPT_ACTIVE) {
1054                 log_err(NULL, _("Device %s is not active.\n"), name);
1055                 return -ENODEV;
1056         }
1057
1058         r = dm_query_device(name, &device, &cad.size, &cad.iv_offset, &cad.offset,
1059                             &cipher_full, &key_size, &key, NULL, NULL,
1060                             &device_uuid);
1061         if (r < 0)
1062                 goto out;
1063
1064         *cd = NULL;
1065         r = crypt_init(cd, device);
1066
1067         /* Underlying device disappeared but mapping still active */
1068         if (!device || r == -ENOTBLK)
1069                 log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
1070                             name);
1071
1072         /* Underlying device is not readable but crypt mapping exists */
1073         if (r == -ENOTBLK) {
1074                 free(device);
1075                 device = NULL;
1076                 r = crypt_init(cd, NULL);
1077         }
1078
1079         if (r < 0)
1080                 goto out;
1081
1082         /* Try to initialise basic parameters from active device */
1083
1084         if (!(*cd)->backing_file && device && crypt_loop_device(device) &&
1085             !((*cd)->backing_file = crypt_loop_backing_file(device))) {
1086                 r = -ENOMEM;
1087                 goto out;
1088         }
1089
1090         if (device_uuid) {
1091                 if (!strncmp(CRYPT_PLAIN, device_uuid, sizeof(CRYPT_PLAIN)-1)) {
1092                         (*cd)->type = strdup(CRYPT_PLAIN);
1093                         (*cd)->plain_uuid = strdup(device_uuid);
1094                         (*cd)->plain_hdr.hash = NULL; /* no way to get this */
1095                         (*cd)->plain_hdr.offset = cad.offset;
1096                         (*cd)->plain_hdr.skip = cad.iv_offset;
1097                         (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1098                         if (!(*cd)->volume_key) {
1099                                 r = -ENOMEM;
1100                                 goto out;
1101                         }
1102
1103                         r = crypt_parse_name_and_mode(cipher_full, cipher, NULL, cipher_mode);
1104                         if (!r) {
1105                                 (*cd)->plain_cipher = strdup(cipher);
1106                                 (*cd)->plain_cipher_mode = strdup(cipher_mode);
1107                         }
1108                 } else if (!strncmp(CRYPT_LOOPAES, device_uuid, sizeof(CRYPT_LOOPAES)-1)) {
1109                         (*cd)->type = strdup(CRYPT_LOOPAES);
1110                         (*cd)->loopaes_uuid = strdup(device_uuid);
1111                         (*cd)->loopaes_hdr.offset = cad.offset;
1112
1113                         r = crypt_parse_name_and_mode(cipher_full, cipher,
1114                                                       &key_nums, cipher_mode);
1115                         if (!r) {
1116                                 (*cd)->loopaes_cipher = strdup(cipher);
1117                                 (*cd)->loopaes_cipher_mode = strdup(cipher_mode);
1118                                 /* version 3 uses last key for IV */
1119                                 if (key_size % key_nums)
1120                                         key_nums++;
1121                                 (*cd)->loopaes_key_size = key_size / key_nums;
1122                         }
1123                 } else if (!strncmp(CRYPT_LUKS1, device_uuid, sizeof(CRYPT_LUKS1)-1)) {
1124                         if (device) {
1125                                 if (crypt_load(*cd, CRYPT_LUKS1, NULL) < 0 ||
1126                                     crypt_volume_key_verify(*cd, key, key_size) < 0) {
1127                                         log_dbg("LUKS device header does not match active device.");
1128                                         goto out;
1129                                 }
1130
1131                                 (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1132                                 if (!(*cd)->volume_key) {
1133                                         r = -ENOMEM;
1134                                         goto out;
1135                                 }
1136                         }
1137                 }
1138         } else
1139                 log_dbg("Active device has no UUID set, some parameters are not set.");
1140
1141 out:
1142         if (r < 0) {
1143                 crypt_free(*cd);
1144                 *cd = NULL;
1145         }
1146         crypt_safe_free(key);
1147         free(device);
1148         free(cipher_full);
1149         free(device_uuid);
1150         return r;
1151 }
1152
1153 static int _crypt_format_plain(struct crypt_device *cd,
1154                                const char *cipher,
1155                                const char *cipher_mode,
1156                                const char *uuid,
1157                                size_t volume_key_size,
1158                                struct crypt_params_plain *params)
1159 {
1160         if (!cipher || !cipher_mode) {
1161                 log_err(cd, _("Invalid plain crypt parameters.\n"));
1162                 return -EINVAL;
1163         }
1164
1165         if (volume_key_size > 1024) {
1166                 log_err(cd, _("Invalid key size.\n"));
1167                 return -EINVAL;
1168         }
1169
1170         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
1171         if (!cd->volume_key)
1172                 return -ENOMEM;
1173
1174         cd->plain_cipher = strdup(cipher);
1175         cd->plain_cipher_mode = strdup(cipher_mode);
1176
1177         if (uuid)
1178                 cd->plain_uuid = strdup(uuid);
1179
1180         if (params && params->hash)
1181                 cd->plain_hdr.hash = strdup(params->hash);
1182
1183         cd->plain_hdr.offset = params ? params->offset : 0;
1184         cd->plain_hdr.skip = params ? params->skip : 0;
1185
1186         if (!cd->plain_cipher || !cd->plain_cipher_mode)
1187                 return -ENOMEM;
1188
1189         return 0;
1190 }
1191
1192 static int _crypt_format_luks1(struct crypt_device *cd,
1193                                const char *cipher,
1194                                const char *cipher_mode,
1195                                const char *uuid,
1196                                const char *volume_key,
1197                                size_t volume_key_size,
1198                                struct crypt_params_luks1 *params)
1199 {
1200         int r;
1201         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1202         unsigned long alignment_offset = 0;
1203
1204         if (!cd->device) {
1205                 log_err(cd, _("Can't format LUKS without device.\n"));
1206                 return -EINVAL;
1207         }
1208
1209         if (volume_key)
1210                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1211                                                       volume_key);
1212         else
1213                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1214
1215         if(!cd->volume_key)
1216                 return -ENOMEM;
1217
1218         if (params && params->data_alignment)
1219                 required_alignment = params->data_alignment * SECTOR_SIZE;
1220         else
1221                 get_topology_alignment(cd->device, &required_alignment,
1222                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1223
1224         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
1225                                (params && params->hash) ? params->hash : "sha1",
1226                                uuid, LUKS_STRIPES,
1227                                required_alignment / SECTOR_SIZE,
1228                                alignment_offset / SECTOR_SIZE,
1229                                cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1230         if(r < 0)
1231                 return r;
1232
1233         /* Wipe first 8 sectors - fs magic numbers etc. */
1234         r = wipe_device_header(cd->device, 8);
1235         if(r < 0) {
1236                 if (r == -EBUSY)
1237                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
1238                                 cd->device);
1239                 else
1240                         log_err(cd, _("Cannot wipe header on device %s.\n"),
1241                                 cd->device);
1242
1243                 return r;
1244         }
1245
1246         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
1247
1248         return r;
1249 }
1250
1251 static int _crypt_format_loopaes(struct crypt_device *cd,
1252                                  const char *cipher,
1253                                  const char *uuid,
1254                                  size_t volume_key_size,
1255                                  struct crypt_params_loopaes *params)
1256 {
1257         if (!cd->device) {
1258                 log_err(cd, _("Can't format LOOPAES without device.\n"));
1259                 return -EINVAL;
1260         }
1261
1262         if (volume_key_size > 1024) {
1263                 log_err(cd, _("Invalid key size.\n"));
1264                 return -EINVAL;
1265         }
1266
1267         cd->loopaes_key_size = volume_key_size;
1268
1269         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1270
1271         if (uuid)
1272                 cd->loopaes_uuid = strdup(uuid);
1273
1274         if (params && params->hash)
1275                 cd->loopaes_hdr.hash = strdup(params->hash);
1276
1277         cd->loopaes_hdr.offset = params ? params->offset : 0;
1278
1279         return 0;
1280 }
1281
1282 int crypt_format(struct crypt_device *cd,
1283         const char *type,
1284         const char *cipher,
1285         const char *cipher_mode,
1286         const char *uuid,
1287         const char *volume_key,
1288         size_t volume_key_size,
1289         void *params)
1290 {
1291         int r;
1292
1293         if (!type)
1294                 return -EINVAL;
1295
1296         log_dbg("Formatting device %s as type %s.", cd->device ?: "(none)", type);
1297
1298         r = init_crypto(cd);
1299         if (r < 0)
1300                 return r;
1301
1302         if (isPLAIN(type))
1303                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1304                                         uuid, volume_key_size, params);
1305         else if (isLUKS(type))
1306                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1307                                         uuid, volume_key, volume_key_size, params);
1308         else if (isLOOPAES(type))
1309                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1310         else {
1311                 /* FIXME: allow plugins here? */
1312                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1313                 r = -EINVAL;
1314         }
1315
1316         if (!r && !(cd->type = strdup(type)))
1317                 r = -ENOMEM;
1318
1319         if (r < 0) {
1320                 crypt_free_volume_key(cd->volume_key);
1321                 cd->volume_key = NULL;
1322         }
1323
1324         return r;
1325 }
1326
1327 int crypt_load(struct crypt_device *cd,
1328                const char *requested_type,
1329                void *params)
1330 {
1331         struct luks_phdr hdr;
1332         int r;
1333
1334         log_dbg("Trying to load %s crypt type from device %s.",
1335                 requested_type ?: "any", cd->device ?: "(none)");
1336
1337         if (!cd->device)
1338                 return -EINVAL;
1339
1340         if (requested_type && !isLUKS(requested_type))
1341                 return -EINVAL;
1342
1343         r = init_crypto(cd);
1344         if (r < 0)
1345                 return r;
1346
1347         r = LUKS_read_phdr(cd->device, &hdr, 1, cd);
1348
1349         if (!r) {
1350                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
1351                 cd->type = strdup(CRYPT_LUKS1);
1352                 if (!cd->type)
1353                         r = -ENOMEM;
1354         }
1355
1356         return r;
1357 }
1358
1359 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1360 {
1361         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
1362         uint64_t size, skip, offset;
1363         int key_size, read_only, r;
1364
1365         /* Device context type must be initialised */
1366         if (!cd->type || !crypt_get_uuid(cd))
1367                 return -EINVAL;
1368
1369         r = dm_query_device(name, &device, &size, &skip, &offset,
1370                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
1371         if (r < 0) {
1372                 log_err(NULL, _("Device %s is not active.\n"), name);
1373                 goto out;
1374         }
1375
1376         if (!uuid) {
1377                 r = -EINVAL;
1378                 goto out;
1379         }
1380
1381         r = device_check_and_adjust(cd, device, 0, &new_size, &offset, &read_only);
1382         if (r)
1383                 goto out;
1384
1385         if (new_size == size) {
1386                 log_dbg("Device has already requested size %" PRIu64
1387                         " sectors.", size);
1388                 r = 0;
1389                 goto out;
1390         }
1391
1392         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1393
1394         r = dm_create_device(name, device, cipher, cd->type,
1395                              crypt_get_uuid(cd), new_size, skip, offset,
1396                              key_size, key, read_only, 1);
1397 out:
1398         crypt_safe_free(key);
1399         free(cipher);
1400         free(device);
1401         free(uuid);
1402
1403         return r;
1404 }
1405
1406 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1407 {
1408         if (!isLUKS(cd->type)) {
1409                 log_err(cd, _("This operation is not supported for this device type.\n"));
1410                 return  -EINVAL;
1411         }
1412
1413         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1414                 log_dbg("UUID is the same as requested (%s) for device %s.",
1415                         uuid, cd->device);
1416                 return 0;
1417         }
1418
1419         if (uuid)
1420                 log_dbg("Requested new UUID change to %s for %s.", uuid, cd->device);
1421         else
1422                 log_dbg("Requested new UUID refresh for %s.", cd->device);
1423
1424         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1425                 return -EPERM;
1426
1427         return LUKS_hdr_uuid_set(cd->device, &cd->hdr, uuid, cd);
1428 }
1429
1430 int crypt_header_backup(struct crypt_device *cd,
1431                         const char *requested_type,
1432                         const char *backup_file)
1433 {
1434         int r;
1435
1436         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1437                 return -EINVAL;
1438
1439         r = init_crypto(cd);
1440         if (r < 0)
1441                 return r;
1442
1443         log_dbg("Requested header backup of device %s (%s) to "
1444                 "file %s.", cd->device, requested_type, backup_file);
1445
1446         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
1447 }
1448
1449 int crypt_header_restore(struct crypt_device *cd,
1450                          const char *requested_type,
1451                          const char *backup_file)
1452 {
1453         int r;
1454
1455         if (requested_type && !isLUKS(requested_type))
1456                 return -EINVAL;
1457
1458         /* Some hash functions need initialized gcrypt library */
1459         r = init_crypto(cd);
1460         if (r < 0)
1461                 return r;
1462
1463         log_dbg("Requested header restore to device %s (%s) from "
1464                 "file %s.", cd->device, requested_type, backup_file);
1465
1466         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
1467 }
1468
1469 void crypt_free(struct crypt_device *cd)
1470 {
1471         if (cd) {
1472                 log_dbg("Releasing crypt device %s context.", cd->device);
1473
1474                 if (cd->loop_fd != -1)
1475                         close(cd->loop_fd);
1476
1477                 dm_exit();
1478                 crypt_free_volume_key(cd->volume_key);
1479
1480                 free(cd->device);
1481                 free(cd->backing_file);
1482                 free(cd->type);
1483
1484                 /* used in plain device only */
1485                 free((char*)cd->plain_hdr.hash);
1486                 free(cd->plain_cipher);
1487                 free(cd->plain_cipher_mode);
1488                 free(cd->plain_uuid);
1489
1490                 free(cd);
1491         }
1492 }
1493
1494 int crypt_suspend(struct crypt_device *cd,
1495                   const char *name)
1496 {
1497         crypt_status_info ci;
1498         int r, suspended = 0;
1499
1500         log_dbg("Suspending volume %s.", name);
1501
1502         ci = crypt_status(NULL, name);
1503         if (ci < CRYPT_ACTIVE) {
1504                 log_err(cd, _("Volume %s is not active.\n"), name);
1505                 return -EINVAL;
1506         }
1507
1508         if (!cd && dm_init(NULL, 1) < 0)
1509                 return -ENOSYS;
1510
1511         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1512                             NULL, NULL, NULL, NULL, &suspended, NULL);
1513         if (r < 0)
1514                 goto out;
1515
1516         if (suspended) {
1517                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1518                 r = -EINVAL;
1519                 goto out;
1520         }
1521
1522         r = dm_suspend_and_wipe_key(name);
1523         if (r == -ENOTSUP)
1524                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1525         else if (r)
1526                 log_err(cd, "Error during suspending device %s.\n", name);
1527 out:
1528         if (!cd)
1529                 dm_exit();
1530         return r;
1531 }
1532
1533 int crypt_resume_by_passphrase(struct crypt_device *cd,
1534                                const char *name,
1535                                int keyslot,
1536                                const char *passphrase,
1537                                size_t passphrase_size)
1538 {
1539         struct volume_key *vk = NULL;
1540         int r, suspended = 0;
1541
1542         log_dbg("Resuming volume %s.", name);
1543
1544         if (!isLUKS(cd->type)) {
1545                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1546                 r = -EINVAL;
1547                 goto out;
1548         }
1549
1550         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1551                             NULL, NULL, NULL, NULL, &suspended, NULL);
1552         if (r < 0)
1553                 return r;
1554
1555         if (!suspended) {
1556                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1557                 return -EINVAL;
1558         }
1559
1560         if (passphrase) {
1561                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1562                                            passphrase_size, &cd->hdr, &vk, cd);
1563         } else
1564                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1565
1566         if (r >= 0) {
1567                 keyslot = r;
1568                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1569                 if (r == -ENOTSUP)
1570                         log_err(cd, "Resume is not supported for device %s.\n", name);
1571                 else if (r)
1572                         log_err(cd, "Error during resuming device %s.\n", name);
1573         } else
1574                 r = keyslot;
1575 out:
1576         crypt_free_volume_key(vk);
1577         return r < 0 ? r : keyslot;
1578 }
1579
1580 int crypt_resume_by_keyfile(struct crypt_device *cd,
1581                             const char *name,
1582                             int keyslot,
1583                             const char *keyfile,
1584                             size_t keyfile_size)
1585 {
1586         struct volume_key *vk = NULL;
1587         char *passphrase_read = NULL;
1588         unsigned int passphrase_size_read;
1589         int r, suspended = 0;
1590
1591         log_dbg("Resuming volume %s.", name);
1592
1593         if (!isLUKS(cd->type)) {
1594                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1595                 r = -EINVAL;
1596                 goto out;
1597         }
1598
1599         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1600                             NULL, NULL, NULL, NULL, &suspended, NULL);
1601         if (r < 0)
1602                 return r;
1603
1604         if (!suspended) {
1605                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1606                 return -EINVAL;
1607         }
1608
1609         if (!keyfile)
1610                 return -EINVAL;
1611
1612         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1613                           &passphrase_size_read, keyfile, keyfile_size);
1614         if (r < 0)
1615                 goto out;
1616
1617         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1618                                    passphrase_size_read, &cd->hdr, &vk, cd);
1619         if (r < 0)
1620                 goto out;
1621
1622         keyslot = r;
1623         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1624         if (r)
1625                 log_err(cd, "Error during resuming device %s.\n", name);
1626 out:
1627         crypt_safe_free(passphrase_read);
1628         crypt_free_volume_key(vk);
1629         return r < 0 ? r : keyslot;
1630 }
1631
1632 // slot manipulation
1633 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1634         int keyslot, // -1 any
1635         const char *passphrase, // NULL -> terminal
1636         size_t passphrase_size,
1637         const char *new_passphrase, // NULL -> terminal
1638         size_t new_passphrase_size)
1639 {
1640         struct volume_key *vk = NULL;
1641         char *password = NULL, *new_password = NULL;
1642         unsigned int passwordLen, new_passwordLen;
1643         int r;
1644
1645         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1646                 "new passphrase %sprovided.",
1647                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1648
1649         if (!isLUKS(cd->type)) {
1650                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1651                 return -EINVAL;
1652         }
1653
1654         r = keyslot_verify_or_find_empty(cd, &keyslot);
1655         if (r)
1656                 return r;
1657
1658         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1659                 /* No slots used, try to use pre-generated key in header */
1660                 if (cd->volume_key) {
1661                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1662                         r = vk ? 0 : -ENOMEM;
1663                 } else {
1664                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1665                         return -EINVAL;
1666                 }
1667         } else if (passphrase) {
1668                 /* Passphrase provided, use it to unlock existing keyslot */
1669                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1670                                            passphrase_size, &cd->hdr, &vk, cd);
1671         } else {
1672                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1673                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1674                                       &password, &passwordLen, 0);
1675                 if (r < 0)
1676                         goto out;
1677
1678                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1679                                            passwordLen, &cd->hdr, &vk, cd);
1680                 crypt_safe_free(password);
1681         }
1682
1683         if(r < 0)
1684                 goto out;
1685
1686         if (new_passphrase) {
1687                 new_password = (char *)new_passphrase;
1688                 new_passwordLen = new_passphrase_size;
1689         } else {
1690                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1691                                       &new_password, &new_passwordLen, 1);
1692                 if(r < 0)
1693                         goto out;
1694         }
1695
1696         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1697                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1698         if(r < 0) goto out;
1699
1700         r = 0;
1701 out:
1702         if (!new_passphrase)
1703                 crypt_safe_free(new_password);
1704         crypt_free_volume_key(vk);
1705         return r ?: keyslot;
1706 }
1707
1708 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1709         int keyslot,
1710         const char *keyfile,
1711         size_t keyfile_size,
1712         const char *new_keyfile,
1713         size_t new_keyfile_size)
1714 {
1715         struct volume_key *vk = NULL;
1716         char *password = NULL; unsigned int passwordLen;
1717         char *new_password = NULL; unsigned int new_passwordLen;
1718         int r;
1719
1720         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1721                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1722
1723         if (!isLUKS(cd->type)) {
1724                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1725                 return -EINVAL;
1726         }
1727
1728         r = keyslot_verify_or_find_empty(cd, &keyslot);
1729         if (r)
1730                 return r;
1731
1732         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1733                 /* No slots used, try to use pre-generated key in header */
1734                 if (cd->volume_key) {
1735                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1736                         r = vk ? 0 : -ENOMEM;
1737                 } else {
1738                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1739                         return -EINVAL;
1740                 }
1741         } else {
1742                 /* Read password from file of (if NULL) from terminal */
1743                 if (keyfile)
1744                         r = key_from_file(cd, _("Enter any passphrase: "),
1745                                           &password, &passwordLen,
1746                                           keyfile, keyfile_size);
1747                 else
1748                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1749                                               &password, &passwordLen, 0);
1750                 if (r < 0)
1751                         goto out;
1752
1753                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1754                                            &cd->hdr, &vk, cd);
1755         }
1756
1757         if(r < 0)
1758                 goto out;
1759
1760         if (new_keyfile)
1761                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1762                                   &new_password, &new_passwordLen, new_keyfile,
1763                                   new_keyfile_size);
1764         else
1765                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1766                                       &new_password, &new_passwordLen, 1);
1767         if (r < 0)
1768                 goto out;
1769
1770         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1771                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1772 out:
1773         crypt_safe_free(password);
1774         crypt_safe_free(new_password);
1775         crypt_free_volume_key(vk);
1776         return r < 0 ? r : keyslot;
1777 }
1778
1779 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1780         int keyslot,
1781         const char *volume_key,
1782         size_t volume_key_size,
1783         const char *passphrase,
1784         size_t passphrase_size)
1785 {
1786         struct volume_key *vk = NULL;
1787         int r = -EINVAL;
1788         char *new_password = NULL; unsigned int new_passwordLen;
1789
1790         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1791
1792         if (!isLUKS(cd->type)) {
1793                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1794                 return -EINVAL;
1795         }
1796
1797         if (volume_key)
1798                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1799         else if (cd->volume_key)
1800                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1801
1802         if (!vk)
1803                 return -ENOMEM;
1804
1805         r = LUKS_verify_volume_key(&cd->hdr, vk);
1806         if (r < 0) {
1807                 log_err(cd, _("Volume key does not match the volume.\n"));
1808                 goto out;
1809         }
1810
1811         r = keyslot_verify_or_find_empty(cd, &keyslot);
1812         if (r)
1813                 goto out;
1814
1815         if (!passphrase) {
1816                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1817                                       &new_password, &new_passwordLen, 1);
1818                 if (r < 0)
1819                         goto out;
1820                 passphrase = new_password;
1821                 passphrase_size = new_passwordLen;
1822         }
1823
1824         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1825                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1826 out:
1827         crypt_safe_free(new_password);
1828         crypt_free_volume_key(vk);
1829         return (r < 0) ? r : keyslot;
1830 }
1831
1832 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1833 {
1834         crypt_keyslot_info ki;
1835
1836         log_dbg("Destroying keyslot %d.", keyslot);
1837
1838         if (!isLUKS(cd->type)) {
1839                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1840                 return -EINVAL;
1841         }
1842
1843         ki = crypt_keyslot_status(cd, keyslot);
1844         if (ki == CRYPT_SLOT_INVALID) {
1845                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1846                 return -EINVAL;
1847         }
1848
1849         if (ki == CRYPT_SLOT_INACTIVE) {
1850                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1851                 return -EINVAL;
1852         }
1853
1854         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1855 }
1856
1857 // activation/deactivation of device mapping
1858 int crypt_activate_by_passphrase(struct crypt_device *cd,
1859         const char *name,
1860         int keyslot,
1861         const char *passphrase,
1862         size_t passphrase_size,
1863         uint32_t flags)
1864 {
1865         crypt_status_info ci;
1866         struct volume_key *vk = NULL;
1867         char *read_passphrase = NULL;
1868         unsigned int passphraseLen = 0;
1869         int r;
1870
1871         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1872                 name ? "Activating" : "Checking", name ?: "",
1873                 keyslot, passphrase ? "" : "[none] ");
1874
1875         if (name) {
1876                 ci = crypt_status(NULL, name);
1877                 if (ci == CRYPT_INVALID)
1878                         return -EINVAL;
1879                 else if (ci >= CRYPT_ACTIVE) {
1880                         log_err(cd, _("Device %s already exists.\n"), name);
1881                         return -EEXIST;
1882                 }
1883         }
1884
1885         /* plain, use hashed passphrase */
1886         if (isPLAIN(cd->type)) {
1887                 if (!passphrase) {
1888                         r = key_from_terminal(cd, NULL, &read_passphrase,
1889                                               &passphraseLen, 0);
1890                         if (r < 0)
1891                                 goto out;
1892                         passphrase = read_passphrase;
1893                         passphrase_size = passphraseLen;
1894                 }
1895                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1896                                          cd->plain_cipher, cd->plain_cipher_mode,
1897                                          NULL, passphrase, passphrase_size,
1898                                          cd->volume_key->keylength, 0,
1899                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
1900                                          cd->plain_uuid,
1901                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1902                 keyslot = 0;
1903         } else if (isLUKS(cd->type)) {
1904                 /* provided passphrase, do not retry */
1905                 if (passphrase) {
1906                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1907                                                    passphrase_size, &cd->hdr, &vk, cd);
1908                 } else
1909                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1910
1911                 if (r >= 0) {
1912                         keyslot = r;
1913                         if (name)
1914                                 r = open_from_hdr_and_vk(cd, vk, name, flags);
1915                 }
1916         } else
1917                 r = -EINVAL;
1918 out:
1919         crypt_safe_free(read_passphrase);
1920         crypt_free_volume_key(vk);
1921
1922         return r < 0  ? r : keyslot;
1923 }
1924
1925 int crypt_activate_by_keyfile(struct crypt_device *cd,
1926         const char *name,
1927         int keyslot,
1928         const char *keyfile,
1929         size_t keyfile_size,
1930         uint32_t flags)
1931 {
1932         crypt_status_info ci;
1933         struct volume_key *vk = NULL;
1934         char *passphrase_read = NULL;
1935         unsigned int passphrase_size_read, key_count = 0;
1936         int r;
1937
1938         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1939                 name ?: "", keyslot, keyfile ?: "[none]");
1940
1941         if (name) {
1942                 ci = crypt_status(NULL, name);
1943                 if (ci == CRYPT_INVALID)
1944                         return -EINVAL;
1945                 else if (ci >= CRYPT_ACTIVE) {
1946                         log_err(cd, _("Device %s already exists.\n"), name);
1947                         return -EEXIST;
1948                 }
1949         }
1950
1951         if (!keyfile)
1952                 return -EINVAL;
1953
1954         if (isPLAIN(cd->type)) {
1955                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1956                                   &passphrase_size_read, keyfile, keyfile_size);
1957                 if (r < 0)
1958                         goto out;
1959                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1960                                          cd->plain_cipher, cd->plain_cipher_mode,
1961                                          NULL, passphrase_read, passphrase_size_read,
1962                                          cd->volume_key->keylength, 0,
1963                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
1964                                          cd->plain_uuid,
1965                                          flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1966         } else if (isLUKS(cd->type)) {
1967                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1968                           &passphrase_size_read, keyfile, keyfile_size);
1969                 if (r < 0)
1970                         goto out;
1971                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1972                                            passphrase_size_read, &cd->hdr, &vk, cd);
1973                 if (r < 0)
1974                         goto out;
1975                 keyslot = r;
1976
1977                 if (name) {
1978                         r = open_from_hdr_and_vk(cd, vk, name, flags);
1979                         if (r < 0)
1980                                 goto out;
1981                 }
1982                 r = keyslot;
1983         } else if (isLOOPAES(cd->type)) {
1984                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1985                                   keyfile, LOOPAES_KEYFILE_MAXSIZE);
1986                 if (r < 0)
1987                         goto out;
1988                 r = LOOPAES_parse_keyfile(cd, &vk, &key_count,
1989                                           passphrase_read, passphrase_size_read);
1990                 if (r < 0)
1991                         goto out;
1992                 if (name)
1993                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1994                                              key_count, vk, flags);
1995         } else
1996                 r = -EINVAL;
1997
1998 out:
1999         crypt_safe_free(passphrase_read);
2000         crypt_free_volume_key(vk);
2001
2002         return r;
2003 }
2004
2005 int crypt_activate_by_volume_key(struct crypt_device *cd,
2006         const char *name,
2007         const char *volume_key,
2008         size_t volume_key_size,
2009         uint32_t flags)
2010 {
2011         crypt_status_info ci;
2012         struct volume_key *vk;
2013         int r;
2014
2015         log_dbg("Activating volume %s by volume key.", name);
2016
2017         /* use key directly, no hash */
2018         if (isPLAIN(cd->type)) {
2019                 if (!volume_key || !volume_key_size || !cd->volume_key ||
2020                         volume_key_size != cd->volume_key->keylength) {
2021                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
2022                         return -EINVAL;
2023                 }
2024
2025                 return create_device_helper(cd, name, NULL,
2026                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
2027                         cd->volume_key->keylength, 0, cd->plain_hdr.skip,
2028                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
2029         }
2030
2031         if (!isLUKS(cd->type)) {
2032                 log_err(cd, _("Device type is not properly initialised.\n"));
2033                 return -EINVAL;
2034         }
2035
2036         if (name) {
2037                 ci = crypt_status(NULL, name);
2038                 if (ci == CRYPT_INVALID)
2039                         return -EINVAL;
2040                 else if (ci >= CRYPT_ACTIVE) {
2041                         log_err(cd, _("Device %s already exists.\n"), name);
2042                         return -EEXIST;
2043                 }
2044         }
2045
2046         /* If key is not provided, try to use internal key */
2047         if (!volume_key) {
2048                 if (!cd->volume_key) {
2049                         log_err(cd, _("Volume key does not match the volume.\n"));
2050                         return -EINVAL;
2051                 }
2052                 volume_key_size = cd->volume_key->keylength;
2053                 volume_key = cd->volume_key->key;
2054         }
2055
2056         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2057         if (!vk)
2058                 return -ENOMEM;
2059         r = LUKS_verify_volume_key(&cd->hdr, vk);
2060
2061         if (r == -EPERM)
2062                 log_err(cd, _("Volume key does not match the volume.\n"));
2063
2064         if (!r && name)
2065                 r = open_from_hdr_and_vk(cd, vk, name, flags);
2066
2067         crypt_free_volume_key(vk);
2068
2069         return r;
2070 }
2071
2072 int crypt_deactivate(struct crypt_device *cd, const char *name)
2073 {
2074         int r;
2075
2076         if (!name)
2077                 return -EINVAL;
2078
2079         log_dbg("Deactivating volume %s.", name);
2080
2081         if (!cd && dm_init(NULL, 1) < 0)
2082                 return -ENOSYS;
2083
2084         switch (crypt_status(cd, name)) {
2085                 case CRYPT_ACTIVE:
2086                         r = dm_remove_device(name, 0, 0);
2087                         break;
2088                 case CRYPT_BUSY:
2089                         log_err(cd, _("Device %s is busy.\n"), name);
2090                         r = -EBUSY;
2091                         break;
2092                 case CRYPT_INACTIVE:
2093                         log_err(cd, _("Device %s is not active.\n"), name);
2094                         r = -ENODEV;
2095                         break;
2096                 default:
2097                         log_err(cd, _("Invalid device %s.\n"), name);
2098                         r = -EINVAL;
2099         }
2100
2101         if (!cd)
2102                 dm_exit();
2103
2104         return r;
2105 }
2106
2107 int crypt_volume_key_get(struct crypt_device *cd,
2108         int keyslot,
2109         char *volume_key,
2110         size_t *volume_key_size,
2111         const char *passphrase,
2112         size_t passphrase_size)
2113 {
2114         struct volume_key *vk;
2115         char *processed_key = NULL;
2116         int r, key_len;
2117
2118         key_len = crypt_get_volume_key_size(cd);
2119         if (key_len > *volume_key_size) {
2120                 log_err(cd, _("Volume key buffer too small.\n"));
2121                 return -ENOMEM;
2122         }
2123
2124         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2125                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
2126                                             passphrase, passphrase_size);
2127                 if (!processed_key) {
2128                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2129                         return -EINVAL;
2130                 }
2131                 memcpy(volume_key, processed_key, key_len);
2132                 *volume_key_size = key_len;
2133                 crypt_safe_free(processed_key);
2134                 return 0;
2135         }
2136
2137         if (isLUKS(cd->type)) {
2138                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
2139                                         passphrase_size, &cd->hdr, &vk, cd);
2140
2141                 if (r >= 0) {
2142                         memcpy(volume_key, vk->key, vk->keylength);
2143                         *volume_key_size = vk->keylength;
2144                 }
2145
2146                 crypt_free_volume_key(vk);
2147                 return r;
2148         }
2149
2150         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2151         return -EINVAL;
2152 }
2153
2154 int crypt_volume_key_verify(struct crypt_device *cd,
2155         const char *volume_key,
2156         size_t volume_key_size)
2157 {
2158         struct volume_key *vk;
2159         int r;
2160
2161         if (!isLUKS(cd->type)) {
2162                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2163                 return -EINVAL;
2164         }
2165
2166         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2167         if (!vk)
2168                 return -ENOMEM;
2169
2170         r = LUKS_verify_volume_key(&cd->hdr, vk);
2171
2172         if (r == -EPERM)
2173                 log_err(cd, _("Volume key does not match the volume.\n"));
2174
2175         crypt_free_volume_key(vk);
2176
2177         return r;
2178 }
2179
2180 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2181 {
2182         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2183         cd->timeout = timeout_sec;
2184 }
2185
2186 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2187 {
2188         log_dbg("Password retry count set to %d.", tries);
2189         cd->tries = tries;
2190 }
2191
2192 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2193 {
2194         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2195         cd->iteration_time = iteration_time_ms;
2196 }
2197
2198 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2199 {
2200         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2201         cd->password_verify = password_verify ? 1 : 0;
2202 }
2203
2204 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2205 {
2206         switch (rng_type) {
2207         case CRYPT_RNG_URANDOM:
2208         case CRYPT_RNG_RANDOM:
2209                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2210                 cd->rng_type = rng_type;
2211         }
2212 }
2213
2214 int crypt_get_rng_type(struct crypt_device *cd)
2215 {
2216         if (!cd)
2217                 return -EINVAL;
2218
2219         return cd->rng_type;
2220 }
2221
2222 int crypt_memory_lock(struct crypt_device *cd, int lock)
2223 {
2224         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2225 }
2226
2227 // reporting
2228 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2229 {
2230         int r;
2231
2232         if (!cd && dm_init(NULL, 1) < 0)
2233                 return CRYPT_INVALID;
2234
2235         r = dm_status_device(name);
2236
2237         if (!cd)
2238                 dm_exit();
2239
2240         if (r < 0 && r != -ENODEV)
2241                 return CRYPT_INVALID;
2242
2243         if (r == 0)
2244                 return CRYPT_ACTIVE;
2245
2246         if (r > 0)
2247                 return CRYPT_BUSY;
2248
2249         return CRYPT_INACTIVE;
2250 }
2251
2252 static void hexprintICB(struct crypt_device *cd, char *d, int n)
2253 {
2254         int i;
2255         for(i = 0; i < n; i++)
2256                 log_std(cd, "%02hhx ", (char)d[i]);
2257 }
2258
2259 int crypt_dump(struct crypt_device *cd)
2260 {
2261         int i;
2262         if (!isLUKS(cd->type)) { //FIXME
2263                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2264                 return -EINVAL;
2265         }
2266
2267         log_std(cd, "LUKS header information for %s\n\n", cd->device);
2268         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2269         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2270         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2271         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2272         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2273         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2274         log_std(cd, "MK digest:     \t");
2275         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
2276         log_std(cd, "\n");
2277         log_std(cd, "MK salt:       \t");
2278         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
2279         log_std(cd, "\n               \t");
2280         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2281         log_std(cd, "\n");
2282         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2283         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2284         for(i = 0; i < LUKS_NUMKEYS; i++) {
2285                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2286                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2287                         log_std(cd, "\tIterations:         \t%d\n",
2288                                 cd->hdr.keyblock[i].passwordIterations);
2289                         log_std(cd, "\tSalt:               \t");
2290                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
2291                                     LUKS_SALTSIZE/2);
2292                         log_std(cd, "\n\t                      \t");
2293                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
2294                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2295                         log_std(cd, "\n");
2296
2297                         log_std(cd, "\tKey material offset:\t%d\n",
2298                                 cd->hdr.keyblock[i].keyMaterialOffset);
2299                         log_std(cd, "\tAF stripes:            \t%d\n",
2300                                 cd->hdr.keyblock[i].stripes);
2301                 }
2302                 else 
2303                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2304         }
2305
2306         return 0;
2307 }
2308
2309 const char *crypt_get_cipher(struct crypt_device *cd)
2310 {
2311         if (isPLAIN(cd->type))
2312                 return cd->plain_cipher;
2313
2314         if (isLUKS(cd->type))
2315                 return cd->hdr.cipherName;
2316
2317         if (isLOOPAES(cd->type))
2318                 return cd->loopaes_cipher;
2319
2320         return NULL;
2321 }
2322
2323 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2324 {
2325         if (isPLAIN(cd->type))
2326                 return cd->plain_cipher_mode;
2327
2328         if (isLUKS(cd->type))
2329                 return cd->hdr.cipherMode;
2330
2331         if (isLOOPAES(cd->type))
2332                 return cd->loopaes_cipher_mode;
2333
2334         return NULL;
2335 }
2336
2337 const char *crypt_get_uuid(struct crypt_device *cd)
2338 {
2339         if (isLUKS(cd->type))
2340                 return cd->hdr.uuid;
2341
2342         if (isPLAIN(cd->type))
2343                 return cd->plain_uuid;
2344
2345         if (isLOOPAES(cd->type))
2346                 return cd->loopaes_uuid;
2347
2348         return NULL;
2349 }
2350
2351 const char *crypt_get_device_name(struct crypt_device *cd)
2352 {
2353         return cd->device;
2354 }
2355
2356 int crypt_get_volume_key_size(struct crypt_device *cd)
2357 {
2358         if (isPLAIN(cd->type) && cd->volume_key)
2359                 return cd->volume_key->keylength;
2360
2361         if (isLUKS(cd->type))
2362                 return cd->hdr.keyBytes;
2363
2364         if (isLOOPAES(cd->type))
2365                 return cd->loopaes_key_size;
2366
2367         return 0;
2368 }
2369
2370 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2371 {
2372         if (isPLAIN(cd->type))
2373                 return cd->plain_hdr.offset;
2374
2375         if (isLUKS(cd->type))
2376                 return cd->hdr.payloadOffset;
2377
2378         if (isLOOPAES(cd->type))
2379                 return cd->loopaes_hdr.offset;
2380
2381         return 0;
2382 }
2383
2384 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2385 {
2386         if (!isLUKS(cd->type)) {
2387                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2388                 return CRYPT_SLOT_INVALID;
2389         }
2390
2391         return LUKS_keyslot_info(&cd->hdr, keyslot);
2392 }
2393
2394 int crypt_keyslot_max(const char *type)
2395 {
2396         if (type && isLUKS(type))
2397                 return LUKS_NUMKEYS;
2398
2399         return -EINVAL;
2400 }
2401
2402 const char *crypt_get_type(struct crypt_device *cd)
2403 {
2404         return cd->type;
2405 }
2406
2407 int crypt_get_active_device(struct crypt_device *cd,
2408                             const char *name,
2409                             struct crypt_active_device *cad)
2410 {
2411         int r, readonly;
2412
2413         r = dm_query_device(name, NULL, &cad->size, &cad->iv_offset, &cad->offset,
2414                             NULL, NULL, NULL, &readonly, NULL, NULL);
2415         if (r < 0)
2416                 return r;
2417
2418         cad->flags = readonly ? CRYPT_ACTIVATE_READONLY : 0;
2419
2420         return 0;
2421 }