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