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