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