Rewrite dm query/create function backend.
[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 static int process_key(struct crypt_device *cd, const char *hash_name,
139                        size_t key_size, const char *pass, size_t passLen,
140                        struct volume_key **vk)
141 {
142         int r;
143
144         if (!key_size)
145                 return -EINVAL;
146
147         *vk = crypt_alloc_volume_key(key_size, NULL);
148         if (!*vk)
149                 return -ENOMEM;
150
151         if (hash_name) {
152                 r = crypt_plain_hash(cd, hash_name, (*vk)->key, key_size, pass, passLen);
153                 if (r < 0) {
154                         if (r == -ENOENT)
155                                 log_err(cd, _("Hash algorithm %s not supported.\n"),
156                                         hash_name);
157                         else
158                                 log_err(cd, _("Key processing error (using hash %s).\n"),
159                                         hash_name);
160                         crypt_free_volume_key(*vk);
161                         *vk = NULL;
162                         return -EINVAL;
163                 }
164         } else if (passLen > key_size) {
165                 memcpy((*vk)->key, pass, key_size);
166         } else {
167                 memcpy((*vk)->key, pass, passLen);
168         }
169
170         return 0;
171 }
172
173 static int isPLAIN(const char *type)
174 {
175         return (type && !strcmp(CRYPT_PLAIN, type));
176 }
177
178 static int isLUKS(const char *type)
179 {
180         return (type && !strcmp(CRYPT_LUKS1, type));
181 }
182
183 static int isLOOPAES(const char *type)
184 {
185         return (type && !strcmp(CRYPT_LOOPAES, type));
186 }
187
188 /* keyslot helpers */
189 static int keyslot_verify_or_find_empty(struct crypt_device *cd, int *keyslot)
190 {
191         if (*keyslot == CRYPT_ANY_SLOT) {
192                 *keyslot = LUKS_keyslot_find_empty(&cd->hdr);
193                 if (*keyslot < 0) {
194                         log_err(cd, _("All key slots full.\n"));
195                         return -EINVAL;
196                 }
197         }
198
199         switch (LUKS_keyslot_info(&cd->hdr, *keyslot)) {
200                 case CRYPT_SLOT_INVALID:
201                         log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
202                                 *keyslot, LUKS_NUMKEYS - 1);
203                         return -EINVAL;
204                 case CRYPT_SLOT_INACTIVE:
205                         break;
206                 default:
207                         log_err(cd, _("Key slot %d is full, please select another one.\n"),
208                                 *keyslot);
209                         return -EINVAL;
210         }
211
212         return 0;
213 }
214
215 int PLAIN_activate(struct crypt_device *cd,
216                      const char *name,
217                      struct volume_key *vk,
218                      uint64_t size,
219                      uint64_t iv_offset,
220                      uint32_t flags)
221 {
222         int r;
223         char *dm_cipher = NULL;
224         struct crypt_dm_active_device dmd = {
225                 .device = crypt_get_device_name(cd),
226                 .cipher = NULL,
227                 .uuid   = crypt_get_uuid(cd),
228                 .key    = vk->key,
229                 .key_size = vk->keylength,
230                 .offset = crypt_get_data_offset(cd),
231                 .iv_offset = iv_offset,
232                 .size   = size,
233                 .flags  = flags
234         };
235
236         r = device_check_and_adjust(cd, dmd.device,
237                                     (dmd.flags & CRYPT_ACTIVATE_SHARED) ? DEV_SHARED : DEV_EXCL,
238                                     &dmd.size, &dmd.offset, &flags);
239         if (r)
240                 return r;
241
242         if (crypt_get_cipher_mode(cd))
243                 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
244         else
245                 r = asprintf(&dm_cipher, "%s", crypt_get_cipher(cd));
246         if (r < 0)
247                 return -ENOMEM;
248
249         dmd.cipher = dm_cipher;
250         log_dbg("Trying to activate PLAIN device %s using cipher %s.", name, dmd.cipher);
251
252         r = dm_create_device(name, CRYPT_PLAIN, &dmd, 0);
253
254         // FIXME
255         if (!cd->plain_uuid && dm_query_device(name, DM_ACTIVE_UUID, &dmd) >= 0)
256                 cd->plain_uuid = (char*)dmd.uuid;
257
258         free(dm_cipher);
259         return r;
260 }
261
262 int crypt_confirm(struct crypt_device *cd, const char *msg)
263 {
264         if (!cd || !cd->confirm)
265                 return 1;
266         else
267                 return cd->confirm(msg, cd->confirm_usrptr);
268 }
269
270 static int key_from_terminal(struct crypt_device *cd, char *msg, char **key,
271                               size_t *key_len, int force_verify)
272 {
273         char *prompt = NULL;
274         int r;
275
276         *key = NULL;
277         if(!msg && asprintf(&prompt, _("Enter passphrase for %s: "),
278                             cd->backing_file ?: cd->device) < 0)
279                 return -ENOMEM;
280
281         if (!msg)
282                 msg = prompt;
283
284         if (cd->password) {
285                 *key = crypt_safe_alloc(DEFAULT_PASSPHRASE_SIZE_MAX);
286                 if (!*key) {
287                         r = -ENOMEM;
288                         goto out;
289                 }
290                 r = cd->password(msg, *key, DEFAULT_PASSPHRASE_SIZE_MAX,
291                                  cd->password_usrptr);
292                 if (r < 0) {
293                         crypt_safe_free(*key);
294                         *key = NULL;
295                 } else
296                         *key_len = r;
297         } else
298                 r = crypt_get_key(msg, key, key_len, 0, NULL, cd->timeout,
299                                   (force_verify || cd->password_verify), cd);
300 out:
301         free(prompt);
302         return (r < 0) ? r: 0;
303 }
304
305 static int volume_key_by_terminal_passphrase(struct crypt_device *cd, int keyslot,
306                                              struct volume_key **vk)
307 {
308         char *passphrase_read = NULL;
309         size_t passphrase_size_read;
310         int r = -EINVAL, eperm = 0, tries = cd->tries;
311
312         *vk = NULL;
313         do {
314                 crypt_free_volume_key(*vk);
315                 *vk = NULL;
316
317                 r = key_from_terminal(cd, NULL, &passphrase_read,
318                                       &passphrase_size_read, 0);
319                 if(r < 0)
320                         goto out;
321
322                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
323                                            passphrase_size_read, &cd->hdr, vk, cd);
324                 if (r == -EPERM)
325                         eperm = 1;
326                 crypt_safe_free(passphrase_read);
327                 passphrase_read = NULL;
328         } while (r == -EPERM && (--tries > 0));
329 out:
330         if (r < 0) {
331                 crypt_free_volume_key(*vk);
332                 *vk = NULL;
333
334                 /* Report wrong passphrase if at least one try failed */
335                 if (eperm && r == -EPIPE)
336                         r = -EPERM;
337         }
338
339         crypt_safe_free(passphrase_read);
340         return r;
341 }
342
343 static int key_from_file(struct crypt_device *cd, char *msg,
344                           char **key, size_t *key_len,
345                           const char *key_file, size_t key_size)
346 {
347         return crypt_get_key(msg, key, key_len, key_size, key_file,
348                              cd->timeout, 0, cd);
349 }
350
351 void crypt_set_log_callback(struct crypt_device *cd,
352         void (*log)(int level, const char *msg, void *usrptr),
353         void *usrptr)
354 {
355         if (!cd)
356                 _default_log = log;
357         else {
358                 cd->log = log;
359                 cd->log_usrptr = usrptr;
360         }
361 }
362
363 void crypt_set_confirm_callback(struct crypt_device *cd,
364         int (*confirm)(const char *msg, void *usrptr),
365         void *usrptr)
366 {
367         cd->confirm = confirm;
368         cd->confirm_usrptr = usrptr;
369 }
370
371 void crypt_set_password_callback(struct crypt_device *cd,
372         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
373         void *usrptr)
374 {
375         cd->password = password;
376         cd->password_usrptr = usrptr;
377 }
378
379 void crypt_get_error(char *buf, size_t size)
380 {
381         const char *error = get_error();
382
383         if (!buf || size < 1)
384                 set_error(NULL);
385         else if (error) {
386                 strncpy(buf, error, size - 1);
387                 buf[size - 1] = '\0';
388                 set_error(NULL);
389         } else
390                 buf[0] = '\0';
391 }
392
393 const char *crypt_get_dir(void)
394 {
395         return dm_get_dir();
396 }
397
398 int crypt_init(struct crypt_device **cd, const char *device)
399 {
400         struct crypt_device *h = NULL;
401         int r, readonly = 0;
402
403         if (!cd)
404                 return -EINVAL;
405
406         log_dbg("Allocating crypt device %s context.", device);
407
408         if (!(h = malloc(sizeof(struct crypt_device))))
409                 return -ENOMEM;
410
411         memset(h, 0, sizeof(*h));
412         h->loop_fd = -1;
413
414         if (device) {
415                 r = device_ready(NULL, device, O_RDONLY);
416                 if (r == -ENOTBLK) {
417                         h->device = crypt_loop_get_device();
418                         log_dbg("Not a block device, %s%s.",
419                                 h->device ? "using free loop device " :
420                                          "no free loop device found",
421                                 h->device ?: "");
422                         if (!h->device) {
423                                 log_err(NULL, _("Cannot find a free loopback device.\n"));
424                                 r = -ENOSYS;
425                                 goto bad;
426                         }
427
428                         /* Keep the loop open, dettached on last close. */
429                         h->loop_fd = crypt_loop_attach(h->device, device, 0, 1, &readonly);
430                         if (h->loop_fd == -1) {
431                                 log_err(NULL, _("Attaching loopback device failed "
432                                         "(loop device with autoclear flag is required).\n"));
433                                 r = -EINVAL;
434                                 goto bad;
435                         }
436
437                         h->backing_file = crypt_loop_backing_file(h->device);
438                         r = device_ready(NULL, h->device, O_RDONLY);
439                 }
440                 if (r < 0) {
441                         r = -ENOTBLK;
442                         goto bad;
443                 }
444         }
445
446         if (!h->device && device && !(h->device = strdup(device))) {
447                 r = -ENOMEM;
448                 goto bad;
449         }
450
451         if (dm_init(h, 1) < 0) {
452                 r = -ENOSYS;
453                 goto bad;
454         }
455
456         h->iteration_time = 1000;
457         h->password_verify = 0;
458         h->tries = 3;
459         h->rng_type = crypt_random_default_key_rng();
460         *cd = h;
461         return 0;
462 bad:
463
464         if (h) {
465                 if (h->loop_fd != -1)
466                         close(h->loop_fd);
467                 free(h->device);
468                 free(h->backing_file);
469         }
470         free(h);
471         return r;
472 }
473
474 int crypt_init_by_name(struct crypt_device **cd, const char *name)
475 {
476         crypt_status_info ci;
477         struct crypt_dm_active_device dmd;
478         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
479         int key_nums, r;
480
481
482         log_dbg("Allocating crypt device context by device %s.", name);
483
484         ci = crypt_status(NULL, name);
485         if (ci == CRYPT_INVALID)
486                 return -ENODEV;
487
488         if (ci < CRYPT_ACTIVE) {
489                 log_err(NULL, _("Device %s is not active.\n"), name);
490                 return -ENODEV;
491         }
492
493         r = dm_query_device(name, DM_ACTIVE_ALL, &dmd);
494         if (r < 0)
495                 goto out;
496
497         *cd = NULL;
498         r = crypt_init(cd, dmd.device);
499
500         /* Underlying device disappeared but mapping still active */
501         if (!dmd.device || r == -ENOTBLK)
502                 log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
503                             name);
504
505         /* Underlying device is not readable but crypt mapping exists */
506         if (r == -ENOTBLK) {
507                 free((char*)dmd.device);
508                 dmd.device = NULL;
509                 r = crypt_init(cd, NULL);
510         }
511
512         if (r < 0)
513                 goto out;
514
515         /* Try to initialise basic parameters from active device */
516
517         if (!(*cd)->backing_file && dmd.device && crypt_loop_device(dmd.device) &&
518             !((*cd)->backing_file = crypt_loop_backing_file(dmd.device))) {
519                 r = -ENOMEM;
520                 goto out;
521         }
522
523         if (dmd.uuid) {
524                 if (!strncmp(CRYPT_PLAIN, dmd.uuid, sizeof(CRYPT_PLAIN)-1)) {
525                         (*cd)->type = strdup(CRYPT_PLAIN);
526                         (*cd)->plain_uuid = strdup(dmd.uuid);
527                         (*cd)->plain_hdr.hash = NULL; /* no way to get this */
528                         (*cd)->plain_hdr.offset = dmd.offset;
529                         (*cd)->plain_hdr.skip = dmd.iv_offset;
530                         (*cd)->volume_key = crypt_alloc_volume_key(dmd.key_size, dmd.key);
531                         if (!(*cd)->volume_key) {
532                                 r = -ENOMEM;
533                                 goto out;
534                         }
535
536                         r = crypt_parse_name_and_mode(dmd.cipher, cipher, NULL, cipher_mode);
537                         if (!r) {
538                                 (*cd)->plain_cipher = strdup(cipher);
539                                 (*cd)->plain_cipher_mode = strdup(cipher_mode);
540                         }
541                 } else if (!strncmp(CRYPT_LOOPAES, dmd.uuid, sizeof(CRYPT_LOOPAES)-1)) {
542                         (*cd)->type = strdup(CRYPT_LOOPAES);
543                         (*cd)->loopaes_uuid = strdup(dmd.uuid);
544                         (*cd)->loopaes_hdr.offset = dmd.offset;
545
546                         r = crypt_parse_name_and_mode(dmd.cipher, cipher,
547                                                       &key_nums, cipher_mode);
548                         if (!r) {
549                                 (*cd)->loopaes_cipher = strdup(cipher);
550                                 (*cd)->loopaes_cipher_mode = strdup(cipher_mode);
551                                 /* version 3 uses last key for IV */
552                                 if (dmd.key_size % key_nums)
553                                         key_nums++;
554                                 (*cd)->loopaes_key_size = dmd.key_size / key_nums;
555                         }
556                 } else if (!strncmp(CRYPT_LUKS1, dmd.uuid, sizeof(CRYPT_LUKS1)-1)) {
557                         if (dmd.device) {
558                                 if (crypt_load(*cd, CRYPT_LUKS1, NULL) < 0 ||
559                                     crypt_volume_key_verify(*cd, dmd.key, dmd.key_size) < 0) {
560                                         log_dbg("LUKS device header does not match active device.");
561                                         goto out;
562                                 }
563
564                                 (*cd)->volume_key = crypt_alloc_volume_key(dmd.key_size, dmd.key);
565                                 if (!(*cd)->volume_key) {
566                                         r = -ENOMEM;
567                                         goto out;
568                                 }
569                         }
570                 }
571         } else
572                 log_dbg("Active device has no UUID set, some parameters are not set.");
573
574 out:
575         if (r < 0) {
576                 crypt_free(*cd);
577                 *cd = NULL;
578         }
579         crypt_safe_free(dmd.key);
580         free((char*)dmd.device);
581         free((char*)dmd.cipher);
582         free((char*)dmd.uuid);
583         return r;
584 }
585
586 static int _crypt_format_plain(struct crypt_device *cd,
587                                const char *cipher,
588                                const char *cipher_mode,
589                                const char *uuid,
590                                size_t volume_key_size,
591                                struct crypt_params_plain *params)
592 {
593         if (!cipher || !cipher_mode) {
594                 log_err(cd, _("Invalid plain crypt parameters.\n"));
595                 return -EINVAL;
596         }
597
598         if (volume_key_size > 1024) {
599                 log_err(cd, _("Invalid key size.\n"));
600                 return -EINVAL;
601         }
602
603         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
604         if (!cd->volume_key)
605                 return -ENOMEM;
606
607         cd->plain_cipher = strdup(cipher);
608         cd->plain_cipher_mode = strdup(cipher_mode);
609
610         if (uuid)
611                 cd->plain_uuid = strdup(uuid);
612
613         if (params && params->hash)
614                 cd->plain_hdr.hash = strdup(params->hash);
615
616         cd->plain_hdr.offset = params ? params->offset : 0;
617         cd->plain_hdr.skip = params ? params->skip : 0;
618         cd->plain_hdr.size = params ? params->size : 0;
619
620         if (!cd->plain_cipher || !cd->plain_cipher_mode)
621                 return -ENOMEM;
622
623         return 0;
624 }
625
626 static int _crypt_format_luks1(struct crypt_device *cd,
627                                const char *cipher,
628                                const char *cipher_mode,
629                                const char *uuid,
630                                const char *volume_key,
631                                size_t volume_key_size,
632                                struct crypt_params_luks1 *params)
633 {
634         int r;
635         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
636         unsigned long alignment_offset = 0;
637
638         if (!cd->device) {
639                 log_err(cd, _("Can't format LUKS without device.\n"));
640                 return -EINVAL;
641         }
642
643         if (volume_key)
644                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
645                                                       volume_key);
646         else
647                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
648
649         if(!cd->volume_key)
650                 return -ENOMEM;
651
652         if (params && params->data_alignment)
653                 required_alignment = params->data_alignment * SECTOR_SIZE;
654         else
655                 get_topology_alignment(cd->device, &required_alignment,
656                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
657
658         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
659                                (params && params->hash) ? params->hash : "sha1",
660                                uuid, LUKS_STRIPES,
661                                required_alignment / SECTOR_SIZE,
662                                alignment_offset / SECTOR_SIZE,
663                                cd->iteration_time, &cd->PBKDF2_per_sec, cd);
664         if(r < 0)
665                 return r;
666
667         /* Wipe first 8 sectors - fs magic numbers etc. */
668         r = wipe_device_header(cd->device, 8);
669         if(r < 0) {
670                 if (r == -EBUSY)
671                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
672                                 cd->device);
673                 else
674                         log_err(cd, _("Cannot wipe header on device %s.\n"),
675                                 cd->device);
676
677                 return r;
678         }
679
680         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
681
682         return r;
683 }
684
685 static int _crypt_format_loopaes(struct crypt_device *cd,
686                                  const char *cipher,
687                                  const char *uuid,
688                                  size_t volume_key_size,
689                                  struct crypt_params_loopaes *params)
690 {
691         if (!cd->device) {
692                 log_err(cd, _("Can't format LOOPAES without device.\n"));
693                 return -EINVAL;
694         }
695
696         if (volume_key_size > 1024) {
697                 log_err(cd, _("Invalid key size.\n"));
698                 return -EINVAL;
699         }
700
701         cd->loopaes_key_size = volume_key_size;
702
703         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
704
705         if (uuid)
706                 cd->loopaes_uuid = strdup(uuid);
707
708         if (params && params->hash)
709                 cd->loopaes_hdr.hash = strdup(params->hash);
710
711         cd->loopaes_hdr.offset = params ? params->offset : 0;
712         cd->loopaes_hdr.skip = params ? params->skip : 0;
713
714         return 0;
715 }
716
717 int crypt_format(struct crypt_device *cd,
718         const char *type,
719         const char *cipher,
720         const char *cipher_mode,
721         const char *uuid,
722         const char *volume_key,
723         size_t volume_key_size,
724         void *params)
725 {
726         int r;
727
728         if (!type)
729                 return -EINVAL;
730
731         log_dbg("Formatting device %s as type %s.", cd->device ?: "(none)", type);
732
733         r = init_crypto(cd);
734         if (r < 0)
735                 return r;
736
737         if (isPLAIN(type))
738                 r = _crypt_format_plain(cd, cipher, cipher_mode,
739                                         uuid, volume_key_size, params);
740         else if (isLUKS(type))
741                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
742                                         uuid, volume_key, volume_key_size, params);
743         else if (isLOOPAES(type))
744                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
745         else {
746                 /* FIXME: allow plugins here? */
747                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
748                 r = -EINVAL;
749         }
750
751         if (!r && !(cd->type = strdup(type)))
752                 r = -ENOMEM;
753
754         if (r < 0) {
755                 crypt_free_volume_key(cd->volume_key);
756                 cd->volume_key = NULL;
757         }
758
759         return r;
760 }
761
762 int crypt_load(struct crypt_device *cd,
763                const char *requested_type,
764                void *params __attribute__((unused)))
765 {
766         struct luks_phdr hdr;
767         int r;
768
769         log_dbg("Trying to load %s crypt type from device %s.",
770                 requested_type ?: "any", cd->device ?: "(none)");
771
772         if (!cd->device)
773                 return -EINVAL;
774
775         if (requested_type && !isLUKS(requested_type))
776                 return -EINVAL;
777
778         r = init_crypto(cd);
779         if (r < 0)
780                 return r;
781
782         r = LUKS_read_phdr(cd->device, &hdr, 1, cd);
783
784         if (!r) {
785                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
786                 cd->type = strdup(CRYPT_LUKS1);
787                 if (!cd->type)
788                         r = -ENOMEM;
789         }
790
791         return r;
792 }
793
794 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
795 {
796         struct crypt_dm_active_device dmd;
797         int r;
798
799         /* Device context type must be initialised */
800         if (!cd->type || !crypt_get_uuid(cd))
801                 return -EINVAL;
802
803         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
804
805         r = dm_query_device(name, DM_ACTIVE_ALL, &dmd);
806         if (r < 0) {
807                 log_err(NULL, _("Device %s is not active.\n"), name);
808                 goto out;
809         }
810
811         if (!dmd.uuid) {
812                 r = -EINVAL;
813                 goto out;
814         }
815
816         r = device_check_and_adjust(cd, dmd.device, DEV_OK, &new_size, &dmd.offset, &dmd.flags);
817         if (r)
818                 goto out;
819
820         if (new_size == dmd.size) {
821                 log_dbg("Device has already requested size %" PRIu64
822                         " sectors.", dmd.size);
823                 r = 0;
824         } else {
825                 dmd.size = new_size;
826                 r = dm_create_device(name, cd->type, &dmd, 1);
827         }
828 out:
829         crypt_safe_free(dmd.key);
830         free((char*)dmd.cipher);
831         free((char*)dmd.device);
832         free((char*)dmd.uuid);
833
834         return r;
835 }
836
837 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
838 {
839         if (!isLUKS(cd->type)) {
840                 log_err(cd, _("This operation is not supported for this device type.\n"));
841                 return  -EINVAL;
842         }
843
844         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
845                 log_dbg("UUID is the same as requested (%s) for device %s.",
846                         uuid, cd->device);
847                 return 0;
848         }
849
850         if (uuid)
851                 log_dbg("Requested new UUID change to %s for %s.", uuid, cd->device);
852         else
853                 log_dbg("Requested new UUID refresh for %s.", cd->device);
854
855         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
856                 return -EPERM;
857
858         return LUKS_hdr_uuid_set(cd->device, &cd->hdr, uuid, cd);
859 }
860
861 int crypt_header_backup(struct crypt_device *cd,
862                         const char *requested_type,
863                         const char *backup_file)
864 {
865         int r;
866
867         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
868                 return -EINVAL;
869
870         r = init_crypto(cd);
871         if (r < 0)
872                 return r;
873
874         log_dbg("Requested header backup of device %s (%s) to "
875                 "file %s.", cd->device, requested_type, backup_file);
876
877         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
878 }
879
880 int crypt_header_restore(struct crypt_device *cd,
881                          const char *requested_type,
882                          const char *backup_file)
883 {
884         int r;
885
886         if (requested_type && !isLUKS(requested_type))
887                 return -EINVAL;
888
889         /* Some hash functions need initialized gcrypt library */
890         r = init_crypto(cd);
891         if (r < 0)
892                 return r;
893
894         log_dbg("Requested header restore to device %s (%s) from "
895                 "file %s.", cd->device, requested_type, backup_file);
896
897         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
898 }
899
900 void crypt_free(struct crypt_device *cd)
901 {
902         if (cd) {
903                 log_dbg("Releasing crypt device %s context.", cd->device);
904
905                 if (cd->loop_fd != -1)
906                         close(cd->loop_fd);
907
908                 dm_exit();
909                 crypt_free_volume_key(cd->volume_key);
910
911                 free(cd->device);
912                 free(cd->backing_file);
913                 free(cd->type);
914
915                 /* used in plain device only */
916                 free((char*)cd->plain_hdr.hash);
917                 free(cd->plain_cipher);
918                 free(cd->plain_cipher_mode);
919                 free(cd->plain_uuid);
920
921                 /* used in loop-AES device only */
922                 free((char*)cd->loopaes_hdr.hash);
923                 free(cd->loopaes_cipher);
924                 free(cd->loopaes_uuid);
925
926                 free(cd);
927         }
928 }
929
930 int crypt_suspend(struct crypt_device *cd,
931                   const char *name)
932 {
933         crypt_status_info ci;
934         int r;
935
936         log_dbg("Suspending volume %s.", name);
937
938         ci = crypt_status(NULL, name);
939         if (ci < CRYPT_ACTIVE) {
940                 log_err(cd, _("Volume %s is not active.\n"), name);
941                 return -EINVAL;
942         }
943
944         if (!cd && dm_init(NULL, 1) < 0)
945                 return -ENOSYS;
946
947         r = dm_status_suspended(name);
948         if (r < 0)
949                 goto out;
950
951         if (r) {
952                 log_err(cd, _("Volume %s is already suspended.\n"), name);
953                 r = -EINVAL;
954                 goto out;
955         }
956
957         r = dm_suspend_and_wipe_key(name);
958         if (r == -ENOTSUP)
959                 log_err(cd, "Suspend is not supported for device %s.\n", name);
960         else if (r)
961                 log_err(cd, "Error during suspending device %s.\n", name);
962 out:
963         if (!cd)
964                 dm_exit();
965         return r;
966 }
967
968 int crypt_resume_by_passphrase(struct crypt_device *cd,
969                                const char *name,
970                                int keyslot,
971                                const char *passphrase,
972                                size_t passphrase_size)
973 {
974         struct volume_key *vk = NULL;
975         int r;
976
977         log_dbg("Resuming volume %s.", name);
978
979         if (!isLUKS(cd->type)) {
980                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
981                 r = -EINVAL;
982                 goto out;
983         }
984
985         r = dm_status_suspended(name);
986         if (r < 0)
987                 return r;
988
989         if (!r) {
990                 log_err(cd, _("Volume %s is not suspended.\n"), name);
991                 return -EINVAL;
992         }
993
994         if (passphrase) {
995                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
996                                            passphrase_size, &cd->hdr, &vk, cd);
997         } else
998                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
999
1000         if (r >= 0) {
1001                 keyslot = r;
1002                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1003                 if (r == -ENOTSUP)
1004                         log_err(cd, "Resume is not supported for device %s.\n", name);
1005                 else if (r)
1006                         log_err(cd, "Error during resuming device %s.\n", name);
1007         } else
1008                 r = keyslot;
1009 out:
1010         crypt_free_volume_key(vk);
1011         return r < 0 ? r : keyslot;
1012 }
1013
1014 int crypt_resume_by_keyfile(struct crypt_device *cd,
1015                             const char *name,
1016                             int keyslot,
1017                             const char *keyfile,
1018                             size_t keyfile_size)
1019 {
1020         struct volume_key *vk = NULL;
1021         char *passphrase_read = NULL;
1022         size_t passphrase_size_read;
1023         int r;
1024
1025         log_dbg("Resuming volume %s.", name);
1026
1027         if (!isLUKS(cd->type)) {
1028                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1029                 r = -EINVAL;
1030                 goto out;
1031         }
1032
1033         r = dm_status_suspended(name);
1034         if (r < 0)
1035                 return r;
1036
1037         if (!r) {
1038                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1039                 return -EINVAL;
1040         }
1041
1042         if (!keyfile)
1043                 return -EINVAL;
1044
1045         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1046                           &passphrase_size_read, keyfile, keyfile_size);
1047         if (r < 0)
1048                 goto out;
1049
1050         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1051                                    passphrase_size_read, &cd->hdr, &vk, cd);
1052         if (r < 0)
1053                 goto out;
1054
1055         keyslot = r;
1056         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1057         if (r)
1058                 log_err(cd, "Error during resuming device %s.\n", name);
1059 out:
1060         crypt_safe_free(passphrase_read);
1061         crypt_free_volume_key(vk);
1062         return r < 0 ? r : keyslot;
1063 }
1064
1065 // slot manipulation
1066 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1067         int keyslot, // -1 any
1068         const char *passphrase, // NULL -> terminal
1069         size_t passphrase_size,
1070         const char *new_passphrase, // NULL -> terminal
1071         size_t new_passphrase_size)
1072 {
1073         struct volume_key *vk = NULL;
1074         char *password = NULL, *new_password = NULL;
1075         size_t passwordLen, new_passwordLen;
1076         int r;
1077
1078         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1079                 "new passphrase %sprovided.",
1080                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1081
1082         if (!isLUKS(cd->type)) {
1083                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1084                 return -EINVAL;
1085         }
1086
1087         r = keyslot_verify_or_find_empty(cd, &keyslot);
1088         if (r)
1089                 return r;
1090
1091         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1092                 /* No slots used, try to use pre-generated key in header */
1093                 if (cd->volume_key) {
1094                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1095                         r = vk ? 0 : -ENOMEM;
1096                 } else {
1097                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1098                         return -EINVAL;
1099                 }
1100         } else if (passphrase) {
1101                 /* Passphrase provided, use it to unlock existing keyslot */
1102                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1103                                            passphrase_size, &cd->hdr, &vk, cd);
1104         } else {
1105                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1106                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1107                                       &password, &passwordLen, 0);
1108                 if (r < 0)
1109                         goto out;
1110
1111                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1112                                            passwordLen, &cd->hdr, &vk, cd);
1113                 crypt_safe_free(password);
1114         }
1115
1116         if(r < 0)
1117                 goto out;
1118
1119         if (new_passphrase) {
1120                 new_password = (char *)new_passphrase;
1121                 new_passwordLen = new_passphrase_size;
1122         } else {
1123                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1124                                       &new_password, &new_passwordLen, 1);
1125                 if(r < 0)
1126                         goto out;
1127         }
1128
1129         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1130                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1131         if(r < 0) goto out;
1132
1133         r = 0;
1134 out:
1135         if (!new_passphrase)
1136                 crypt_safe_free(new_password);
1137         crypt_free_volume_key(vk);
1138         return r ?: keyslot;
1139 }
1140
1141 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1142         int keyslot,
1143         const char *keyfile,
1144         size_t keyfile_size,
1145         const char *new_keyfile,
1146         size_t new_keyfile_size)
1147 {
1148         struct volume_key *vk = NULL;
1149         char *password = NULL; size_t passwordLen;
1150         char *new_password = NULL; size_t new_passwordLen;
1151         int r;
1152
1153         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1154                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1155
1156         if (!isLUKS(cd->type)) {
1157                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1158                 return -EINVAL;
1159         }
1160
1161         r = keyslot_verify_or_find_empty(cd, &keyslot);
1162         if (r)
1163                 return r;
1164
1165         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1166                 /* No slots used, try to use pre-generated key in header */
1167                 if (cd->volume_key) {
1168                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1169                         r = vk ? 0 : -ENOMEM;
1170                 } else {
1171                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1172                         return -EINVAL;
1173                 }
1174         } else {
1175                 /* Read password from file of (if NULL) from terminal */
1176                 if (keyfile)
1177                         r = key_from_file(cd, _("Enter any passphrase: "),
1178                                           &password, &passwordLen,
1179                                           keyfile, keyfile_size);
1180                 else
1181                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1182                                               &password, &passwordLen, 0);
1183                 if (r < 0)
1184                         goto out;
1185
1186                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1187                                            &cd->hdr, &vk, cd);
1188         }
1189
1190         if(r < 0)
1191                 goto out;
1192
1193         if (new_keyfile)
1194                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1195                                   &new_password, &new_passwordLen, new_keyfile,
1196                                   new_keyfile_size);
1197         else
1198                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1199                                       &new_password, &new_passwordLen, 1);
1200         if (r < 0)
1201                 goto out;
1202
1203         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1204                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1205 out:
1206         crypt_safe_free(password);
1207         crypt_safe_free(new_password);
1208         crypt_free_volume_key(vk);
1209         return r < 0 ? r : keyslot;
1210 }
1211
1212 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1213         int keyslot,
1214         const char *volume_key,
1215         size_t volume_key_size,
1216         const char *passphrase,
1217         size_t passphrase_size)
1218 {
1219         struct volume_key *vk = NULL;
1220         int r = -EINVAL;
1221         char *new_password = NULL; size_t new_passwordLen;
1222
1223         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1224
1225         if (!isLUKS(cd->type)) {
1226                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1227                 return -EINVAL;
1228         }
1229
1230         if (volume_key)
1231                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1232         else if (cd->volume_key)
1233                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1234
1235         if (!vk)
1236                 return -ENOMEM;
1237
1238         r = LUKS_verify_volume_key(&cd->hdr, vk);
1239         if (r < 0) {
1240                 log_err(cd, _("Volume key does not match the volume.\n"));
1241                 goto out;
1242         }
1243
1244         r = keyslot_verify_or_find_empty(cd, &keyslot);
1245         if (r)
1246                 goto out;
1247
1248         if (!passphrase) {
1249                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1250                                       &new_password, &new_passwordLen, 1);
1251                 if (r < 0)
1252                         goto out;
1253                 passphrase = new_password;
1254                 passphrase_size = new_passwordLen;
1255         }
1256
1257         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1258                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1259 out:
1260         crypt_safe_free(new_password);
1261         crypt_free_volume_key(vk);
1262         return (r < 0) ? r : keyslot;
1263 }
1264
1265 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1266 {
1267         crypt_keyslot_info ki;
1268
1269         log_dbg("Destroying keyslot %d.", keyslot);
1270
1271         if (!isLUKS(cd->type)) {
1272                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1273                 return -EINVAL;
1274         }
1275
1276         ki = crypt_keyslot_status(cd, keyslot);
1277         if (ki == CRYPT_SLOT_INVALID) {
1278                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1279                 return -EINVAL;
1280         }
1281
1282         if (ki == CRYPT_SLOT_INACTIVE) {
1283                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1284                 return -EINVAL;
1285         }
1286
1287         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1288 }
1289
1290 // activation/deactivation of device mapping
1291 int crypt_activate_by_passphrase(struct crypt_device *cd,
1292         const char *name,
1293         int keyslot,
1294         const char *passphrase,
1295         size_t passphrase_size,
1296         uint32_t flags)
1297 {
1298         crypt_status_info ci;
1299         struct volume_key *vk = NULL;
1300         char *read_passphrase = NULL;
1301         size_t passphraseLen = 0;
1302         int r;
1303
1304         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1305                 name ? "Activating" : "Checking", name ?: "",
1306                 keyslot, passphrase ? "" : "[none] ");
1307
1308         if (name) {
1309                 ci = crypt_status(NULL, name);
1310                 if (ci == CRYPT_INVALID)
1311                         return -EINVAL;
1312                 else if (ci >= CRYPT_ACTIVE) {
1313                         log_err(cd, _("Device %s already exists.\n"), name);
1314                         return -EEXIST;
1315                 }
1316         }
1317
1318         /* plain, use hashed passphrase */
1319         if (isPLAIN(cd->type)) {
1320                 if (!name)
1321                         return -EINVAL;
1322
1323                 if (!passphrase) {
1324                         r = key_from_terminal(cd, NULL, &read_passphrase,
1325                                               &passphraseLen, 0);
1326                         if (r < 0)
1327                                 goto out;
1328                         passphrase = read_passphrase;
1329                         passphrase_size = passphraseLen;
1330                 }
1331
1332                 r = process_key(cd, cd->plain_hdr.hash,
1333                                 cd->volume_key->keylength,
1334                                 passphrase, passphrase_size, &vk);
1335                 if (r < 0)
1336                         goto out;
1337
1338                 r = PLAIN_activate(cd, name, vk,
1339                                    cd->plain_hdr.size,
1340                                    cd->plain_hdr.skip, flags);
1341                 keyslot = 0;
1342         } else if (isLUKS(cd->type)) {
1343                 /* provided passphrase, do not retry */
1344                 if (passphrase) {
1345                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1346                                                    passphrase_size, &cd->hdr, &vk, cd);
1347                 } else
1348                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1349
1350                 if (r >= 0) {
1351                         keyslot = r;
1352                         if (name)
1353                                 r = LUKS1_activate(cd, name, vk, flags);
1354                 }
1355         } else
1356                 r = -EINVAL;
1357 out:
1358         crypt_safe_free(read_passphrase);
1359         crypt_free_volume_key(vk);
1360
1361         return r < 0  ? r : keyslot;
1362 }
1363
1364 int crypt_activate_by_keyfile(struct crypt_device *cd,
1365         const char *name,
1366         int keyslot,
1367         const char *keyfile,
1368         size_t keyfile_size,
1369         uint32_t flags)
1370 {
1371         crypt_status_info ci;
1372         struct volume_key *vk = NULL;
1373         char *passphrase_read = NULL;
1374         size_t passphrase_size_read;
1375         unsigned int key_count = 0;
1376         int r;
1377
1378         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1379                 name ?: "", keyslot, keyfile ?: "[none]");
1380
1381         if (name) {
1382                 ci = crypt_status(NULL, name);
1383                 if (ci == CRYPT_INVALID)
1384                         return -EINVAL;
1385                 else if (ci >= CRYPT_ACTIVE) {
1386                         log_err(cd, _("Device %s already exists.\n"), name);
1387                         return -EEXIST;
1388                 }
1389         }
1390
1391         if (!keyfile)
1392                 return -EINVAL;
1393
1394         if (isPLAIN(cd->type)) {
1395                 if (!name)
1396                         return -EINVAL;
1397
1398                 r = key_from_file(cd, _("Enter passphrase: "),
1399                                   &passphrase_read, &passphrase_size_read,
1400                                   keyfile, keyfile_size);
1401                 if (r < 0)
1402                         goto out;
1403
1404                 r = process_key(cd, cd->plain_hdr.hash,
1405                                 cd->volume_key->keylength,
1406                                 passphrase_read, passphrase_size_read, &vk);
1407                 if (r < 0)
1408                         goto out;
1409
1410                 r = PLAIN_activate(cd, name, vk,
1411                                    cd->plain_hdr.size,
1412                                    cd->plain_hdr.skip, flags);
1413         } else if (isLUKS(cd->type)) {
1414                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1415                           &passphrase_size_read, keyfile, keyfile_size);
1416                 if (r < 0)
1417                         goto out;
1418                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1419                                            passphrase_size_read, &cd->hdr, &vk, cd);
1420                 if (r < 0)
1421                         goto out;
1422                 keyslot = r;
1423
1424                 if (name) {
1425                         r = LUKS1_activate(cd, name, vk, flags);
1426                         if (r < 0)
1427                                 goto out;
1428                 }
1429                 r = keyslot;
1430         } else if (isLOOPAES(cd->type)) {
1431                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1432                                   keyfile, keyfile_size);
1433                 if (r < 0)
1434                         goto out;
1435                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1436                                           passphrase_read, passphrase_size_read);
1437                 if (r < 0)
1438                         goto out;
1439                 if (name)
1440                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1441                                              key_count, vk,
1442                                              cd->loopaes_hdr.skip,
1443                                              flags);
1444         } else
1445                 r = -EINVAL;
1446
1447 out:
1448         crypt_safe_free(passphrase_read);
1449         crypt_free_volume_key(vk);
1450
1451         return r;
1452 }
1453
1454 int crypt_activate_by_volume_key(struct crypt_device *cd,
1455         const char *name,
1456         const char *volume_key,
1457         size_t volume_key_size,
1458         uint32_t flags)
1459 {
1460         crypt_status_info ci;
1461         struct volume_key *vk = NULL;
1462         int r = -EINVAL;
1463
1464         log_dbg("Activating volume %s by volume key.", name);
1465
1466         if (name) {
1467                 ci = crypt_status(NULL, name);
1468                 if (ci == CRYPT_INVALID)
1469                         return -EINVAL;
1470                 else if (ci >= CRYPT_ACTIVE) {
1471                         log_err(cd, _("Device %s already exists.\n"), name);
1472                         return -EEXIST;
1473                 }
1474         }
1475
1476         /* use key directly, no hash */
1477         if (isPLAIN(cd->type)) {
1478                 if (!name)
1479                         return -EINVAL;
1480
1481                 if (!volume_key || !volume_key_size || !cd->volume_key ||
1482                         volume_key_size != cd->volume_key->keylength) {
1483                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
1484                         return -EINVAL;
1485                 }
1486
1487                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1488                 if (!vk)
1489                         return -ENOMEM;
1490
1491                 r = PLAIN_activate(cd, name, vk,
1492                                    cd->plain_hdr.size,
1493                                    cd->plain_hdr.skip, flags);
1494         } else if (isLUKS(cd->type)) {
1495                 /* If key is not provided, try to use internal key */
1496                 if (!volume_key) {
1497                         if (!cd->volume_key) {
1498                                 log_err(cd, _("Volume key does not match the volume.\n"));
1499                                 return -EINVAL;
1500                         }
1501                         volume_key_size = cd->volume_key->keylength;
1502                         volume_key = cd->volume_key->key;
1503                 }
1504
1505                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1506                 if (!vk)
1507                         return -ENOMEM;
1508                 r = LUKS_verify_volume_key(&cd->hdr, vk);
1509
1510                 if (r == -EPERM)
1511                         log_err(cd, _("Volume key does not match the volume.\n"));
1512
1513                 if (!r && name)
1514                         r = LUKS1_activate(cd, name, vk, flags);
1515         } else
1516                 log_err(cd, _("Device type is not properly initialised.\n"));
1517
1518         crypt_free_volume_key(vk);
1519
1520         return r;
1521 }
1522
1523 int crypt_deactivate(struct crypt_device *cd, const char *name)
1524 {
1525         int r;
1526
1527         if (!name)
1528                 return -EINVAL;
1529
1530         log_dbg("Deactivating volume %s.", name);
1531
1532         if (!cd && dm_init(NULL, 1) < 0)
1533                 return -ENOSYS;
1534
1535         switch (crypt_status(cd, name)) {
1536                 case CRYPT_ACTIVE:
1537                         r = dm_remove_device(name, 0, 0);
1538                         break;
1539                 case CRYPT_BUSY:
1540                         log_err(cd, _("Device %s is busy.\n"), name);
1541                         r = -EBUSY;
1542                         break;
1543                 case CRYPT_INACTIVE:
1544                         log_err(cd, _("Device %s is not active.\n"), name);
1545                         r = -ENODEV;
1546                         break;
1547                 default:
1548                         log_err(cd, _("Invalid device %s.\n"), name);
1549                         r = -EINVAL;
1550         }
1551
1552         if (!cd)
1553                 dm_exit();
1554
1555         return r;
1556 }
1557
1558 int crypt_volume_key_get(struct crypt_device *cd,
1559         int keyslot,
1560         char *volume_key,
1561         size_t *volume_key_size,
1562         const char *passphrase,
1563         size_t passphrase_size)
1564 {
1565         struct volume_key *vk = NULL;
1566         unsigned key_len;
1567         int r = -EINVAL;
1568
1569         key_len = crypt_get_volume_key_size(cd);
1570         if (key_len > *volume_key_size) {
1571                 log_err(cd, _("Volume key buffer too small.\n"));
1572                 return -ENOMEM;
1573         }
1574
1575         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
1576                 r = process_key(cd, cd->plain_hdr.hash, key_len,
1577                                 passphrase, passphrase_size, &vk);
1578                 if (r < 0)
1579                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
1580         } else if (isLUKS(cd->type)) {
1581                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1582                                         passphrase_size, &cd->hdr, &vk, cd);
1583
1584         } else
1585                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
1586
1587         if (r >= 0) {
1588                 memcpy(volume_key, vk->key, vk->keylength);
1589                 *volume_key_size = vk->keylength;
1590         }
1591
1592         crypt_free_volume_key(vk);
1593         return r;
1594 }
1595
1596 int crypt_volume_key_verify(struct crypt_device *cd,
1597         const char *volume_key,
1598         size_t volume_key_size)
1599 {
1600         struct volume_key *vk;
1601         int r;
1602
1603         if (!isLUKS(cd->type)) {
1604                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1605                 return -EINVAL;
1606         }
1607
1608         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1609         if (!vk)
1610                 return -ENOMEM;
1611
1612         r = LUKS_verify_volume_key(&cd->hdr, vk);
1613
1614         if (r == -EPERM)
1615                 log_err(cd, _("Volume key does not match the volume.\n"));
1616
1617         crypt_free_volume_key(vk);
1618
1619         return r;
1620 }
1621
1622 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
1623 {
1624         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
1625         cd->timeout = timeout_sec;
1626 }
1627
1628 void crypt_set_password_retry(struct crypt_device *cd, int tries)
1629 {
1630         log_dbg("Password retry count set to %d.", tries);
1631         cd->tries = tries;
1632 }
1633
1634 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
1635 {
1636         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
1637         cd->iteration_time = iteration_time_ms;
1638 }
1639
1640 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
1641 {
1642         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
1643         cd->password_verify = password_verify ? 1 : 0;
1644 }
1645
1646 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
1647 {
1648         switch (rng_type) {
1649         case CRYPT_RNG_URANDOM:
1650         case CRYPT_RNG_RANDOM:
1651                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
1652                 cd->rng_type = rng_type;
1653         }
1654 }
1655
1656 int crypt_get_rng_type(struct crypt_device *cd)
1657 {
1658         if (!cd)
1659                 return -EINVAL;
1660
1661         return cd->rng_type;
1662 }
1663
1664 int crypt_memory_lock(struct crypt_device *cd, int lock)
1665 {
1666         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
1667 }
1668
1669 // reporting
1670 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
1671 {
1672         int r;
1673
1674         if (!cd && dm_init(NULL, 1) < 0)
1675                 return CRYPT_INVALID;
1676
1677         r = dm_status_device(name);
1678
1679         if (!cd)
1680                 dm_exit();
1681
1682         if (r < 0 && r != -ENODEV)
1683                 return CRYPT_INVALID;
1684
1685         if (r == 0)
1686                 return CRYPT_ACTIVE;
1687
1688         if (r > 0)
1689                 return CRYPT_BUSY;
1690
1691         return CRYPT_INACTIVE;
1692 }
1693
1694 static void hexprintICB(struct crypt_device *cd, char *d, int n)
1695 {
1696         int i;
1697         for(i = 0; i < n; i++)
1698                 log_std(cd, "%02hhx ", (char)d[i]);
1699 }
1700
1701 int crypt_dump(struct crypt_device *cd)
1702 {
1703         int i;
1704         if (!isLUKS(cd->type)) { //FIXME
1705                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1706                 return -EINVAL;
1707         }
1708
1709         log_std(cd, "LUKS header information for %s\n\n", cd->device);
1710         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
1711         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
1712         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
1713         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
1714         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
1715         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
1716         log_std(cd, "MK digest:     \t");
1717         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
1718         log_std(cd, "\n");
1719         log_std(cd, "MK salt:       \t");
1720         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
1721         log_std(cd, "\n               \t");
1722         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1723         log_std(cd, "\n");
1724         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
1725         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
1726         for(i = 0; i < LUKS_NUMKEYS; i++) {
1727                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
1728                         log_std(cd, "Key Slot %d: ENABLED\n",i);
1729                         log_std(cd, "\tIterations:         \t%d\n",
1730                                 cd->hdr.keyblock[i].passwordIterations);
1731                         log_std(cd, "\tSalt:               \t");
1732                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
1733                                     LUKS_SALTSIZE/2);
1734                         log_std(cd, "\n\t                      \t");
1735                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
1736                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1737                         log_std(cd, "\n");
1738
1739                         log_std(cd, "\tKey material offset:\t%d\n",
1740                                 cd->hdr.keyblock[i].keyMaterialOffset);
1741                         log_std(cd, "\tAF stripes:            \t%d\n",
1742                                 cd->hdr.keyblock[i].stripes);
1743                 }
1744                 else 
1745                         log_std(cd, "Key Slot %d: DISABLED\n", i);
1746         }
1747
1748         return 0;
1749 }
1750
1751 const char *crypt_get_cipher(struct crypt_device *cd)
1752 {
1753         if (isPLAIN(cd->type))
1754                 return cd->plain_cipher;
1755
1756         if (isLUKS(cd->type))
1757                 return cd->hdr.cipherName;
1758
1759         if (isLOOPAES(cd->type))
1760                 return cd->loopaes_cipher;
1761
1762         return NULL;
1763 }
1764
1765 const char *crypt_get_cipher_mode(struct crypt_device *cd)
1766 {
1767         if (isPLAIN(cd->type))
1768                 return cd->plain_cipher_mode;
1769
1770         if (isLUKS(cd->type))
1771                 return cd->hdr.cipherMode;
1772
1773         if (isLOOPAES(cd->type))
1774                 return cd->loopaes_cipher_mode;
1775
1776         return NULL;
1777 }
1778
1779 const char *crypt_get_uuid(struct crypt_device *cd)
1780 {
1781         if (isLUKS(cd->type))
1782                 return cd->hdr.uuid;
1783
1784         if (isPLAIN(cd->type))
1785                 return cd->plain_uuid;
1786
1787         if (isLOOPAES(cd->type))
1788                 return cd->loopaes_uuid;
1789
1790         return NULL;
1791 }
1792
1793 const char *crypt_get_device_name(struct crypt_device *cd)
1794 {
1795         return cd->device;
1796 }
1797
1798 int crypt_get_volume_key_size(struct crypt_device *cd)
1799 {
1800         if (isPLAIN(cd->type) && cd->volume_key)
1801                 return cd->volume_key->keylength;
1802
1803         if (isLUKS(cd->type))
1804                 return cd->hdr.keyBytes;
1805
1806         if (isLOOPAES(cd->type))
1807                 return cd->loopaes_key_size;
1808
1809         return 0;
1810 }
1811
1812 uint64_t crypt_get_data_offset(struct crypt_device *cd)
1813 {
1814         if (isPLAIN(cd->type))
1815                 return cd->plain_hdr.offset;
1816
1817         if (isLUKS(cd->type))
1818                 return cd->hdr.payloadOffset;
1819
1820         if (isLOOPAES(cd->type))
1821                 return cd->loopaes_hdr.offset;
1822
1823         return 0;
1824 }
1825
1826 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
1827 {
1828         if (!isLUKS(cd->type)) {
1829                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1830                 return CRYPT_SLOT_INVALID;
1831         }
1832
1833         return LUKS_keyslot_info(&cd->hdr, keyslot);
1834 }
1835
1836 int crypt_keyslot_max(const char *type)
1837 {
1838         if (type && isLUKS(type))
1839                 return LUKS_NUMKEYS;
1840
1841         return -EINVAL;
1842 }
1843
1844 const char *crypt_get_type(struct crypt_device *cd)
1845 {
1846         return cd->type;
1847 }
1848
1849 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
1850                             const char *name,
1851                             struct crypt_active_device *cad)
1852 {
1853         struct crypt_dm_active_device dmd;
1854         int r;
1855
1856         r = dm_query_device(name, 0, &dmd);
1857         if (r < 0)
1858                 return r;
1859
1860         cad->offset     = dmd.offset;
1861         cad->iv_offset  = dmd.iv_offset;
1862         cad->size       = dmd.size;
1863         cad->flags      = dmd.flags;
1864
1865         return 0;
1866 }