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