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