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