Fix keyfile=- processing in create command (1.3.0, issue 104)
[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 verify_other_keyslot(struct crypt_device *cd,
237                                 const char *key_file,
238                                 int keyIndex)
239 {
240         struct volume_key *vk = NULL;
241         crypt_keyslot_info ki;
242         int openedIndex, r;
243         char *password = NULL;
244         size_t passwordLen;
245
246         r = crypt_get_key(_("Enter any remaining LUKS passphrase: "),
247                           &password, &passwordLen, 0, key_file, cd->timeout,
248                           cd->password_verify, cd);
249         if(r < 0)
250                 goto out;
251
252         ki = crypt_keyslot_status(cd, keyIndex);
253         if (ki == CRYPT_SLOT_ACTIVE) /* Not last slot */
254                 LUKS_keyslot_set(&cd->hdr, keyIndex, 0);
255
256         openedIndex = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT,
257                                              password, passwordLen,
258                                              &cd->hdr, &vk, cd);
259
260         if (ki == CRYPT_SLOT_ACTIVE)
261                 LUKS_keyslot_set(&cd->hdr, keyIndex, 1);
262
263         if (openedIndex < 0)
264                 r = -EPERM;
265         else
266                 log_verbose(cd, _("Key slot %d verified.\n"), openedIndex);
267 out:
268         crypt_free_volume_key(vk);
269         crypt_safe_free(password);
270         return r;
271 }
272
273 static int find_keyslot_by_passphrase(struct crypt_device *cd,
274                                       const char *key_file,
275                                       char *message)
276 {
277         struct volume_key *vk = NULL;
278         char *password = NULL;
279         size_t passwordLen;
280         int r;
281
282         r = crypt_get_key(message,&password,&passwordLen, 0, key_file,
283                           cd->timeout, cd->password_verify, cd);
284         if (r < 0)
285                 goto out;
286
287         r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
288                                    passwordLen, &cd->hdr, &vk, cd);
289 out:
290         crypt_free_volume_key(vk);
291         crypt_safe_free(password);
292         return r;
293 }
294
295 static int luks_remove_helper(struct crypt_device *cd,
296                               int key_slot,
297                               const char *other_key_file,
298                               const char *key_file,
299                               int verify)
300 {
301         crypt_keyslot_info ki;
302         int r = -EINVAL;
303
304         if (key_slot == CRYPT_ANY_SLOT) {
305                 key_slot = find_keyslot_by_passphrase(cd, key_file,
306                                 _("Enter LUKS passphrase to be deleted: "));
307                 if(key_slot < 0) {
308                         r = -EPERM;
309                         goto out;
310                 }
311
312                 log_std(cd, _("Key slot %d selected for deletion.\n"), key_slot);
313         }
314
315         ki = crypt_keyslot_status(cd, key_slot);
316         if (ki == CRYPT_SLOT_INVALID) {
317                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
318                         key_slot, LUKS_NUMKEYS - 1);
319                 r = -EINVAL;
320                 goto out;
321         }
322         if (ki <= CRYPT_SLOT_INACTIVE) {
323                 log_err(cd, _("Key %d not active. Can't wipe.\n"), key_slot);
324                 r = -EINVAL;
325                 goto out;
326         }
327
328         if (ki == CRYPT_SLOT_ACTIVE_LAST && cd->confirm &&
329             !(cd->confirm(_("This is the last keyslot."
330                             " Device will become unusable after purging this key."),
331                          cd->confirm_usrptr))) {
332                 r = -EINVAL;
333                 goto out;
334         }
335
336         if(verify)
337                 r = verify_other_keyslot(cd, other_key_file, key_slot);
338         else
339                 r = 0;
340
341         if (!r)
342                 r = crypt_keyslot_destroy(cd, key_slot);
343 out:
344         return (r < 0) ? r : 0;
345 }
346
347 static int create_device_helper(struct crypt_device *cd,
348                                 const char *name,
349                                 const char *hash,
350                                 const char *cipher,
351                                 const char *cipher_mode,
352                                 const char *key_file,
353                                 const char *passphrase,
354                                 size_t passphrase_size,
355                                 size_t key_size,
356                                 uint64_t size,
357                                 uint64_t skip,
358                                 uint64_t offset,
359                                 const char *uuid,
360                                 int read_only,
361                                 int reload)
362 {
363         crypt_status_info ci;
364         char *dm_cipher = NULL;
365         char *processed_key = NULL;
366         int r;
367
368         if (!name)
369                 return -EINVAL;
370
371         ci = crypt_status(cd, name);
372         if (ci == CRYPT_INVALID)
373                 return -EINVAL;
374
375         if (reload && ci < CRYPT_ACTIVE)
376                 return -EINVAL;
377
378         if (!reload && ci >= CRYPT_ACTIVE) {
379                 log_err(cd, _("Device %s already exists.\n"), name);
380                 return -EEXIST;
381         }
382
383         if (key_size > 1024) {
384                 log_err(cd, _("Invalid key size %d.\n"), (int)key_size);
385                 return -EINVAL;
386         }
387
388         r = device_check_and_adjust(cd, cd->device, !reload, &size, &offset, &read_only);
389         if (r)
390                 return r;
391
392         if (cipher_mode && asprintf(&dm_cipher, "%s-%s", cipher, cipher_mode) < 0)
393                 return -ENOMEM;
394
395         processed_key = process_key(cd, hash, key_file, key_size, passphrase, passphrase_size);
396         if (!processed_key) {
397                 r = -ENOENT;
398                 goto out;
399         }
400
401         r = dm_create_device(name, cd->device, dm_cipher ?: cipher, cd->type, uuid, size, skip, offset,
402                              key_size, processed_key, read_only, reload);
403
404         if (isPLAIN(cd->type) && !uuid)
405                 (void)dm_query_device(name, NULL, NULL, NULL, NULL, NULL, NULL,
406                                       NULL, NULL, NULL, &cd->plain_uuid);
407 out:
408         free(dm_cipher);
409         crypt_safe_free(processed_key);
410         return r;
411 }
412
413 static int open_from_hdr_and_vk(struct crypt_device *cd,
414                                 struct volume_key *vk,
415                                 const char *name,
416                                 uint32_t flags)
417 {
418         uint64_t size, offset;
419         char *cipher;
420         int read_only, no_uuid, r;
421
422         size = 0;
423         offset = crypt_get_data_offset(cd);
424         read_only = flags & CRYPT_ACTIVATE_READONLY;
425         no_uuid = flags & CRYPT_ACTIVATE_NO_UUID;
426
427         r = device_check_and_adjust(cd, cd->device, 1, &size, &offset, &read_only);
428         if (r)
429                 return r;
430
431         if (asprintf(&cipher, "%s-%s", crypt_get_cipher(cd),
432                      crypt_get_cipher_mode(cd)) < 0)
433                 r = -ENOMEM;
434         else
435                 r = dm_create_device(name, cd->device, cipher, cd->type,
436                                      no_uuid ? NULL : crypt_get_uuid(cd),
437                                      size, 0, offset, vk->keylength, vk->key,
438                                      read_only, 0);
439         free(cipher);
440         return r;
441 }
442
443 static void log_wrapper(int level, const char *msg, void *usrptr)
444 {
445         void (*xlog)(int level, char *msg) = usrptr;
446         xlog(level, (char *)msg);
447 }
448
449 static int yesDialog_wrapper(const char *msg, void *usrptr)
450 {
451         int (*xyesDialog)(char *msg) = usrptr;
452         return xyesDialog((char*)msg);
453 }
454
455 int crypt_confirm(struct crypt_device *cd, const char *msg)
456 {
457         if (!cd || !cd->confirm)
458                 return 1;
459         else
460                 return cd->confirm(msg, cd->confirm_usrptr);
461 }
462
463 static int key_from_terminal(struct crypt_device *cd, char *msg, char **key,
464                               size_t *key_len, int force_verify)
465 {
466         char *prompt = NULL;
467         int r;
468
469         *key = NULL;
470         if(!msg && asprintf(&prompt, _("Enter passphrase for %s: "),
471                             cd->backing_file ?: cd->device) < 0)
472                 return -ENOMEM;
473
474         if (!msg)
475                 msg = prompt;
476
477         if (cd->password) {
478                 *key = crypt_safe_alloc(DEFAULT_PASSPHRASE_SIZE_MAX);
479                 if (!*key) {
480                         r = -ENOMEM;
481                         goto out;
482                 }
483                 r = cd->password(msg, *key, DEFAULT_PASSPHRASE_SIZE_MAX,
484                                  cd->password_usrptr);
485                 if (r < 0) {
486                         crypt_safe_free(*key);
487                         *key = NULL;
488                 } else
489                         *key_len = r;
490         } else
491                 r = crypt_get_key(msg, key, key_len, 0, NULL, cd->timeout,
492                                   (force_verify || cd->password_verify), cd);
493 out:
494         free(prompt);
495         return (r < 0) ? r: 0;
496 }
497
498 static int volume_key_by_terminal_passphrase(struct crypt_device *cd, int keyslot,
499                                              struct volume_key **vk)
500 {
501         char *passphrase_read = NULL;
502         size_t passphrase_size_read;
503         int r = -EINVAL, eperm = 0, tries = cd->tries;
504
505         *vk = NULL;
506         do {
507                 crypt_free_volume_key(*vk);
508                 *vk = NULL;
509
510                 r = key_from_terminal(cd, NULL, &passphrase_read,
511                                       &passphrase_size_read, 0);
512                 if(r < 0)
513                         goto out;
514
515                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
516                                            passphrase_size_read, &cd->hdr, vk, cd);
517                 if (r == -EPERM)
518                         eperm = 1;
519                 crypt_safe_free(passphrase_read);
520                 passphrase_read = NULL;
521         } while (r == -EPERM && (--tries > 0));
522 out:
523         if (r < 0) {
524                 crypt_free_volume_key(*vk);
525                 *vk = NULL;
526
527                 /* Report wrong passphrase if at least one try failed */
528                 if (eperm && r == -EPIPE)
529                         r = -EPERM;
530         }
531
532         crypt_safe_free(passphrase_read);
533         return r;
534 }
535
536 static int key_from_file(struct crypt_device *cd, char *msg,
537                           char **key, size_t *key_len,
538                           const char *key_file, size_t key_size)
539 {
540         return crypt_get_key(msg, key, key_len, key_size, key_file,
541                              cd->timeout, 0, cd);
542 }
543
544 static int _crypt_init(struct crypt_device **cd,
545                        const char *type,
546                        struct crypt_options *options,
547                        int load, int need_dm)
548 {
549         int init_by_name, r;
550
551         /* if it is plain device and mapping table is being reloaded
552         initialize it by name*/
553         init_by_name = (type && !strcmp(type, CRYPT_PLAIN) && load);
554
555         /* Some of old API calls do not require DM in kernel,
556            fake initialisation by initialise it with kernel_check disabled */
557         if (!need_dm)
558                 (void)dm_init(NULL, 0);
559         if (init_by_name)
560                 r = crypt_init_by_name(cd, options->name);
561         else
562                 r = crypt_init(cd, options->device);
563         if (!need_dm)
564                 dm_exit();
565
566         if (r)
567                 return -EINVAL;
568
569         crypt_set_log_callback(*cd, log_wrapper, options->icb->log);
570         crypt_set_confirm_callback(*cd, yesDialog_wrapper, options->icb->yesDialog);
571
572         crypt_set_timeout(*cd, options->timeout);
573         crypt_set_password_retry(*cd, options->tries);
574         crypt_set_iterarion_time(*cd, options->iteration_time ?: 1000);
575         crypt_set_password_verify(*cd, options->flags & CRYPT_FLAG_VERIFY);
576
577         if (load && !init_by_name)
578                 r = crypt_load(*cd, type, NULL);
579
580         if (!r && type && !(*cd)->type) {
581                 (*cd)->type = strdup(type);
582                 if (!(*cd)->type)
583                         r = -ENOMEM;
584         }
585
586         if (r)
587                 crypt_free(*cd);
588
589         return r;
590 }
591
592 void crypt_set_log_callback(struct crypt_device *cd,
593         void (*log)(int level, const char *msg, void *usrptr),
594         void *usrptr)
595 {
596         if (!cd)
597                 _default_log = log;
598         else {
599                 cd->log = log;
600                 cd->log_usrptr = usrptr;
601         }
602 }
603
604 void crypt_set_confirm_callback(struct crypt_device *cd,
605         int (*confirm)(const char *msg, void *usrptr),
606         void *usrptr)
607 {
608         cd->confirm = confirm;
609         cd->confirm_usrptr = usrptr;
610 }
611
612 void crypt_set_password_callback(struct crypt_device *cd,
613         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
614         void *usrptr)
615 {
616         cd->password = password;
617         cd->password_usrptr = usrptr;
618 }
619
620 /* OPTIONS: name, cipher, device, hash, key_file, key_size, key_slot,
621  *          offset, size, skip, timeout, tries, passphrase_fd (ignored),
622  *          flags, icb */
623 static int crypt_create_and_update_device(struct crypt_options *options, int update)
624 {
625         struct crypt_device *cd = NULL;
626         char *passphrase = NULL;
627         size_t passphrase_size = 0;
628         int r;
629
630         r = _crypt_init(&cd, CRYPT_PLAIN, options, 0, 1);
631         if (r)
632                 return r;
633
634         r = crypt_get_key(_("Enter passphrase: "), &passphrase, &passphrase_size,
635                           options->key_size, options->key_file,
636                           cd->timeout, cd->password_verify, cd);
637         if (!r)
638                 r = create_device_helper(cd, options->name, options->hash,
639                         options->cipher, NULL, options->key_file,
640                         passphrase, passphrase_size,
641                         options->key_size, options->size, options->skip,
642                         options->offset, NULL, options->flags & CRYPT_FLAG_READONLY,
643                         update);
644
645         crypt_safe_free(passphrase);
646         crypt_free(cd);
647         return r;
648 }
649
650 int crypt_create_device(struct crypt_options *options)
651 {
652         return crypt_create_and_update_device(options, 0);
653 }
654
655 int crypt_update_device(struct crypt_options *options)
656 {
657         return crypt_create_and_update_device(options, 1);
658 }
659
660 /* OPTIONS: name, size, icb */
661 int crypt_resize_device(struct crypt_options *options)
662 {
663         struct crypt_device *cd = NULL;
664         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
665         const char *type = NULL;
666         uint64_t size, skip, offset;
667         int key_size, read_only, r;
668
669         log_dbg("Resizing device %s to %" PRIu64 " sectors.", options->name, options->size);
670
671         if (dm_init(NULL, 1) < 0)
672                 return -ENOSYS;
673
674         r = dm_query_device(options->name, &device, &size, &skip, &offset,
675                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
676         if (r < 0) {
677                 log_err(NULL, _("Device %s is not active.\n"), options->name);
678                 goto out;
679         }
680
681         /* Try to determine type of device from UUID */
682         type = CRYPT_PLAIN;
683         if (uuid) {
684                 if (!strncmp(uuid, CRYPT_PLAIN, strlen(CRYPT_PLAIN))) {
685                         type = CRYPT_PLAIN;
686                         free (uuid);
687                         uuid = NULL;
688                 } else if (!strncmp(uuid, CRYPT_LUKS1, strlen(CRYPT_LUKS1)))
689                         type = CRYPT_LUKS1;
690         }
691
692         if (!options->device)
693                 options->device = device;
694
695         r = _crypt_init(&cd, type, options, 1, 1);
696         if (r)
697                 goto out;
698
699         size = options->size;
700         r = device_check_and_adjust(cd, device, 0, &size, &offset, &read_only);
701         if (r)
702                 goto out;
703
704         r = dm_create_device(options->name, device, cipher, type,
705                              crypt_get_uuid(cd), size, skip, offset,
706                              key_size, key, read_only, 1);
707 out:
708         crypt_safe_free(key);
709         free(cipher);
710         if (options->device == device)
711                 options->device = NULL;
712         free(device);
713         free(uuid);
714         crypt_free(cd);
715         dm_exit();
716         return r;
717 }
718
719 /* OPTIONS: name, icb */
720 int crypt_query_device(struct crypt_options *options)
721 {
722         int read_only, r;
723
724         log_dbg("Query device %s.", options->name);
725
726         if (dm_init(NULL, 1) < 0)
727                 return -ENOSYS;
728
729         r = dm_status_device(options->name);
730         if (r < 0)
731                 goto out;
732
733         r = dm_query_device(options->name, (char **)&options->device, &options->size,
734                             &options->skip, &options->offset, (char **)&options->cipher,
735                             &options->key_size, NULL, &read_only, NULL, NULL);
736         if (r >= 0) {
737                 if (read_only)
738                         options->flags |= CRYPT_FLAG_READONLY;
739
740                 options->flags |= CRYPT_FLAG_FREE_DEVICE;
741                 options->flags |= CRYPT_FLAG_FREE_CIPHER;
742
743                 r = 1;
744         }
745 out:
746         if (r == -ENODEV)
747                 r = 0;
748
749         dm_exit();
750         return r;
751 }
752
753 /* OPTIONS: name, icb */
754 int crypt_remove_device(struct crypt_options *options)
755 {
756         struct crypt_device *cd = NULL;
757         int r;
758
759         r = crypt_init_by_name(&cd, options->name);
760         if (r == 0)
761                 r = crypt_deactivate(cd, options->name);
762
763         crypt_free(cd);
764         return r;
765
766 }
767
768 /* OPTIONS: device, cipher, hash, align_payload, key_size (master key), key_slot
769  *          new_key_file, iteration_time, timeout, flags, icb */
770 int crypt_luksFormat(struct crypt_options *options)
771 {
772         char cipherName[LUKS_CIPHERNAME_L];
773         char cipherMode[LUKS_CIPHERMODE_L];
774         char *password=NULL;
775         size_t passwordLen;
776         struct crypt_device *cd = NULL;
777         struct crypt_params_luks1 cp = {
778                 .hash = options->hash,
779                 .data_alignment = options->align_payload
780         };
781         int r;
782
783         r = crypt_parse_name_and_mode(options->cipher, cipherName, NULL, cipherMode);
784         if(r < 0) {
785                 log_err(cd, _("No known cipher specification pattern detected.\n"));
786                 return r;
787         }
788
789         if ((r = _crypt_init(&cd, CRYPT_LUKS1, options, 0, 1)))
790                 return r;
791
792         if (options->key_slot >= LUKS_NUMKEYS && options->key_slot != CRYPT_ANY_SLOT) {
793                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
794                         options->key_slot, LUKS_NUMKEYS - 1);
795                 r = -EINVAL;
796                 goto out;
797         }
798
799         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen, 0,
800                           options->new_key_file, cd->timeout, cd->password_verify, cd);
801
802         if(r < 0)
803                 goto out;
804
805         r = crypt_format(cd, CRYPT_LUKS1, cipherName, cipherMode,
806                          NULL, NULL, options->key_size, &cp);
807         if (r < 0)
808                 goto out;
809
810         /* Add keyslot using internally stored volume key generated during format */
811         r = crypt_keyslot_add_by_volume_key(cd, options->key_slot, NULL, 0,
812                                             password, passwordLen);
813 out:
814         crypt_free(cd);
815         crypt_safe_free(password);
816         return (r < 0) ? r : 0;
817 }
818
819 /* OPTIONS: name, device, key_size, key_file, timeout, tries, flags, icb */
820 int crypt_luksOpen(struct crypt_options *options)
821 {
822         struct crypt_device *cd = NULL;
823         uint32_t flags = 0;
824         int r;
825
826         if (!options->name)
827                 return -EINVAL;
828
829         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
830         if (r)
831                 return r;
832
833         if (options->flags & CRYPT_FLAG_READONLY)
834                 flags |= CRYPT_ACTIVATE_READONLY;
835
836         if (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS)
837                 flags |= CRYPT_ACTIVATE_NO_UUID;
838
839         if (options->key_file)
840                 r = crypt_activate_by_keyfile(cd, options->name,
841                         CRYPT_ANY_SLOT, options->key_file, 0,
842                         flags);
843         else
844                 r = crypt_activate_by_passphrase(cd, options->name,
845                         CRYPT_ANY_SLOT, options->passphrase,
846                         options->passphrase ? strlen(options->passphrase) : 0,
847                         flags);
848
849         crypt_free(cd);
850         return (r < 0) ? r : 0;
851 }
852
853 /* OPTIONS: device, keys_slot, key_file, timeout, flags, icb */
854 int crypt_luksKillSlot(struct crypt_options *options)
855 {
856         struct crypt_device *cd = NULL;
857         int r;
858
859         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
860         if (r)
861                 return r;
862
863         r = luks_remove_helper(cd, options->key_slot, options->key_file, NULL,
864                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
865
866         crypt_free(cd);
867         return (r < 0) ? r : 0;
868 }
869
870 /* OPTIONS: device, new_key_file, key_file, timeout, flags, icb */
871 int crypt_luksRemoveKey(struct crypt_options *options)
872 {
873         struct crypt_device *cd = NULL;
874         int r;
875
876         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
877         if (r)
878                 return r;
879
880         r = luks_remove_helper(cd, CRYPT_ANY_SLOT, options->key_file, options->new_key_file,
881                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
882
883         crypt_free(cd);
884         return (r < 0) ? r : 0;
885 }
886
887
888 /* OPTIONS: device, new_key_file, key_file, key_slot, flags,
889             iteration_time, timeout, icb */
890 int crypt_luksAddKey(struct crypt_options *options)
891 {
892         struct crypt_device *cd = NULL;
893         int r = -EINVAL;
894
895         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
896         if (r)
897                 return r;
898
899         if (options->key_file || options->new_key_file)
900                 r = crypt_keyslot_add_by_keyfile(cd, options->key_slot,
901                                                  options->key_file, 0,
902                                                  options->new_key_file, 0);
903         else
904                 r = crypt_keyslot_add_by_passphrase(cd, options->key_slot,
905                                                     NULL, 0, NULL, 0);
906
907         crypt_free(cd);
908         return (r < 0) ? r : 0;
909 }
910
911 /* OPTIONS: device, icb */
912 int crypt_luksUUID(struct crypt_options *options)
913 {
914         struct crypt_device *cd = NULL;
915         const char *uuid;
916         int r;
917
918         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
919         if (r)
920                 return r;
921
922         uuid = crypt_get_uuid(cd);
923         log_std(cd, "%s\n", uuid ?: "");
924         crypt_free(cd);
925         return 0;
926 }
927
928 /* OPTIONS: device, icb */
929 int crypt_isLuks(struct crypt_options *options)
930 {
931         struct crypt_device *cd = NULL;
932         int r;
933
934         log_dbg("Check device %s for LUKS header.", options->device);
935
936         r = init_crypto(cd);
937         if (r < 0)
938                 return r;
939
940         r = crypt_init(&cd, options->device);
941         if (r < 0)
942                 return -EINVAL;
943
944         /* Do print fail here, no need to crypt_load() */
945         r = LUKS_read_phdr(cd->device, &cd->hdr, 0, cd) ? -EINVAL : 0;
946
947         crypt_free(cd);
948         return r;
949 }
950
951 /* OPTIONS: device, icb */
952 int crypt_luksDump(struct crypt_options *options)
953 {
954         struct crypt_device *cd = NULL;
955         int r;
956
957         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
958         if(r < 0)
959                 return r;
960
961         r = crypt_dump(cd);
962
963         crypt_free(cd);
964         return r;
965 }
966
967 void crypt_get_error(char *buf, size_t size)
968 {
969         const char *error = get_error();
970
971         if (!buf || size < 1)
972                 set_error(NULL);
973         else if (error) {
974                 strncpy(buf, error, size - 1);
975                 buf[size - 1] = '\0';
976                 set_error(NULL);
977         } else
978                 buf[0] = '\0';
979 }
980
981 void crypt_put_options(struct crypt_options *options)
982 {
983         if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
984                 free((char *)options->device);
985                 options->device = NULL;
986                 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
987         }
988         if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
989                 free((char *)options->cipher);
990                 options->cipher = NULL;
991                 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
992         }
993 }
994
995 const char *crypt_get_dir(void)
996 {
997         return dm_get_dir();
998 }
999
1000 /////////////////////////////////
1001 //
1002 // New API
1003 //
1004
1005 int crypt_init(struct crypt_device **cd, const char *device)
1006 {
1007         struct crypt_device *h = NULL;
1008         int r, readonly = 0;
1009
1010         if (!cd)
1011                 return -EINVAL;
1012
1013         log_dbg("Allocating crypt device %s context.", device);
1014
1015         if (!(h = malloc(sizeof(struct crypt_device))))
1016                 return -ENOMEM;
1017
1018         memset(h, 0, sizeof(*h));
1019         h->loop_fd = -1;
1020
1021         if (device) {
1022                 r = device_ready(NULL, device, O_RDONLY);
1023                 if (r == -ENOTBLK) {
1024                         h->device = crypt_loop_get_device();
1025                         log_dbg("Not a block device, %s%s.",
1026                                 h->device ? "using free loop device " :
1027                                          "no free loop device found",
1028                                 h->device ?: "");
1029                         if (!h->device) {
1030                                 log_err(NULL, _("Cannot find a free loopback device.\n"));
1031                                 r = -ENOSYS;
1032                                 goto bad;
1033                         }
1034
1035                         /* Keep the loop open, dettached on last close. */
1036                         h->loop_fd = crypt_loop_attach(h->device, device, 0, 1, &readonly);
1037                         if (h->loop_fd == -1) {
1038                                 log_err(NULL, _("Attaching loopback device failed "
1039                                         "(loop device with autoclear flag is required).\n"));
1040                                 r = -EINVAL;
1041                                 goto bad;
1042                         }
1043
1044                         h->backing_file = crypt_loop_backing_file(h->device);
1045                         r = device_ready(NULL, h->device, O_RDONLY);
1046                 }
1047                 if (r < 0) {
1048                         r = -ENOTBLK;
1049                         goto bad;
1050                 }
1051         }
1052
1053         if (!h->device && device && !(h->device = strdup(device))) {
1054                 r = -ENOMEM;
1055                 goto bad;
1056         }
1057
1058         if (dm_init(h, 1) < 0) {
1059                 r = -ENOSYS;
1060                 goto bad;
1061         }
1062
1063         h->iteration_time = 1000;
1064         h->password_verify = 0;
1065         h->tries = 3;
1066         h->rng_type = crypt_random_default_key_rng();
1067         *cd = h;
1068         return 0;
1069 bad:
1070
1071         if (h) {
1072                 if (h->loop_fd != -1)
1073                         close(h->loop_fd);
1074                 free(h->device);
1075                 free(h->backing_file);
1076         }
1077         free(h);
1078         return r;
1079 }
1080
1081 int crypt_init_by_name(struct crypt_device **cd, const char *name)
1082 {
1083         crypt_status_info ci;
1084         struct crypt_active_device cad;
1085         char *device = NULL, *cipher_full = NULL, *device_uuid = NULL;
1086         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
1087         char *key = NULL;
1088         int key_size = 0, key_nums, r;
1089
1090
1091         log_dbg("Allocating crypt device context by device %s.", name);
1092
1093         ci = crypt_status(NULL, name);
1094         if (ci == CRYPT_INVALID)
1095                 return -ENODEV;
1096
1097         if (ci < CRYPT_ACTIVE) {
1098                 log_err(NULL, _("Device %s is not active.\n"), name);
1099                 return -ENODEV;
1100         }
1101
1102         r = dm_query_device(name, &device, &cad.size, &cad.iv_offset, &cad.offset,
1103                             &cipher_full, &key_size, &key, NULL, NULL,
1104                             &device_uuid);
1105         if (r < 0)
1106                 goto out;
1107
1108         *cd = NULL;
1109         r = crypt_init(cd, device);
1110
1111         /* Underlying device disappeared but mapping still active */
1112         if (!device || r == -ENOTBLK)
1113                 log_verbose(NULL, _("Underlying device for crypt device %s disappeared.\n"),
1114                             name);
1115
1116         /* Underlying device is not readable but crypt mapping exists */
1117         if (r == -ENOTBLK) {
1118                 free(device);
1119                 device = NULL;
1120                 r = crypt_init(cd, NULL);
1121         }
1122
1123         if (r < 0)
1124                 goto out;
1125
1126         /* Try to initialise basic parameters from active device */
1127
1128         if (!(*cd)->backing_file && device && crypt_loop_device(device) &&
1129             !((*cd)->backing_file = crypt_loop_backing_file(device))) {
1130                 r = -ENOMEM;
1131                 goto out;
1132         }
1133
1134         if (device_uuid) {
1135                 if (!strncmp(CRYPT_PLAIN, device_uuid, sizeof(CRYPT_PLAIN)-1)) {
1136                         (*cd)->type = strdup(CRYPT_PLAIN);
1137                         (*cd)->plain_uuid = strdup(device_uuid);
1138                         (*cd)->plain_hdr.hash = NULL; /* no way to get this */
1139                         (*cd)->plain_hdr.offset = cad.offset;
1140                         (*cd)->plain_hdr.skip = cad.iv_offset;
1141                         (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1142                         if (!(*cd)->volume_key) {
1143                                 r = -ENOMEM;
1144                                 goto out;
1145                         }
1146
1147                         r = crypt_parse_name_and_mode(cipher_full, cipher, NULL, cipher_mode);
1148                         if (!r) {
1149                                 (*cd)->plain_cipher = strdup(cipher);
1150                                 (*cd)->plain_cipher_mode = strdup(cipher_mode);
1151                         }
1152                 } else if (!strncmp(CRYPT_LOOPAES, device_uuid, sizeof(CRYPT_LOOPAES)-1)) {
1153                         (*cd)->type = strdup(CRYPT_LOOPAES);
1154                         (*cd)->loopaes_uuid = strdup(device_uuid);
1155                         (*cd)->loopaes_hdr.offset = cad.offset;
1156
1157                         r = crypt_parse_name_and_mode(cipher_full, cipher,
1158                                                       &key_nums, cipher_mode);
1159                         if (!r) {
1160                                 (*cd)->loopaes_cipher = strdup(cipher);
1161                                 (*cd)->loopaes_cipher_mode = strdup(cipher_mode);
1162                                 /* version 3 uses last key for IV */
1163                                 if (key_size % key_nums)
1164                                         key_nums++;
1165                                 (*cd)->loopaes_key_size = key_size / key_nums;
1166                         }
1167                 } else if (!strncmp(CRYPT_LUKS1, device_uuid, sizeof(CRYPT_LUKS1)-1)) {
1168                         if (device) {
1169                                 if (crypt_load(*cd, CRYPT_LUKS1, NULL) < 0 ||
1170                                     crypt_volume_key_verify(*cd, key, key_size) < 0) {
1171                                         log_dbg("LUKS device header does not match active device.");
1172                                         goto out;
1173                                 }
1174
1175                                 (*cd)->volume_key = crypt_alloc_volume_key(key_size, key);
1176                                 if (!(*cd)->volume_key) {
1177                                         r = -ENOMEM;
1178                                         goto out;
1179                                 }
1180                         }
1181                 }
1182         } else
1183                 log_dbg("Active device has no UUID set, some parameters are not set.");
1184
1185 out:
1186         if (r < 0) {
1187                 crypt_free(*cd);
1188                 *cd = NULL;
1189         }
1190         crypt_safe_free(key);
1191         free(device);
1192         free(cipher_full);
1193         free(device_uuid);
1194         return r;
1195 }
1196
1197 static int _crypt_format_plain(struct crypt_device *cd,
1198                                const char *cipher,
1199                                const char *cipher_mode,
1200                                const char *uuid,
1201                                size_t volume_key_size,
1202                                struct crypt_params_plain *params)
1203 {
1204         if (!cipher || !cipher_mode) {
1205                 log_err(cd, _("Invalid plain crypt parameters.\n"));
1206                 return -EINVAL;
1207         }
1208
1209         if (volume_key_size > 1024) {
1210                 log_err(cd, _("Invalid key size.\n"));
1211                 return -EINVAL;
1212         }
1213
1214         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
1215         if (!cd->volume_key)
1216                 return -ENOMEM;
1217
1218         cd->plain_cipher = strdup(cipher);
1219         cd->plain_cipher_mode = strdup(cipher_mode);
1220
1221         if (uuid)
1222                 cd->plain_uuid = strdup(uuid);
1223
1224         if (params && params->hash)
1225                 cd->plain_hdr.hash = strdup(params->hash);
1226
1227         cd->plain_hdr.offset = params ? params->offset : 0;
1228         cd->plain_hdr.skip = params ? params->skip : 0;
1229
1230         if (!cd->plain_cipher || !cd->plain_cipher_mode)
1231                 return -ENOMEM;
1232
1233         return 0;
1234 }
1235
1236 static int _crypt_format_luks1(struct crypt_device *cd,
1237                                const char *cipher,
1238                                const char *cipher_mode,
1239                                const char *uuid,
1240                                const char *volume_key,
1241                                size_t volume_key_size,
1242                                struct crypt_params_luks1 *params)
1243 {
1244         int r;
1245         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1246         unsigned long alignment_offset = 0;
1247
1248         if (!cd->device) {
1249                 log_err(cd, _("Can't format LUKS without device.\n"));
1250                 return -EINVAL;
1251         }
1252
1253         if (volume_key)
1254                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1255                                                       volume_key);
1256         else
1257                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1258
1259         if(!cd->volume_key)
1260                 return -ENOMEM;
1261
1262         if (params && params->data_alignment)
1263                 required_alignment = params->data_alignment * SECTOR_SIZE;
1264         else
1265                 get_topology_alignment(cd->device, &required_alignment,
1266                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1267
1268         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
1269                                (params && params->hash) ? params->hash : "sha1",
1270                                uuid, LUKS_STRIPES,
1271                                required_alignment / SECTOR_SIZE,
1272                                alignment_offset / SECTOR_SIZE,
1273                                cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1274         if(r < 0)
1275                 return r;
1276
1277         /* Wipe first 8 sectors - fs magic numbers etc. */
1278         r = wipe_device_header(cd->device, 8);
1279         if(r < 0) {
1280                 if (r == -EBUSY)
1281                         log_err(cd, _("Cannot format device %s which is still in use.\n"),
1282                                 cd->device);
1283                 else
1284                         log_err(cd, _("Cannot wipe header on device %s.\n"),
1285                                 cd->device);
1286
1287                 return r;
1288         }
1289
1290         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
1291
1292         return r;
1293 }
1294
1295 static int _crypt_format_loopaes(struct crypt_device *cd,
1296                                  const char *cipher,
1297                                  const char *uuid,
1298                                  size_t volume_key_size,
1299                                  struct crypt_params_loopaes *params)
1300 {
1301         if (!cd->device) {
1302                 log_err(cd, _("Can't format LOOPAES without device.\n"));
1303                 return -EINVAL;
1304         }
1305
1306         if (volume_key_size > 1024) {
1307                 log_err(cd, _("Invalid key size.\n"));
1308                 return -EINVAL;
1309         }
1310
1311         cd->loopaes_key_size = volume_key_size;
1312
1313         cd->loopaes_cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1314
1315         if (uuid)
1316                 cd->loopaes_uuid = strdup(uuid);
1317
1318         if (params && params->hash)
1319                 cd->loopaes_hdr.hash = strdup(params->hash);
1320
1321         cd->loopaes_hdr.offset = params ? params->offset : 0;
1322         cd->loopaes_hdr.skip = params ? params->skip : 0;
1323
1324         return 0;
1325 }
1326
1327 int crypt_format(struct crypt_device *cd,
1328         const char *type,
1329         const char *cipher,
1330         const char *cipher_mode,
1331         const char *uuid,
1332         const char *volume_key,
1333         size_t volume_key_size,
1334         void *params)
1335 {
1336         int r;
1337
1338         if (!type)
1339                 return -EINVAL;
1340
1341         log_dbg("Formatting device %s as type %s.", cd->device ?: "(none)", type);
1342
1343         r = init_crypto(cd);
1344         if (r < 0)
1345                 return r;
1346
1347         if (isPLAIN(type))
1348                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1349                                         uuid, volume_key_size, params);
1350         else if (isLUKS(type))
1351                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1352                                         uuid, volume_key, volume_key_size, params);
1353         else if (isLOOPAES(type))
1354                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
1355         else {
1356                 /* FIXME: allow plugins here? */
1357                 log_err(cd, _("Unknown crypt device type %s requested.\n"), type);
1358                 r = -EINVAL;
1359         }
1360
1361         if (!r && !(cd->type = strdup(type)))
1362                 r = -ENOMEM;
1363
1364         if (r < 0) {
1365                 crypt_free_volume_key(cd->volume_key);
1366                 cd->volume_key = NULL;
1367         }
1368
1369         return r;
1370 }
1371
1372 int crypt_load(struct crypt_device *cd,
1373                const char *requested_type,
1374                void *params __attribute__((unused)))
1375 {
1376         struct luks_phdr hdr;
1377         int r;
1378
1379         log_dbg("Trying to load %s crypt type from device %s.",
1380                 requested_type ?: "any", cd->device ?: "(none)");
1381
1382         if (!cd->device)
1383                 return -EINVAL;
1384
1385         if (requested_type && !isLUKS(requested_type))
1386                 return -EINVAL;
1387
1388         r = init_crypto(cd);
1389         if (r < 0)
1390                 return r;
1391
1392         r = LUKS_read_phdr(cd->device, &hdr, 1, cd);
1393
1394         if (!r) {
1395                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
1396                 cd->type = strdup(CRYPT_LUKS1);
1397                 if (!cd->type)
1398                         r = -ENOMEM;
1399         }
1400
1401         return r;
1402 }
1403
1404 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
1405 {
1406         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
1407         uint64_t size, skip, offset;
1408         int key_size, read_only, r;
1409
1410         /* Device context type must be initialised */
1411         if (!cd->type || !crypt_get_uuid(cd))
1412                 return -EINVAL;
1413
1414         log_dbg("Resizing device %s to %" PRIu64 " sectors.", name, new_size);
1415
1416         r = dm_query_device(name, &device, &size, &skip, &offset,
1417                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
1418         if (r < 0) {
1419                 log_err(NULL, _("Device %s is not active.\n"), name);
1420                 goto out;
1421         }
1422
1423         if (!uuid) {
1424                 r = -EINVAL;
1425                 goto out;
1426         }
1427
1428         r = device_check_and_adjust(cd, device, 0, &new_size, &offset, &read_only);
1429         if (r)
1430                 goto out;
1431
1432         if (new_size == size) {
1433                 log_dbg("Device has already requested size %" PRIu64
1434                         " sectors.", size);
1435                 r = 0;
1436                 goto out;
1437         }
1438
1439         r = dm_create_device(name, device, cipher, cd->type,
1440                              crypt_get_uuid(cd), new_size, skip, offset,
1441                              key_size, key, read_only, 1);
1442 out:
1443         crypt_safe_free(key);
1444         free(cipher);
1445         free(device);
1446         free(uuid);
1447
1448         return r;
1449 }
1450
1451 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
1452 {
1453         if (!isLUKS(cd->type)) {
1454                 log_err(cd, _("This operation is not supported for this device type.\n"));
1455                 return  -EINVAL;
1456         }
1457
1458         if (uuid && !strncmp(uuid, cd->hdr.uuid, sizeof(cd->hdr.uuid))) {
1459                 log_dbg("UUID is the same as requested (%s) for device %s.",
1460                         uuid, cd->device);
1461                 return 0;
1462         }
1463
1464         if (uuid)
1465                 log_dbg("Requested new UUID change to %s for %s.", uuid, cd->device);
1466         else
1467                 log_dbg("Requested new UUID refresh for %s.", cd->device);
1468
1469         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
1470                 return -EPERM;
1471
1472         return LUKS_hdr_uuid_set(cd->device, &cd->hdr, uuid, cd);
1473 }
1474
1475 int crypt_header_backup(struct crypt_device *cd,
1476                         const char *requested_type,
1477                         const char *backup_file)
1478 {
1479         int r;
1480
1481         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1482                 return -EINVAL;
1483
1484         r = init_crypto(cd);
1485         if (r < 0)
1486                 return r;
1487
1488         log_dbg("Requested header backup of device %s (%s) to "
1489                 "file %s.", cd->device, requested_type, backup_file);
1490
1491         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
1492 }
1493
1494 int crypt_header_restore(struct crypt_device *cd,
1495                          const char *requested_type,
1496                          const char *backup_file)
1497 {
1498         int r;
1499
1500         if (requested_type && !isLUKS(requested_type))
1501                 return -EINVAL;
1502
1503         /* Some hash functions need initialized gcrypt library */
1504         r = init_crypto(cd);
1505         if (r < 0)
1506                 return r;
1507
1508         log_dbg("Requested header restore to device %s (%s) from "
1509                 "file %s.", cd->device, requested_type, backup_file);
1510
1511         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
1512 }
1513
1514 void crypt_free(struct crypt_device *cd)
1515 {
1516         if (cd) {
1517                 log_dbg("Releasing crypt device %s context.", cd->device);
1518
1519                 if (cd->loop_fd != -1)
1520                         close(cd->loop_fd);
1521
1522                 dm_exit();
1523                 crypt_free_volume_key(cd->volume_key);
1524
1525                 free(cd->device);
1526                 free(cd->backing_file);
1527                 free(cd->type);
1528
1529                 /* used in plain device only */
1530                 free((char*)cd->plain_hdr.hash);
1531                 free(cd->plain_cipher);
1532                 free(cd->plain_cipher_mode);
1533                 free(cd->plain_uuid);
1534
1535                 /* used in loop-AES device only */
1536                 free((char*)cd->loopaes_hdr.hash);
1537                 free(cd->loopaes_cipher);
1538                 free(cd->loopaes_uuid);
1539
1540                 free(cd);
1541         }
1542 }
1543
1544 int crypt_suspend(struct crypt_device *cd,
1545                   const char *name)
1546 {
1547         crypt_status_info ci;
1548         int r, suspended = 0;
1549
1550         log_dbg("Suspending volume %s.", name);
1551
1552         ci = crypt_status(NULL, name);
1553         if (ci < CRYPT_ACTIVE) {
1554                 log_err(cd, _("Volume %s is not active.\n"), name);
1555                 return -EINVAL;
1556         }
1557
1558         if (!cd && dm_init(NULL, 1) < 0)
1559                 return -ENOSYS;
1560
1561         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1562                             NULL, NULL, NULL, NULL, &suspended, NULL);
1563         if (r < 0)
1564                 goto out;
1565
1566         if (suspended) {
1567                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1568                 r = -EINVAL;
1569                 goto out;
1570         }
1571
1572         r = dm_suspend_and_wipe_key(name);
1573         if (r == -ENOTSUP)
1574                 log_err(cd, "Suspend is not supported for device %s.\n", name);
1575         else if (r)
1576                 log_err(cd, "Error during suspending device %s.\n", name);
1577 out:
1578         if (!cd)
1579                 dm_exit();
1580         return r;
1581 }
1582
1583 int crypt_resume_by_passphrase(struct crypt_device *cd,
1584                                const char *name,
1585                                int keyslot,
1586                                const char *passphrase,
1587                                size_t passphrase_size)
1588 {
1589         struct volume_key *vk = NULL;
1590         int r, suspended = 0;
1591
1592         log_dbg("Resuming volume %s.", name);
1593
1594         if (!isLUKS(cd->type)) {
1595                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1596                 r = -EINVAL;
1597                 goto out;
1598         }
1599
1600         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1601                             NULL, NULL, NULL, NULL, &suspended, NULL);
1602         if (r < 0)
1603                 return r;
1604
1605         if (!suspended) {
1606                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1607                 return -EINVAL;
1608         }
1609
1610         if (passphrase) {
1611                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1612                                            passphrase_size, &cd->hdr, &vk, cd);
1613         } else
1614                 r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1615
1616         if (r >= 0) {
1617                 keyslot = r;
1618                 r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1619                 if (r == -ENOTSUP)
1620                         log_err(cd, "Resume is not supported for device %s.\n", name);
1621                 else if (r)
1622                         log_err(cd, "Error during resuming device %s.\n", name);
1623         } else
1624                 r = keyslot;
1625 out:
1626         crypt_free_volume_key(vk);
1627         return r < 0 ? r : keyslot;
1628 }
1629
1630 int crypt_resume_by_keyfile(struct crypt_device *cd,
1631                             const char *name,
1632                             int keyslot,
1633                             const char *keyfile,
1634                             size_t keyfile_size)
1635 {
1636         struct volume_key *vk = NULL;
1637         char *passphrase_read = NULL;
1638         size_t passphrase_size_read;
1639         int r, suspended = 0;
1640
1641         log_dbg("Resuming volume %s.", name);
1642
1643         if (!isLUKS(cd->type)) {
1644                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1645                 r = -EINVAL;
1646                 goto out;
1647         }
1648
1649         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1650                             NULL, NULL, NULL, NULL, &suspended, NULL);
1651         if (r < 0)
1652                 return r;
1653
1654         if (!suspended) {
1655                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1656                 return -EINVAL;
1657         }
1658
1659         if (!keyfile)
1660                 return -EINVAL;
1661
1662         r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1663                           &passphrase_size_read, keyfile, keyfile_size);
1664         if (r < 0)
1665                 goto out;
1666
1667         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1668                                    passphrase_size_read, &cd->hdr, &vk, cd);
1669         if (r < 0)
1670                 goto out;
1671
1672         keyslot = r;
1673         r = dm_resume_and_reinstate_key(name, vk->keylength, vk->key);
1674         if (r)
1675                 log_err(cd, "Error during resuming device %s.\n", name);
1676 out:
1677         crypt_safe_free(passphrase_read);
1678         crypt_free_volume_key(vk);
1679         return r < 0 ? r : keyslot;
1680 }
1681
1682 // slot manipulation
1683 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1684         int keyslot, // -1 any
1685         const char *passphrase, // NULL -> terminal
1686         size_t passphrase_size,
1687         const char *new_passphrase, // NULL -> terminal
1688         size_t new_passphrase_size)
1689 {
1690         struct volume_key *vk = NULL;
1691         char *password = NULL, *new_password = NULL;
1692         size_t passwordLen, new_passwordLen;
1693         int r;
1694
1695         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1696                 "new passphrase %sprovided.",
1697                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1698
1699         if (!isLUKS(cd->type)) {
1700                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1701                 return -EINVAL;
1702         }
1703
1704         r = keyslot_verify_or_find_empty(cd, &keyslot);
1705         if (r)
1706                 return r;
1707
1708         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1709                 /* No slots used, try to use pre-generated key in header */
1710                 if (cd->volume_key) {
1711                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1712                         r = vk ? 0 : -ENOMEM;
1713                 } else {
1714                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1715                         return -EINVAL;
1716                 }
1717         } else if (passphrase) {
1718                 /* Passphrase provided, use it to unlock existing keyslot */
1719                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1720                                            passphrase_size, &cd->hdr, &vk, cd);
1721         } else {
1722                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1723                 r = key_from_terminal(cd, _("Enter any passphrase: "),
1724                                       &password, &passwordLen, 0);
1725                 if (r < 0)
1726                         goto out;
1727
1728                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1729                                            passwordLen, &cd->hdr, &vk, cd);
1730                 crypt_safe_free(password);
1731         }
1732
1733         if(r < 0)
1734                 goto out;
1735
1736         if (new_passphrase) {
1737                 new_password = (char *)new_passphrase;
1738                 new_passwordLen = new_passphrase_size;
1739         } else {
1740                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1741                                       &new_password, &new_passwordLen, 1);
1742                 if(r < 0)
1743                         goto out;
1744         }
1745
1746         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1747                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1748         if(r < 0) goto out;
1749
1750         r = 0;
1751 out:
1752         if (!new_passphrase)
1753                 crypt_safe_free(new_password);
1754         crypt_free_volume_key(vk);
1755         return r ?: keyslot;
1756 }
1757
1758 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1759         int keyslot,
1760         const char *keyfile,
1761         size_t keyfile_size,
1762         const char *new_keyfile,
1763         size_t new_keyfile_size)
1764 {
1765         struct volume_key *vk = NULL;
1766         char *password = NULL; size_t passwordLen;
1767         char *new_password = NULL; size_t new_passwordLen;
1768         int r;
1769
1770         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1771                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1772
1773         if (!isLUKS(cd->type)) {
1774                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1775                 return -EINVAL;
1776         }
1777
1778         r = keyslot_verify_or_find_empty(cd, &keyslot);
1779         if (r)
1780                 return r;
1781
1782         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1783                 /* No slots used, try to use pre-generated key in header */
1784                 if (cd->volume_key) {
1785                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1786                         r = vk ? 0 : -ENOMEM;
1787                 } else {
1788                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1789                         return -EINVAL;
1790                 }
1791         } else {
1792                 /* Read password from file of (if NULL) from terminal */
1793                 if (keyfile)
1794                         r = key_from_file(cd, _("Enter any passphrase: "),
1795                                           &password, &passwordLen,
1796                                           keyfile, keyfile_size);
1797                 else
1798                         r = key_from_terminal(cd, _("Enter any passphrase: "),
1799                                               &password, &passwordLen, 0);
1800                 if (r < 0)
1801                         goto out;
1802
1803                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1804                                            &cd->hdr, &vk, cd);
1805         }
1806
1807         if(r < 0)
1808                 goto out;
1809
1810         if (new_keyfile)
1811                 r = key_from_file(cd, _("Enter new passphrase for key slot: "),
1812                                   &new_password, &new_passwordLen, new_keyfile,
1813                                   new_keyfile_size);
1814         else
1815                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1816                                       &new_password, &new_passwordLen, 1);
1817         if (r < 0)
1818                 goto out;
1819
1820         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1821                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1822 out:
1823         crypt_safe_free(password);
1824         crypt_safe_free(new_password);
1825         crypt_free_volume_key(vk);
1826         return r < 0 ? r : keyslot;
1827 }
1828
1829 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1830         int keyslot,
1831         const char *volume_key,
1832         size_t volume_key_size,
1833         const char *passphrase,
1834         size_t passphrase_size)
1835 {
1836         struct volume_key *vk = NULL;
1837         int r = -EINVAL;
1838         char *new_password = NULL; size_t new_passwordLen;
1839
1840         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1841
1842         if (!isLUKS(cd->type)) {
1843                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1844                 return -EINVAL;
1845         }
1846
1847         if (volume_key)
1848                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
1849         else if (cd->volume_key)
1850                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
1851
1852         if (!vk)
1853                 return -ENOMEM;
1854
1855         r = LUKS_verify_volume_key(&cd->hdr, vk);
1856         if (r < 0) {
1857                 log_err(cd, _("Volume key does not match the volume.\n"));
1858                 goto out;
1859         }
1860
1861         r = keyslot_verify_or_find_empty(cd, &keyslot);
1862         if (r)
1863                 goto out;
1864
1865         if (!passphrase) {
1866                 r = key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1867                                       &new_password, &new_passwordLen, 1);
1868                 if (r < 0)
1869                         goto out;
1870                 passphrase = new_password;
1871                 passphrase_size = new_passwordLen;
1872         }
1873
1874         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1875                          &cd->hdr, vk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1876 out:
1877         crypt_safe_free(new_password);
1878         crypt_free_volume_key(vk);
1879         return (r < 0) ? r : keyslot;
1880 }
1881
1882 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1883 {
1884         crypt_keyslot_info ki;
1885
1886         log_dbg("Destroying keyslot %d.", keyslot);
1887
1888         if (!isLUKS(cd->type)) {
1889                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1890                 return -EINVAL;
1891         }
1892
1893         ki = crypt_keyslot_status(cd, keyslot);
1894         if (ki == CRYPT_SLOT_INVALID) {
1895                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1896                 return -EINVAL;
1897         }
1898
1899         if (ki == CRYPT_SLOT_INACTIVE) {
1900                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1901                 return -EINVAL;
1902         }
1903
1904         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1905 }
1906
1907 // activation/deactivation of device mapping
1908 int crypt_activate_by_passphrase(struct crypt_device *cd,
1909         const char *name,
1910         int keyslot,
1911         const char *passphrase,
1912         size_t passphrase_size,
1913         uint32_t flags)
1914 {
1915         crypt_status_info ci;
1916         struct volume_key *vk = NULL;
1917         char *read_passphrase = NULL;
1918         size_t passphraseLen = 0;
1919         int r;
1920
1921         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1922                 name ? "Activating" : "Checking", name ?: "",
1923                 keyslot, passphrase ? "" : "[none] ");
1924
1925         if (name) {
1926                 ci = crypt_status(NULL, name);
1927                 if (ci == CRYPT_INVALID)
1928                         return -EINVAL;
1929                 else if (ci >= CRYPT_ACTIVE) {
1930                         log_err(cd, _("Device %s already exists.\n"), name);
1931                         return -EEXIST;
1932                 }
1933         }
1934
1935         /* plain, use hashed passphrase */
1936         if (isPLAIN(cd->type)) {
1937                 if (!passphrase) {
1938                         r = key_from_terminal(cd, NULL, &read_passphrase,
1939                                               &passphraseLen, 0);
1940                         if (r < 0)
1941                                 goto out;
1942                         passphrase = read_passphrase;
1943                         passphrase_size = passphraseLen;
1944                 }
1945                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
1946                                          cd->plain_cipher, cd->plain_cipher_mode,
1947                                          NULL, passphrase, passphrase_size,
1948                                          cd->volume_key->keylength, 0,
1949                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
1950                                          cd->plain_uuid,
1951                                          flags & CRYPT_ACTIVATE_READONLY, 0);
1952                 keyslot = 0;
1953         } else if (isLUKS(cd->type)) {
1954                 /* provided passphrase, do not retry */
1955                 if (passphrase) {
1956                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1957                                                    passphrase_size, &cd->hdr, &vk, cd);
1958                 } else
1959                         r = volume_key_by_terminal_passphrase(cd, keyslot, &vk);
1960
1961                 if (r >= 0) {
1962                         keyslot = r;
1963                         if (name)
1964                                 r = open_from_hdr_and_vk(cd, vk, name, flags);
1965                 }
1966         } else
1967                 r = -EINVAL;
1968 out:
1969         crypt_safe_free(read_passphrase);
1970         crypt_free_volume_key(vk);
1971
1972         return r < 0  ? r : keyslot;
1973 }
1974
1975 int crypt_activate_by_keyfile(struct crypt_device *cd,
1976         const char *name,
1977         int keyslot,
1978         const char *keyfile,
1979         size_t keyfile_size,
1980         uint32_t flags)
1981 {
1982         crypt_status_info ci;
1983         struct volume_key *vk = NULL;
1984         char *passphrase_read = NULL;
1985         size_t passphrase_size_read;
1986         unsigned int key_count = 0;
1987         int r;
1988
1989         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1990                 name ?: "", keyslot, keyfile ?: "[none]");
1991
1992         if (name) {
1993                 ci = crypt_status(NULL, name);
1994                 if (ci == CRYPT_INVALID)
1995                         return -EINVAL;
1996                 else if (ci >= CRYPT_ACTIVE) {
1997                         log_err(cd, _("Device %s already exists.\n"), name);
1998                         return -EEXIST;
1999                 }
2000         }
2001
2002         if (!keyfile)
2003                 return -EINVAL;
2004
2005         if (isPLAIN(cd->type)) {
2006                 if (cd->plain_hdr.hash)
2007                         r = crypt_get_key(_("Enter passphrase: "),
2008                                           &passphrase_read, &passphrase_size_read,
2009                                           0, keyfile, cd->timeout, 0, cd);
2010                 else
2011                         r = key_from_file(cd, _("Enter passphrase: "),
2012                                           &passphrase_read, &passphrase_size_read,
2013                                           keyfile, keyfile_size);
2014                 if (r < 0)
2015                         goto out;
2016                 r = create_device_helper(cd, name, cd->plain_hdr.hash,
2017                                          cd->plain_cipher, cd->plain_cipher_mode,
2018                                          NULL, passphrase_read, passphrase_size_read,
2019                                          cd->volume_key->keylength, 0,
2020                                          cd->plain_hdr.skip, cd->plain_hdr.offset,
2021                                          cd->plain_uuid,
2022                                          flags & CRYPT_ACTIVATE_READONLY, 0);
2023         } else if (isLUKS(cd->type)) {
2024                 r = key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
2025                           &passphrase_size_read, keyfile, keyfile_size);
2026                 if (r < 0)
2027                         goto out;
2028                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
2029                                            passphrase_size_read, &cd->hdr, &vk, cd);
2030                 if (r < 0)
2031                         goto out;
2032                 keyslot = r;
2033
2034                 if (name) {
2035                         r = open_from_hdr_and_vk(cd, vk, name, flags);
2036                         if (r < 0)
2037                                 goto out;
2038                 }
2039                 r = keyslot;
2040         } else if (isLOOPAES(cd->type)) {
2041                 r = key_from_file(cd, NULL, &passphrase_read, &passphrase_size_read,
2042                                   keyfile, keyfile_size);
2043                 if (r < 0)
2044                         goto out;
2045                 r = LOOPAES_parse_keyfile(cd, &vk, cd->loopaes_hdr.hash, &key_count,
2046                                           passphrase_read, passphrase_size_read);
2047                 if (r < 0)
2048                         goto out;
2049                 if (name)
2050                         r = LOOPAES_activate(cd, name, cd->loopaes_cipher,
2051                                              key_count, vk,
2052                                              cd->loopaes_hdr.offset,
2053                                              cd->loopaes_hdr.skip,
2054                                              flags);
2055         } else
2056                 r = -EINVAL;
2057
2058 out:
2059         crypt_safe_free(passphrase_read);
2060         crypt_free_volume_key(vk);
2061
2062         return r;
2063 }
2064
2065 int crypt_activate_by_volume_key(struct crypt_device *cd,
2066         const char *name,
2067         const char *volume_key,
2068         size_t volume_key_size,
2069         uint32_t flags)
2070 {
2071         crypt_status_info ci;
2072         struct volume_key *vk;
2073         int r;
2074
2075         log_dbg("Activating volume %s by volume key.", name);
2076
2077         /* use key directly, no hash */
2078         if (isPLAIN(cd->type)) {
2079                 if (!volume_key || !volume_key_size || !cd->volume_key ||
2080                         volume_key_size != cd->volume_key->keylength) {
2081                         log_err(cd, _("Incorrect volume key specified for plain device.\n"));
2082                         return -EINVAL;
2083                 }
2084
2085                 return create_device_helper(cd, name, NULL,
2086                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
2087                         cd->volume_key->keylength, 0, cd->plain_hdr.skip,
2088                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0);
2089         }
2090
2091         if (!isLUKS(cd->type)) {
2092                 log_err(cd, _("Device type is not properly initialised.\n"));
2093                 return -EINVAL;
2094         }
2095
2096         if (name) {
2097                 ci = crypt_status(NULL, name);
2098                 if (ci == CRYPT_INVALID)
2099                         return -EINVAL;
2100                 else if (ci >= CRYPT_ACTIVE) {
2101                         log_err(cd, _("Device %s already exists.\n"), name);
2102                         return -EEXIST;
2103                 }
2104         }
2105
2106         /* If key is not provided, try to use internal key */
2107         if (!volume_key) {
2108                 if (!cd->volume_key) {
2109                         log_err(cd, _("Volume key does not match the volume.\n"));
2110                         return -EINVAL;
2111                 }
2112                 volume_key_size = cd->volume_key->keylength;
2113                 volume_key = cd->volume_key->key;
2114         }
2115
2116         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2117         if (!vk)
2118                 return -ENOMEM;
2119         r = LUKS_verify_volume_key(&cd->hdr, vk);
2120
2121         if (r == -EPERM)
2122                 log_err(cd, _("Volume key does not match the volume.\n"));
2123
2124         if (!r && name)
2125                 r = open_from_hdr_and_vk(cd, vk, name, flags);
2126
2127         crypt_free_volume_key(vk);
2128
2129         return r;
2130 }
2131
2132 int crypt_deactivate(struct crypt_device *cd, const char *name)
2133 {
2134         int r;
2135
2136         if (!name)
2137                 return -EINVAL;
2138
2139         log_dbg("Deactivating volume %s.", name);
2140
2141         if (!cd && dm_init(NULL, 1) < 0)
2142                 return -ENOSYS;
2143
2144         switch (crypt_status(cd, name)) {
2145                 case CRYPT_ACTIVE:
2146                         r = dm_remove_device(name, 0, 0);
2147                         break;
2148                 case CRYPT_BUSY:
2149                         log_err(cd, _("Device %s is busy.\n"), name);
2150                         r = -EBUSY;
2151                         break;
2152                 case CRYPT_INACTIVE:
2153                         log_err(cd, _("Device %s is not active.\n"), name);
2154                         r = -ENODEV;
2155                         break;
2156                 default:
2157                         log_err(cd, _("Invalid device %s.\n"), name);
2158                         r = -EINVAL;
2159         }
2160
2161         if (!cd)
2162                 dm_exit();
2163
2164         return r;
2165 }
2166
2167 int crypt_volume_key_get(struct crypt_device *cd,
2168         int keyslot,
2169         char *volume_key,
2170         size_t *volume_key_size,
2171         const char *passphrase,
2172         size_t passphrase_size)
2173 {
2174         struct volume_key *vk;
2175         char *processed_key = NULL;
2176         unsigned key_len;
2177         int r;
2178
2179         key_len = crypt_get_volume_key_size(cd);
2180         if (key_len > *volume_key_size) {
2181                 log_err(cd, _("Volume key buffer too small.\n"));
2182                 return -ENOMEM;
2183         }
2184
2185         if (isPLAIN(cd->type) && cd->plain_hdr.hash) {
2186                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
2187                                             passphrase, passphrase_size);
2188                 if (!processed_key) {
2189                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
2190                         return -EINVAL;
2191                 }
2192                 memcpy(volume_key, processed_key, key_len);
2193                 *volume_key_size = key_len;
2194                 crypt_safe_free(processed_key);
2195                 return 0;
2196         }
2197
2198         if (isLUKS(cd->type)) {
2199                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
2200                                         passphrase_size, &cd->hdr, &vk, cd);
2201
2202                 if (r >= 0) {
2203                         memcpy(volume_key, vk->key, vk->keylength);
2204                         *volume_key_size = vk->keylength;
2205                 }
2206
2207                 crypt_free_volume_key(vk);
2208                 return r;
2209         }
2210
2211         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
2212         return -EINVAL;
2213 }
2214
2215 int crypt_volume_key_verify(struct crypt_device *cd,
2216         const char *volume_key,
2217         size_t volume_key_size)
2218 {
2219         struct volume_key *vk;
2220         int r;
2221
2222         if (!isLUKS(cd->type)) {
2223                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2224                 return -EINVAL;
2225         }
2226
2227         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
2228         if (!vk)
2229                 return -ENOMEM;
2230
2231         r = LUKS_verify_volume_key(&cd->hdr, vk);
2232
2233         if (r == -EPERM)
2234                 log_err(cd, _("Volume key does not match the volume.\n"));
2235
2236         crypt_free_volume_key(vk);
2237
2238         return r;
2239 }
2240
2241 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
2242 {
2243         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
2244         cd->timeout = timeout_sec;
2245 }
2246
2247 void crypt_set_password_retry(struct crypt_device *cd, int tries)
2248 {
2249         log_dbg("Password retry count set to %d.", tries);
2250         cd->tries = tries;
2251 }
2252
2253 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
2254 {
2255         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
2256         cd->iteration_time = iteration_time_ms;
2257 }
2258
2259 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
2260 {
2261         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
2262         cd->password_verify = password_verify ? 1 : 0;
2263 }
2264
2265 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
2266 {
2267         switch (rng_type) {
2268         case CRYPT_RNG_URANDOM:
2269         case CRYPT_RNG_RANDOM:
2270                 log_dbg("RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
2271                 cd->rng_type = rng_type;
2272         }
2273 }
2274
2275 int crypt_get_rng_type(struct crypt_device *cd)
2276 {
2277         if (!cd)
2278                 return -EINVAL;
2279
2280         return cd->rng_type;
2281 }
2282
2283 int crypt_memory_lock(struct crypt_device *cd, int lock)
2284 {
2285         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
2286 }
2287
2288 // reporting
2289 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
2290 {
2291         int r;
2292
2293         if (!cd && dm_init(NULL, 1) < 0)
2294                 return CRYPT_INVALID;
2295
2296         r = dm_status_device(name);
2297
2298         if (!cd)
2299                 dm_exit();
2300
2301         if (r < 0 && r != -ENODEV)
2302                 return CRYPT_INVALID;
2303
2304         if (r == 0)
2305                 return CRYPT_ACTIVE;
2306
2307         if (r > 0)
2308                 return CRYPT_BUSY;
2309
2310         return CRYPT_INACTIVE;
2311 }
2312
2313 static void hexprintICB(struct crypt_device *cd, char *d, int n)
2314 {
2315         int i;
2316         for(i = 0; i < n; i++)
2317                 log_std(cd, "%02hhx ", (char)d[i]);
2318 }
2319
2320 int crypt_dump(struct crypt_device *cd)
2321 {
2322         int i;
2323         if (!isLUKS(cd->type)) { //FIXME
2324                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2325                 return -EINVAL;
2326         }
2327
2328         log_std(cd, "LUKS header information for %s\n\n", cd->device);
2329         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
2330         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
2331         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
2332         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
2333         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
2334         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
2335         log_std(cd, "MK digest:     \t");
2336         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
2337         log_std(cd, "\n");
2338         log_std(cd, "MK salt:       \t");
2339         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
2340         log_std(cd, "\n               \t");
2341         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2342         log_std(cd, "\n");
2343         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
2344         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
2345         for(i = 0; i < LUKS_NUMKEYS; i++) {
2346                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
2347                         log_std(cd, "Key Slot %d: ENABLED\n",i);
2348                         log_std(cd, "\tIterations:         \t%d\n",
2349                                 cd->hdr.keyblock[i].passwordIterations);
2350                         log_std(cd, "\tSalt:               \t");
2351                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
2352                                     LUKS_SALTSIZE/2);
2353                         log_std(cd, "\n\t                      \t");
2354                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
2355                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
2356                         log_std(cd, "\n");
2357
2358                         log_std(cd, "\tKey material offset:\t%d\n",
2359                                 cd->hdr.keyblock[i].keyMaterialOffset);
2360                         log_std(cd, "\tAF stripes:            \t%d\n",
2361                                 cd->hdr.keyblock[i].stripes);
2362                 }
2363                 else 
2364                         log_std(cd, "Key Slot %d: DISABLED\n", i);
2365         }
2366
2367         return 0;
2368 }
2369
2370 const char *crypt_get_cipher(struct crypt_device *cd)
2371 {
2372         if (isPLAIN(cd->type))
2373                 return cd->plain_cipher;
2374
2375         if (isLUKS(cd->type))
2376                 return cd->hdr.cipherName;
2377
2378         if (isLOOPAES(cd->type))
2379                 return cd->loopaes_cipher;
2380
2381         return NULL;
2382 }
2383
2384 const char *crypt_get_cipher_mode(struct crypt_device *cd)
2385 {
2386         if (isPLAIN(cd->type))
2387                 return cd->plain_cipher_mode;
2388
2389         if (isLUKS(cd->type))
2390                 return cd->hdr.cipherMode;
2391
2392         if (isLOOPAES(cd->type))
2393                 return cd->loopaes_cipher_mode;
2394
2395         return NULL;
2396 }
2397
2398 const char *crypt_get_uuid(struct crypt_device *cd)
2399 {
2400         if (isLUKS(cd->type))
2401                 return cd->hdr.uuid;
2402
2403         if (isPLAIN(cd->type))
2404                 return cd->plain_uuid;
2405
2406         if (isLOOPAES(cd->type))
2407                 return cd->loopaes_uuid;
2408
2409         return NULL;
2410 }
2411
2412 const char *crypt_get_device_name(struct crypt_device *cd)
2413 {
2414         return cd->device;
2415 }
2416
2417 int crypt_get_volume_key_size(struct crypt_device *cd)
2418 {
2419         if (isPLAIN(cd->type) && cd->volume_key)
2420                 return cd->volume_key->keylength;
2421
2422         if (isLUKS(cd->type))
2423                 return cd->hdr.keyBytes;
2424
2425         if (isLOOPAES(cd->type))
2426                 return cd->loopaes_key_size;
2427
2428         return 0;
2429 }
2430
2431 uint64_t crypt_get_data_offset(struct crypt_device *cd)
2432 {
2433         if (isPLAIN(cd->type))
2434                 return cd->plain_hdr.offset;
2435
2436         if (isLUKS(cd->type))
2437                 return cd->hdr.payloadOffset;
2438
2439         if (isLOOPAES(cd->type))
2440                 return cd->loopaes_hdr.offset;
2441
2442         return 0;
2443 }
2444
2445 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
2446 {
2447         if (!isLUKS(cd->type)) {
2448                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
2449                 return CRYPT_SLOT_INVALID;
2450         }
2451
2452         return LUKS_keyslot_info(&cd->hdr, keyslot);
2453 }
2454
2455 int crypt_keyslot_max(const char *type)
2456 {
2457         if (type && isLUKS(type))
2458                 return LUKS_NUMKEYS;
2459
2460         return -EINVAL;
2461 }
2462
2463 const char *crypt_get_type(struct crypt_device *cd)
2464 {
2465         return cd->type;
2466 }
2467
2468 int crypt_get_active_device(struct crypt_device *cd __attribute__((unused)),
2469                             const char *name,
2470                             struct crypt_active_device *cad)
2471 {
2472         int r, readonly;
2473
2474         r = dm_query_device(name, NULL, &cad->size, &cad->iv_offset, &cad->offset,
2475                             NULL, NULL, NULL, &readonly, NULL, NULL);
2476         if (r < 0)
2477                 return r;
2478
2479         cad->flags = readonly ? CRYPT_ACTIVATE_READONLY : 0;
2480
2481         return 0;
2482 }