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