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