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