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