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