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