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