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