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