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