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