LUKS header and Type needs to be set in context before crypt_check_data_device_size...
[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         if (!cd->type && !(cd->type = strdup(CRYPT_LUKS1)))
917                 return -ENOMEM;
918
919         memcpy(&cd->hdr, &hdr, sizeof(hdr));
920
921         /* cd->type and header must be set in context */
922         r = crypt_check_data_device_size(cd);
923         if (r < 0) {
924                 free(cd->type);
925                 cd->type = NULL;
926         }
927
928         return r;
929 }
930
931 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
932 {
933         struct crypt_dm_active_device dmd;
934         int r;
935
936         /* Device context type must be initialised */
937         if (!cd->type || !crypt_get_uuid(cd))
938                 return -EINVAL;
939
940         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
941
942         r = dm_query_device(name, DM_ACTIVE_DEVICE | DM_ACTIVE_CIPHER |
943                                   DM_ACTIVE_UUID | DM_ACTIVE_KEYSIZE |
944                                   DM_ACTIVE_KEY, &dmd);
945         if (r < 0) {
946                 log_err(NULL, _("Device %s is not active.\n"), name);
947                 goto out;
948         }
949
950         if (!dmd.uuid) {
951                 r = -EINVAL;
952                 goto out;
953         }
954
955         r = device_check_and_adjust(cd, dmd.device, DEV_OK, &new_size, &dmd.offset, &dmd.flags);
956         if (r)
957                 goto out;
958
959         if (new_size == dmd.size) {
960                 log_dbg("Device has already requested size %" PRIu64
961                         " sectors.", dmd.size);
962                 r = 0;
963         } else {
964                 dmd.size = new_size;
965                 r = dm_create_device(name, cd->type, &dmd, 1);
966         }
967 out:
968         crypt_free_volume_key(dmd.vk);
969         free(CONST_CAST(void*)dmd.cipher);
970         free(CONST_CAST(void*)dmd.device);
971         free(CONST_CAST(void*)dmd.uuid);
972
973         return r;
974 }
975
976 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
977 {
978         if (!isLUKS(cd->type)) {
979                 log_err(cd, _("This operation is not supported for this device type.\n"));
980                 return  -EINVAL;
981         }
982
983         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
984                 log_dbg("UUID is the same as requested (%s) for device %s.",
985                         uuid, mdata_device(cd));
986                 return 0;
987         }
988
989         if (uuid)
990                 log_dbg("Requested new UUID change to %s for %s.", uuid, mdata_device(cd));
991         else
992                 log_dbg("Requested new UUID refresh for %s.", mdata_device(cd));
993
994         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
995                 return -EPERM;
996
997         return LUKS_hdr_uuid_set(mdata_device(cd), &cd->hdr, uuid, cd);
998 }
999
1000 int crypt_header_backup(struct crypt_device *cd,
1001                         const char *requested_type,
1002                         const char *backup_file)
1003 {
1004         int r;
1005
1006         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1007                 return -EINVAL;
1008
1009         r = init_crypto(cd);
1010         if (r < 0)
1011                 return r;
1012
1013         log_dbg("Requested header backup of device %s (%s) to "
1014                 "file %s.", mdata_device(cd), requested_type, backup_file);
1015
1016         return LUKS_hdr_backup(backup_file, mdata_device(cd), &cd->hdr, cd);
1017 }
1018
1019 int crypt_header_restore(struct crypt_device *cd,
1020                          const char *requested_type,
1021                          const char *backup_file)
1022 {
1023         int r;
1024
1025         if (requested_type && !isLUKS(requested_type))
1026                 return -EINVAL;
1027
1028         /* Some hash functions need initialized gcrypt library */
1029         r = init_crypto(cd);
1030         if (r < 0)
1031                 return r;
1032
1033         log_dbg("Requested header restore to device %s (%s) from "
1034                 "file %s.", mdata_device(cd), requested_type, backup_file);
1035
1036         return LUKS_hdr_restore(backup_file, mdata_device(cd), &cd->hdr, cd);
1037 }
1038
1039 void crypt_free(struct crypt_device *cd)
1040 {
1041         if (cd) {
1042                 log_dbg("Releasing crypt device %s context.", mdata_device(cd));
1043
1044                 if (cd->loop_fd != -1)
1045                         close(cd->loop_fd);
1046
1047                 dm_exit();
1048                 crypt_free_volume_key(cd->volume_key);
1049
1050                 free(cd->device);
1051                 free(cd->metadata_device);
1052                 free(cd->backing_file);
1053                 free(cd->type);
1054
1055                 /* used in plain device only */
1056                 free(CONST_CAST(void*)cd->plain_hdr.hash);
1057                 free(cd->plain_cipher);
1058                 free(cd->plain_cipher_mode);
1059                 free(cd->plain_uuid);
1060
1061                 /* used in loop-AES device only */
1062                 free(CONST_CAST(void*)cd->loopaes_hdr.hash);
1063                 free(cd->loopaes_cipher);
1064                 free(cd->loopaes_uuid);
1065
1066                 free(cd);
1067         }
1068 }
1069
1070 int crypt_suspend(struct crypt_device *cd,
1071                   const char *name)
1072 {
1073         crypt_status_info ci;
1074         int r;
1075
1076         log_dbg("Suspending volume %s.", name);
1077
1078         if (!isLUKS(cd->type)) {
1079                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1080                 r = -EINVAL;
1081                 goto out;
1082         }
1083
1084         ci = crypt_status(NULL, name);
1085         if (ci < CRYPT_ACTIVE) {
1086                 log_err(cd, _("Volume %s is not active.\n"), name);
1087                 return -EINVAL;
1088         }
1089
1090         if (!cd && dm_init(NULL, 1) < 0)
1091                 return -ENOSYS;
1092
1093         r = dm_status_suspended(name);
1094         if (r < 0)
1095                 goto out;
1096
1097         if (r) {
1098                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1099                 r = -EINVAL;
1100                 goto out;
1101         }
1102
1103         r = dm_suspend_and_wipe_key(name);
1104         if (r == -ENOTSUP)
1105                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1106         else if (r)
1107                 log_err(cd, "Error during suspending device %s.\n", name);
1108 out:
1109         if (!cd)
1110                 dm_exit();
1111         return r;
1112 }
1113
1114 int crypt_resume_by_passphrase(struct crypt_device *cd,
1115                                const char *name,
1116                                int keyslot,
1117                                const char *passphrase,
1118                                size_t passphrase_size)
1119 {
1120         struct volume_key *vk = NULL;
1121         int r;
1122
1123         log_dbg("Resuming volume %s.", name);
1124
1125         if (!isLUKS(cd->type)) {
1126                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1127                 r = -EINVAL;
1128                 goto out;
1129         }
1130
1131         r = dm_status_suspended(name);
1132         if (r < 0)
1133                 return r;
1134
1135         if (!r) {
1136                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1137                 return -EINVAL;
1138         }
1139
1140         if (passphrase) {
1141                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1142                                            passphrase_size, &cd->hdr, &vk, cd);
1143         } else
1144                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1145
1146         if (r >= 0) {
1147                 keyslot = r;
1148                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1149                 if (r == -ENOTSUP)
1150                         log_err(cd, "Resume is not supported for device %s.\n", name);
1151                 else if (r)
1152                         log_err(cd, "Error during resuming device %s.\n", name);
1153         } else
1154                 r = keyslot;
1155 out:
1156         crypt_free_volume_key(vk);
1157         return r < 0 ? r : keyslot;
1158 }
1159
1160 int crypt_resume_by_keyfile(struct crypt_device *cd,
1161                             const char *name,
1162                             int keyslot,
1163                             const char *keyfile,
1164                             size_t keyfile_size)
1165 {
1166         struct volume_key *vk = NULL;
1167         char *passphrase_read = NULL;
1168         size_t passphrase_size_read;
1169         int r;
1170
1171         log_dbg("Resuming volume %s.", name);
1172
1173         if (!isLUKS(cd->type)) {
1174                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1175                 r = -EINVAL;
1176                 goto out;
1177         }
1178
1179         r = dm_status_suspended(name);
1180         if (r < 0)
1181                 return r;
1182
1183         if (!r) {
1184                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1185                 return -EINVAL;
1186         }
1187
1188         if (!keyfile)
1189                 return -EINVAL;
1190
1191         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1192                           &passphrase_size_read, keyfile, keyfile_size);
1193         if (r < 0)
1194                 goto out;
1195
1196         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1197                                    passphrase_size_read, &cd->hdr, &vk, cd);
1198         if (r < 0)
1199                 goto out;
1200
1201         keyslot = r;
1202         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1203         if (r)
1204                 log_err(cd, "Error during resuming device %s.\n", name);
1205 out:
1206         crypt_safe_free(passphrase_read);
1207         crypt_free_volume_key(vk);
1208         return r < 0 ? r : keyslot;
1209 }
1210
1211 // slot manipulation
1212 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1213         int keyslot, // -1 any
1214         const char *passphrase, // NULL -> terminal
1215         size_t passphrase_size,
1216         const char *new_passphrase, // NULL -> terminal
1217         size_t new_passphrase_size)
1218 {
1219         struct volume_key *vk = NULL;
1220         char *password = NULL, *new_password = NULL;
1221         size_t passwordLen, new_passwordLen;
1222         int r;
1223
1224         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1225                 "new passphrase %sprovided.",
1226                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1227
1228         if (!isLUKS(cd->type)) {
1229                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1230                 return -EINVAL;
1231         }
1232
1233         r = keyslot_verify_or_find_empty(cd, &keyslot);
1234         if (r)
1235                 return r;
1236
1237         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1238                 /* No slots used, try to use pre-generated key in header */
1239                 if (cd->volume_key) {
1240                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1241                         r = vk ? 0 : -ENOMEM;
1242                 } else {
1243                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1244                         return -EINVAL;
1245                 }
1246         } else if (passphrase) {
1247                 /* Passphrase provided, use it to unlock existing keyslot */
1248                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, passphrase,
1249                                            passphrase_size, &cd->hdr, &vk, cd);
1250         } else {
1251                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1252                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1253                                       &password, &passwordLen, 0);
1254                 if (r < 0)
1255                         goto out;
1256
1257                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password,
1258                                            passwordLen, &cd->hdr, &vk, cd);
1259                 crypt_safe_free(password);
1260         }
1261
1262         if(r < 0)
1263                 goto out;
1264
1265         if (new_passphrase) {
1266                 new_password = CONST_CAST(char*)new_passphrase;
1267                 new_passwordLen = new_passphrase_size;
1268         } else {
1269                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1270                                       &new_password, &new_passwordLen, 1);
1271                 if(r < 0)
1272                         goto out;
1273         }
1274
1275         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1276                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1277         if(r < 0) goto out;
1278
1279         r = 0;
1280 out:
1281         if (!new_passphrase)
1282                 crypt_safe_free(new_password);
1283         crypt_free_volume_key(vk);
1284         return r ?: keyslot;
1285 }
1286
1287 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1288         int keyslot,
1289         const char *keyfile,
1290         size_t keyfile_size,
1291         const char *new_keyfile,
1292         size_t new_keyfile_size)
1293 {
1294         struct volume_key *vk = NULL;
1295         char *password = NULL; size_t passwordLen;
1296         char *new_password = NULL; size_t new_passwordLen;
1297         int r;
1298
1299         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1300                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1301
1302         if (!isLUKS(cd->type)) {
1303                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1304                 return -EINVAL;
1305         }
1306
1307         r = keyslot_verify_or_find_empty(cd, &keyslot);
1308         if (r)
1309                 return r;
1310
1311         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1312                 /* No slots used, try to use pre-generated key in header */
1313                 if (cd->volume_key) {
1314                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1315                         r = vk ? 0 : -ENOMEM;
1316                 } else {
1317                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1318                         return -EINVAL;
1319                 }
1320         } else {
1321                 /* Read password from file of (if NULL) from terminal */
1322                 if (keyfile)
1323                         r = key_from_file(cd, _("Enter any passphrase: "),
1324                                           &password, &passwordLen,
1325                                           keyfile, keyfile_size);
1326                 else
1327                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1328                                               &password, &passwordLen, 0);
1329                 if (r < 0)
1330                         goto out;
1331
1332                 r = LUKS_open_key_with_hdr(mdata_device(cd), CRYPT_ANY_SLOT, password, passwordLen,
1333                                            &cd->hdr, &vk, cd);
1334         }
1335
1336         if(r < 0)
1337                 goto out;
1338
1339         if (new_keyfile)
1340                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1341                                   &new_password, &new_passwordLen, new_keyfile,
1342                                   new_keyfile_size);
1343         else
1344                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1345                                       &new_password, &new_passwordLen, 1);
1346         if (r < 0)
1347                 goto out;
1348
1349         r = LUKS_set_key(mdata_device(cd), keyslot, new_password, new_passwordLen,
1350                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1351 out:
1352         crypt_safe_free(password);
1353         crypt_safe_free(new_password);
1354         crypt_free_volume_key(vk);
1355         return r < 0 ? r : keyslot;
1356 }
1357
1358 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1359         int keyslot,
1360         const char *volume_key,
1361         size_t volume_key_size,
1362         const char *passphrase,
1363         size_t passphrase_size)
1364 {
1365         struct volume_key *vk = NULL;
1366         int r = -EINVAL;
1367         char *new_password = NULL; size_t new_passwordLen;
1368
1369         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1370
1371         if (!isLUKS(cd->type)) {
1372                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1373                 return -EINVAL;
1374         }
1375
1376         if (volume_key)
1377                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1378         else if (cd->volume_key)
1379                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1380
1381         if (!vk)
1382                 return -ENOMEM;
1383
1384         r = LUKS_verify_volume_key(&cd->hdr, vk);
1385         if (r < 0) {
1386                 log_err(cd, _("Volume key does not match the volume.\n"));
1387                 goto out;
1388         }
1389
1390         r = keyslot_verify_or_find_empty(cd, &keyslot);
1391         if (r)
1392                 goto out;
1393
1394         if (!passphrase) {
1395                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1396                                       &new_password, &new_passwordLen, 1);
1397                 if (r < 0)
1398                         goto out;
1399                 passphrase = new_password;
1400                 passphrase_size = new_passwordLen;
1401         }
1402
1403         r = LUKS_set_key(mdata_device(cd), keyslot, passphrase, passphrase_size,
1404                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1405 out:
1406         crypt_safe_free(new_password);
1407         crypt_free_volume_key(vk);
1408         return (r < 0) ? r : keyslot;
1409 }
1410
1411 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1412 {
1413         crypt_keyslot_info ki;
1414
1415         log_dbg("Destroying keyslot %d.", keyslot);
1416
1417         if (!isLUKS(cd->type)) {
1418                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1419                 return -EINVAL;
1420         }
1421
1422         ki = crypt_keyslot_status(cd, keyslot);
1423         if (ki == CRYPT_SLOT_INVALID) {
1424                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1425                 return -EINVAL;
1426         }
1427
1428         if (ki == CRYPT_SLOT_INACTIVE) {
1429                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1430                 return -EINVAL;
1431         }
1432
1433         return LUKS_del_key(mdata_device(cd), keyslot, &cd->hdr, cd);
1434 }
1435
1436 // activation/deactivation of device mapping
1437 int crypt_activate_by_passphrase(struct crypt_device *cd,
1438         const char *name,
1439         int keyslot,
1440         const char *passphrase,
1441         size_t passphrase_size,
1442         uint32_t flags)
1443 {
1444         crypt_status_info ci;
1445         struct volume_key *vk = NULL;
1446         char *read_passphrase = NULL;
1447         size_t passphraseLen = 0;
1448         int r;
1449
1450         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1451                 name ? "Activating" : "Checking", name ?: "",
1452                 keyslot, passphrase ? "" : "[none] ");
1453
1454         if (name) {
1455                 ci = crypt_status(NULL, name);
1456                 if (ci == CRYPT_INVALID)
1457                         return -EINVAL;
1458                 else if (ci >= CRYPT_ACTIVE) {
1459                         log_err(cd, _("Device %s already exists.\n"), name);
1460                         return -EEXIST;
1461                 }
1462         }
1463
1464         /* plain, use hashed passphrase */
1465         if (isPLAIN(cd->type)) {
1466                 if (!name)
1467                         return -EINVAL;
1468
1469                 if (!passphrase) {
1470                         r = key_from_terminal(cd, NULL, &read_passphrase,
1471                                               &passphraseLen, 0);
1472                         if (r < 0)
1473                                 goto out;
1474                         passphrase = read_passphrase;
1475                         passphrase_size = passphraseLen;
1476                 }
1477
1478                 r = process_key(cd, cd->plain_hdr.hash,
1479                                 cd->volume_key->keylength,
1480                                 passphrase, passphrase_size, &vk);
1481                 if (r < 0)
1482                         goto out;
1483
1484                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1485                 keyslot = 0;
1486         } else if (isLUKS(cd->type)) {
1487                 /* provided passphrase, do not retry */
1488                 if (passphrase) {
1489                         r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1490                                                    passphrase_size, &cd->hdr, &vk, cd);
1491                 } else
1492                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1493
1494                 if (r >= 0) {
1495                         keyslot = r;
1496                         if (name)
1497                                 r = LUKS1_activate(cd, name, vk, flags);
1498                 }
1499         } else
1500                 r = -EINVAL;
1501 out:
1502         crypt_safe_free(read_passphrase);
1503         crypt_free_volume_key(vk);
1504
1505         return r < 0  ? r : keyslot;
1506 }
1507
1508 int crypt_activate_by_keyfile(struct crypt_device *cd,
1509         const char *name,
1510         int keyslot,
1511         const char *keyfile,
1512         size_t keyfile_size,
1513         uint32_t flags)
1514 {
1515         crypt_status_info ci;
1516         struct volume_key *vk = NULL;
1517         char *passphrase_read = NULL;
1518         size_t passphrase_size_read;
1519         unsigned int key_count = 0;
1520         int r;
1521
1522         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1523                 name ?: "", keyslot, keyfile ?: "[none]");
1524
1525         if (name) {
1526                 ci = crypt_status(NULL, name);
1527                 if (ci == CRYPT_INVALID)
1528                         return -EINVAL;
1529                 else if (ci >= CRYPT_ACTIVE) {
1530                         log_err(cd, _("Device %s already exists.\n"), name);
1531                         return -EEXIST;
1532                 }
1533         }
1534
1535         if (!keyfile)
1536                 return -EINVAL;
1537
1538         if (isPLAIN(cd->type)) {
1539                 if (!name)
1540                         return -EINVAL;
1541
1542                 r = key_from_file(cd, _("Enter passphrase: "),
1543                                   &passphrase_read, &passphrase_size_read,
1544                                   keyfile, keyfile_size);
1545                 if (r < 0)
1546                         goto out;
1547
1548                 r = process_key(cd, cd->plain_hdr.hash,
1549                                 cd->volume_key->keylength,
1550                                 passphrase_read, passphrase_size_read, &vk);
1551                 if (r < 0)
1552                         goto out;
1553
1554                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1555         } else if (isLUKS(cd->type)) {
1556                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1557                           &passphrase_size_read, keyfile, keyfile_size);
1558                 if (r < 0)
1559                         goto out;
1560                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase_read,
1561                                            passphrase_size_read, &cd->hdr, &vk, cd);
1562                 if (r < 0)
1563                         goto out;
1564                 keyslot = r;
1565
1566                 if (name) {
1567                         r = LUKS1_activate(cd, name, vk, flags);
1568                         if (r < 0)
1569                                 goto out;
1570                 }
1571                 r = keyslot;
1572         } else if (isLOOPAES(cd->type)) {
1573                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
1574                                   keyfile, keyfile_size);
1575                 if (r < 0)
1576                         goto out;
1577                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
1578                                           passphrase_read, passphrase_size_read);
1579                 if (r < 0)
1580                         goto out;
1581                 if (name)
1582                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
1583                                              key_count, vk, flags);
1584         } else
1585                 r = -EINVAL;
1586
1587 out:
1588         crypt_safe_free(passphrase_read);
1589         crypt_free_volume_key(vk);
1590
1591         return r;
1592 }
1593
1594 int crypt_activate_by_volume_key(struct crypt_device *cd,
1595         const char *name,
1596         const char *volume_key,
1597         size_t volume_key_size,
1598         uint32_t flags)
1599 {
1600         crypt_status_info ci;
1601         struct volume_key *vk = NULL;
1602         int r = -EINVAL;
1603
1604         log_dbg("Activating volume %s by volume key.", name);
1605
1606         if (name) {
1607                 ci = crypt_status(NULL, name);
1608                 if (ci == CRYPT_INVALID)
1609                         return -EINVAL;
1610                 else if (ci >= CRYPT_ACTIVE) {
1611                         log_err(cd, _("Device %s already exists.\n"), name);
1612                         return -EEXIST;
1613                 }
1614         }
1615
1616         /* use key directly, no hash */
1617         if (isPLAIN(cd->type)) {
1618                 if (!name)
1619                         return -EINVAL;
1620
1621                 if (!volume_key || !volume_key_size || !cd->volume_key ||
1622                         volume_key_size != cd->volume_key->keylength) {
1623                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
1624                         return -EINVAL;
1625                 }
1626
1627                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1628                 if (!vk)
1629                         return -ENOMEM;
1630
1631                 r = PLAIN_activate(cd, name, vk, cd->plain_hdr.size, flags);
1632         } else if (isLUKS(cd->type)) {
1633                 /* If key is not provided, try to use internal key */
1634                 if (!volume_key) {
1635                         if (!cd->volume_key) {
1636                                 log_err(cd, _("Volume key does not match the volume.\n"));
1637                                 return -EINVAL;
1638                         }
1639                         volume_key_size = cd->volume_key->keylength;
1640                         volume_key = cd->volume_key->key;
1641                 }
1642
1643                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1644                 if (!vk)
1645                         return -ENOMEM;
1646                 r = LUKS_verify_volume_key(&cd->hdr, vk);
1647
1648                 if (r == -EPERM)
1649                         log_err(cd, _("Volume key does not match the volume.\n"));
1650
1651                 if (!r && name)
1652                         r = LUKS1_activate(cd, name, vk, flags);
1653         } else
1654                 log_err(cd, _("Device type is not properly initialised.\n"));
1655
1656         crypt_free_volume_key(vk);
1657
1658         return r;
1659 }
1660
1661 int crypt_deactivate(struct crypt_device *cd, const char *name)
1662 {
1663         int r;
1664
1665         if (!name)
1666                 return -EINVAL;
1667
1668         log_dbg("Deactivating volume %s.", name);
1669
1670         if (!cd && dm_init(NULL, 1) < 0)
1671                 return -ENOSYS;
1672
1673         switch (crypt_status(cd, name)) {
1674                 case CRYPT_ACTIVE:
1675                         r = dm_remove_device(name, 0, 0);
1676                         break;
1677                 case CRYPT_BUSY:
1678                         log_err(cd, _("Device %s is busy.\n"), name);
1679                         r = -EBUSY;
1680                         break;
1681                 case CRYPT_INACTIVE:
1682                         log_err(cd, _("Device %s is not active.\n"), name);
1683                         r = -ENODEV;
1684                         break;
1685                 default:
1686                         log_err(cd, _("Invalid device %s.\n"), name);
1687                         r = -EINVAL;
1688         }
1689
1690         if (!cd)
1691                 dm_exit();
1692
1693         return r;
1694 }
1695
1696 int crypt_volume_key_get(struct crypt_device *cd,
1697         int keyslot,
1698         char *volume_key,
1699         size_t *volume_key_size,
1700         const char *passphrase,
1701         size_t passphrase_size)
1702 {
1703         struct volume_key *vk = NULL;
1704         unsigned key_len;
1705         int r = -EINVAL;
1706
1707         key_len = crypt_get_volume_key_size(cd);
1708         if (key_len > *volume_key_size) {
1709                 log_err(cd, _("Volume key buffer too small.\n"));
1710                 return -ENOMEM;
1711         }
1712
1713         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
1714                 r = process_key(cd, cd->plain_hdr.hash, key_len,
1715                                 passphrase, passphrase_size, &vk);
1716                 if (r < 0)
1717                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
1718         } else if (isLUKS(cd->type)) {
1719                 r = LUKS_open_key_with_hdr(mdata_device(cd), keyslot, passphrase,
1720                                         passphrase_size, &cd->hdr, &vk, cd);
1721
1722         } else
1723                 log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
1724
1725         if (r >= 0) {
1726                 memcpy(volume_key, vk->key, vk->keylength);
1727                 *volume_key_size = vk->keylength;
1728         }
1729
1730         crypt_free_volume_key(vk);
1731         return r;
1732 }
1733
1734 int crypt_volume_key_verify(struct crypt_device *cd,
1735         const char *volume_key,
1736         size_t volume_key_size)
1737 {
1738         struct volume_key *vk;
1739         int r;
1740
1741         if (!isLUKS(cd->type)) {
1742                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1743                 return -EINVAL;
1744         }
1745
1746         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1747         if (!vk)
1748                 return -ENOMEM;
1749
1750         r = LUKS_verify_volume_key(&cd->hdr, vk);
1751
1752         if (r == -EPERM)
1753                 log_err(cd, _("Volume key does not match the volume.\n"));
1754
1755         crypt_free_volume_key(vk);
1756
1757         return r;
1758 }
1759
1760 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
1761 {
1762         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
1763         cd->timeout = timeout_sec;
1764 }
1765
1766 void crypt_set_password_retry(struct crypt_device *cd, int tries)
1767 {
1768         log_dbg("Password retry count set to %d.", tries);
1769         cd->tries = tries;
1770 }
1771
1772 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
1773 {
1774         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
1775         cd->iteration_time = iteration_time_ms;
1776 }
1777
1778 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
1779 {
1780         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
1781         cd->password_verify = password_verify ? 1 : 0;
1782 }
1783
1784 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
1785 {
1786         switch (rng_type) {
1787         case CRYPT_RNG_URANDOM:
1788         case CRYPT_RNG_RANDOM:
1789                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
1790                 cd->rng_type = rng_type;
1791         }
1792 }
1793
1794 int crypt_get_rng_type(struct crypt_device *cd)
1795 {
1796         if (!cd)
1797                 return -EINVAL;
1798
1799         return cd->rng_type;
1800 }
1801
1802 int crypt_memory_lock(struct crypt_device *cd, int lock)
1803 {
1804         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
1805 }
1806
1807 // reporting
1808 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
1809 {
1810         int r;
1811
1812         if (!cd && dm_init(NULL, 1) < 0)
1813                 return CRYPT_INVALID;
1814
1815         r = dm_status_device(name);
1816
1817         if (!cd)
1818                 dm_exit();
1819
1820         if (r < 0 && r != -ENODEV)
1821                 return CRYPT_INVALID;
1822
1823         if (r == 0)
1824                 return CRYPT_ACTIVE;
1825
1826         if (r > 0)
1827                 return CRYPT_BUSY;
1828
1829         return CRYPT_INACTIVE;
1830 }
1831
1832 static void hexprintICB(struct crypt_device *cd, char *d, int n)
1833 {
1834         int i;
1835         for(i = 0; i < n; i++)
1836                 log_std(cd, "%02hhx ", (char)d[i]);
1837 }
1838
1839 int crypt_dump(struct crypt_device *cd)
1840 {
1841         int i;
1842         if (!isLUKS(cd->type)) { //FIXME
1843                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1844                 return -EINVAL;
1845         }
1846
1847         log_std(cd, "LUKS header information for %s\n\n", mdata_device(cd));
1848         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
1849         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
1850         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
1851         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
1852         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
1853         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
1854         log_std(cd, "MK digest:     \t");
1855         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
1856         log_std(cd, "\n");
1857         log_std(cd, "MK salt:       \t");
1858         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
1859         log_std(cd, "\n               \t");
1860         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1861         log_std(cd, "\n");
1862         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
1863         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
1864         for(i = 0; i < LUKS_NUMKEYS; i++) {
1865                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
1866                         log_std(cd, "Key Slot %d: ENABLED\n",i);
1867                         log_std(cd, "\tIterations:         \t%d\n",
1868                                 cd->hdr.keyblock[i].passwordIterations);
1869                         log_std(cd, "\tSalt:               \t");
1870                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
1871                                     LUKS_SALTSIZE/2);
1872                         log_std(cd, "\n\t                      \t");
1873                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
1874                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1875                         log_std(cd, "\n");
1876
1877                         log_std(cd, "\tKey material offset:\t%d\n",
1878                                 cd->hdr.keyblock[i].keyMaterialOffset);
1879                         log_std(cd, "\tAF stripes:            \t%d\n",
1880                                 cd->hdr.keyblock[i].stripes);
1881                 }
1882                 else 
1883                         log_std(cd, "Key Slot %d: DISABLED\n", i);
1884         }
1885
1886         return 0;
1887 }
1888
1889 const char *crypt_get_cipher(struct crypt_device *cd)
1890 {
1891         if (isPLAIN(cd->type))
1892                 return cd->plain_cipher;
1893
1894         if (isLUKS(cd->type))
1895                 return cd->hdr.cipherName;
1896
1897         if (isLOOPAES(cd->type))
1898                 return cd->loopaes_cipher;
1899
1900         return NULL;
1901 }
1902
1903 const char *crypt_get_cipher_mode(struct crypt_device *cd)
1904 {
1905         if (isPLAIN(cd->type))
1906                 return cd->plain_cipher_mode;
1907
1908         if (isLUKS(cd->type))
1909                 return cd->hdr.cipherMode;
1910
1911         if (isLOOPAES(cd->type))
1912                 return cd->loopaes_cipher_mode;
1913
1914         return NULL;
1915 }
1916
1917 const char *crypt_get_uuid(struct crypt_device *cd)
1918 {
1919         if (isLUKS(cd->type))
1920                 return cd->hdr.uuid;
1921
1922         if (isPLAIN(cd->type))
1923                 return cd->plain_uuid;
1924
1925         if (isLOOPAES(cd->type))
1926                 return cd->loopaes_uuid;
1927
1928         return NULL;
1929 }
1930
1931 const char *crypt_get_device_name(struct crypt_device *cd)
1932 {
1933         return cd->device;
1934 }
1935
1936
1937 int crypt_get_volume_key_size(struct crypt_device *cd)
1938 {
1939         if (isPLAIN(cd->type) && cd->volume_key)
1940                 return cd->volume_key->keylength;
1941
1942         if (isLUKS(cd->type))
1943                 return cd->hdr.keyBytes;
1944
1945         if (isLOOPAES(cd->type))
1946                 return cd->loopaes_key_size;
1947
1948         return 0;
1949 }
1950
1951 uint64_t crypt_get_data_offset(struct crypt_device *cd)
1952 {
1953         if (isPLAIN(cd->type))
1954                 return cd->plain_hdr.offset;
1955
1956         if (isLUKS(cd->type))
1957                 return cd->hdr.payloadOffset;
1958
1959         if (isLOOPAES(cd->type))
1960                 return cd->loopaes_hdr.offset;
1961
1962         return 0;
1963 }
1964
1965 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
1966 {
1967         if (isPLAIN(cd->type))
1968                 return cd->plain_hdr.skip;
1969
1970         if (isLUKS(cd->type))
1971                 return 0;
1972
1973         if (isLOOPAES(cd->type))
1974                 return cd->loopaes_hdr.skip;
1975
1976         return 0;
1977 }
1978
1979 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
1980 {
1981         if (!isLUKS(cd->type)) {
1982                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1983                 return CRYPT_SLOT_INVALID;
1984         }
1985
1986         return LUKS_keyslot_info(&cd->hdr, keyslot);
1987 }
1988
1989 int crypt_keyslot_max(const char *type)
1990 {
1991         if (type && isLUKS(type))
1992                 return LUKS_NUMKEYS;
1993
1994         return -EINVAL;
1995 }
1996
1997 const char *crypt_get_type(struct crypt_device *cd)
1998 {
1999         return cd->type;
2000 }
2001
2002 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2003                             const char *name,
2004                             struct crypt_active_device *cad)
2005 {
2006         struct crypt_dm_active_device dmd;
2007         int r;
2008
2009         r = dm_query_device(name, 0, &dmd);
2010         if (r < 0)
2011                 return r;
2012
2013         cad->offset     = dmd.offset;
2014         cad->iv_offset  = dmd.iv_offset;
2015         cad->size       = dmd.size;
2016         cad->flags      = dmd.flags;
2017
2018         return 0;
2019 }