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