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