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