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