Properly apply versioned symbols in library and fix problems uncovered
[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, 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 void crypt_log(struct crypt_device *cd, int class, const char *msg)
51 {
52         if (cd && cd->log)
53                 cd->log(class, msg, cd->log_usrptr);
54         else if (_default_log)
55                 _default_log(class, msg, NULL);
56 }
57
58 void logger(struct crypt_device *cd, int class, const char *file,
59             int line, const char *format, ...)
60 {
61         va_list argp;
62         char *target = NULL;
63
64         va_start(argp, format);
65
66         if (vasprintf(&target, format, argp) > 0) {
67                 if (class >= 0) {
68                         crypt_log(cd, 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 int crypt_confirm(struct crypt_device *cd, const char *msg)
428 {
429         if (!cd || !cd->confirm)
430                 return 1;
431         else
432                 return cd->confirm(msg, cd->confirm_usrptr);
433 }
434
435 static void key_from_terminal(struct crypt_device *cd, char *msg, char **key,
436                               unsigned int *key_len, int force_verify)
437 {
438         int r, flags = 0;
439
440         if (cd->password) {
441                 *key = safe_alloc(MAX_TTY_PASSWORD_LEN);
442                 if (*key)
443                         return;
444                 r = cd->password(msg, *key, (size_t)key_len, cd->password_usrptr);
445                 if (r < 0) {
446                         safe_free(*key);
447                         *key = NULL;
448                 } else
449                         *key_len = r;
450         } else {
451                 if (force_verify || cd->password_verify)
452                         flags |= CRYPT_FLAG_VERIFY_IF_POSSIBLE;
453                 get_key(msg, key, key_len, 0, NULL, cd->timeout, flags, cd);
454         }
455 }
456
457 static int volume_key_by_terminal_passphrase(struct crypt_device *cd, int keyslot,
458                                              struct luks_masterkey **mk)
459 {
460         char *prompt = NULL, *passphrase_read = NULL;
461         unsigned int passphrase_size_read;
462         int r = -EINVAL, tries = cd->tries;
463
464         if(asprintf(&prompt, _("Enter passphrase for %s: "), cd->device) < 0)
465                 return -ENOMEM;
466
467         *mk = NULL;
468         do {
469                 if (*mk)
470                         LUKS_dealloc_masterkey(*mk);
471                 *mk = NULL;
472
473                 key_from_terminal(cd, prompt, &passphrase_read,
474                                   &passphrase_size_read, 0);
475                 if(!passphrase_read) {
476                         r = -EINVAL;
477                         break;
478                 }
479
480                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
481                                            passphrase_size_read, &cd->hdr, mk, cd);
482                 safe_free(passphrase_read);
483                 passphrase_read = NULL;
484         } while (r == -EPERM && (--tries > 0));
485
486         if (r < 0 && *mk) {
487                 LUKS_dealloc_masterkey(*mk);
488                 *mk = NULL;
489         }
490         free(prompt);
491
492         return r;
493
494 }
495
496 static void key_from_file(struct crypt_device *cd, char *msg,
497                           char **key, unsigned int *key_len,
498                           const char *key_file, size_t key_size)
499 {
500         get_key(msg, key, key_len, key_size, key_file, cd->timeout, 0, cd);
501 }
502
503 static int _crypt_init(struct crypt_device **cd,
504                        const char *type,
505                        struct crypt_options *options,
506                        int load, int need_dm)
507 {
508         int init_by_name, r;
509
510         /* if it is plain device and mapping table is being reloaded
511         initialize it by name*/
512         init_by_name = (type && !strcmp(type, CRYPT_PLAIN) && load);
513
514         /* Some of old API calls do not require DM in kernel,
515            fake initialisation by initialise it with kernel_check disabled */
516         if (!need_dm)
517                 (void)dm_init(NULL, 0);
518         if (init_by_name)
519                 r = crypt_init_by_name(cd, options->name);
520         else
521                 r = crypt_init(cd, options->device);
522         if (!need_dm)
523                 dm_exit();
524
525         if (r)
526                 return -EINVAL;
527
528         crypt_set_log_callback(*cd, log_wrapper, options->icb->log);
529         crypt_set_confirm_callback(*cd, yesDialog_wrapper, options->icb->yesDialog);
530
531         crypt_set_timeout(*cd, options->timeout);
532         crypt_set_password_retry(*cd, options->tries);
533         crypt_set_iterarion_time(*cd, options->iteration_time ?: 1000);
534         crypt_set_password_verify(*cd, options->flags & CRYPT_FLAG_VERIFY);
535
536         if (load && !init_by_name)
537                 r = crypt_load(*cd, type, NULL);
538
539         if (!r && type && !(*cd)->type) {
540                 (*cd)->type = strdup(type);
541                 if (!(*cd)->type)
542                         r = -ENOMEM;
543         }
544
545         if (r)
546                 crypt_free(*cd);
547
548         return r;
549 }
550
551 void crypt_set_log_callback(struct crypt_device *cd,
552         void (*log)(int class, const char *msg, void *usrptr),
553         void *usrptr)
554 {
555         if (!cd)
556                 _default_log = log;
557         else {
558                 cd->log = log;
559                 cd->log_usrptr = usrptr;
560         }
561 }
562
563 void crypt_set_confirm_callback(struct crypt_device *cd,
564         int (*confirm)(const char *msg, void *usrptr),
565         void *usrptr)
566 {
567         cd->confirm = confirm;
568         cd->confirm_usrptr = usrptr;
569 }
570
571 void crypt_set_password_callback(struct crypt_device *cd,
572         int (*password)(const char *msg, char *buf, size_t length, void *usrptr),
573         void *usrptr)
574 {
575         cd->password = password;
576         cd->password_usrptr = usrptr;
577 }
578
579 /* OPTIONS: name, cipher, device, hash, key_file, key_size, key_slot,
580  *          offset, size, skip, timeout, tries, passphrase_fd (ignored),
581  *          flags, icb */
582 int crypt_create_device(struct crypt_options *options)
583 {
584         struct crypt_device *cd = NULL;
585         char *key = NULL;
586         unsigned int keyLen;
587         int r;
588
589         r = _crypt_init(&cd, CRYPT_PLAIN, options, 0, 1);
590         if (r)
591                 return r;
592
593         get_key(_("Enter passphrase: "), &key, &keyLen, options->key_size,
594                 options->key_file, cd->timeout, options->flags, cd);
595         if (!key)
596                 r = -ENOENT;
597         else
598                 r = create_device_helper(cd, options->name, options->hash,
599                         options->cipher, NULL, options->key_file, key, keyLen,
600                         options->key_size, options->size, options->skip,
601                         options->offset, NULL, options->flags & CRYPT_FLAG_READONLY,
602                         options->flags, 0);
603
604         safe_free(key);
605         crypt_free(cd);
606         return r;
607 }
608
609 /* OPTIONS: same as create above */
610 int crypt_update_device(struct crypt_options *options)
611 {
612         struct crypt_device *cd = NULL;
613         char *key = NULL;
614         unsigned int keyLen;
615         int r;
616
617         r = _crypt_init(&cd, CRYPT_PLAIN, options, 1, 1);
618         if (r)
619                 return r;
620
621         get_key(_("Enter passphrase: "), &key, &keyLen, options->key_size,
622                 options->key_file, cd->timeout, options->flags, cd);
623         if (!key)
624                 r = -ENOENT;
625         else
626                 r = create_device_helper(cd, options->name, options->hash,
627                         options->cipher, NULL, options->key_file, key, keyLen,
628                         options->key_size, options->size, options->skip,
629                         options->offset, NULL, options->flags & CRYPT_FLAG_READONLY,
630                         options->flags, 1);
631
632         safe_free(key);
633         crypt_free(cd);
634         return r;
635 }
636
637 /* OPTIONS: name, size, icb */
638 int crypt_resize_device(struct crypt_options *options)
639 {
640         struct crypt_device *cd = NULL;
641         char *device = NULL, *cipher = NULL, *uuid = NULL, *key = NULL;
642         char *type = NULL;
643         uint64_t size, skip, offset;
644         int key_size, read_only, r;
645
646         r = dm_query_device(options->name, &device, &size, &skip, &offset,
647                             &cipher, &key_size, &key, &read_only, NULL, &uuid);
648         if (r < 0)
649                 goto out;
650
651         /* Try to determine type of device from UUID */
652         if (uuid) {
653                 if (!strncmp(uuid, CRYPT_PLAIN, strlen(CRYPT_PLAIN))) {
654                         type = CRYPT_PLAIN;
655                         free (uuid);
656                         uuid = NULL;
657                 } else if (!strncmp(uuid, CRYPT_LUKS1, strlen(CRYPT_LUKS1)))
658                         type = CRYPT_LUKS1;
659         }
660
661         r = _crypt_init(&cd, type, options, 1, 1);
662         if (r)
663                 goto out;
664
665         size = options->size;
666         r = device_check_and_adjust(cd, device, &size, &offset, &read_only);
667         if (r)
668                 goto out;
669
670         r = dm_create_device(options->name, device, cipher, type,
671                              crypt_get_uuid(cd), size, skip, offset,
672                              key_size, key, read_only, 1);
673 out:
674         safe_free(key);
675         free(cipher);
676         free(device);
677         free(uuid);
678         crypt_free(cd);
679         return r;
680 }
681
682 /* OPTIONS: name, icb */
683 int crypt_query_device(struct crypt_options *options)
684 {
685         int read_only, r;
686
687         r = dm_status_device(options->name);
688         if (r == -ENODEV)
689                 return 0;
690
691         r = dm_query_device(options->name, (char **)&options->device, &options->size,
692                             &options->skip, &options->offset, (char **)&options->cipher,
693                             &options->key_size, NULL, &read_only, NULL, NULL);
694
695         if (r < 0)
696                 return r;
697
698         if (read_only)
699                 options->flags |= CRYPT_FLAG_READONLY;
700
701         options->flags |= CRYPT_FLAG_FREE_DEVICE;
702         options->flags |= CRYPT_FLAG_FREE_CIPHER;
703
704         return 1;
705 }
706
707 /* OPTIONS: name, icb */
708 int crypt_remove_device(struct crypt_options *options)
709 {
710         struct crypt_device *cd = NULL;
711         int r;
712
713         r = crypt_init_by_name(&cd, options->name);
714         if (r)
715                 return r;
716
717         r = crypt_deactivate(cd, options->name);
718
719         crypt_free(cd);
720         return r;
721
722 }
723
724 /* OPTIONS: device, cipher, hash, align_payload, key_size (master key), key_slot
725  *          new_key_file, iteration_time, timeout, flags, icb */
726 int crypt_luksFormat(struct crypt_options *options)
727 {
728         char cipherName[LUKS_CIPHERNAME_L];
729         char cipherMode[LUKS_CIPHERMODE_L];
730         char *password=NULL;
731         unsigned int passwordLen;
732         struct crypt_device *cd;
733         struct crypt_params_luks1 cp = {
734                 .hash = options->hash,
735                 .data_alignment = options->align_payload
736         };
737         int r;
738
739         r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
740         if(r < 0) {
741                 log_err(cd, _("No known cipher specification pattern detected.\n"));
742                 return r;
743         }
744
745         if ((r = _crypt_init(&cd, CRYPT_LUKS1, options, 0, 1)))
746                 return r;
747
748         if (options->key_slot >= LUKS_NUMKEYS && options->key_slot != CRYPT_ANY_SLOT) {
749                 log_err(cd, _("Key slot %d is invalid, please select between 0 and %d.\n"),
750                         options->key_slot, LUKS_NUMKEYS - 1);
751                 r = -EINVAL;
752                 goto out;
753         }
754
755         get_key(_("Enter LUKS passphrase: "), &password, &passwordLen, 0,
756                 options->new_key_file, options->timeout, options->flags, cd);
757
758         if(!password) {
759                 r = -EINVAL;
760                 goto out;
761         }
762
763         r = crypt_format(cd, CRYPT_LUKS1, cipherName, cipherMode,
764                          NULL, NULL, options->key_size, &cp);
765         if (r < 0)
766                 goto out;
767
768         /* Add keyslot using internally stored volume key generated during format */
769         r = crypt_keyslot_add_by_volume_key(cd, options->key_slot, NULL, 0,
770                                             password, passwordLen);
771 out:
772         crypt_free(cd);
773         safe_free(password);
774         return (r < 0) ? r : 0;
775 }
776
777 /* OPTIONS: name, device, key_size, key_file, timeout, tries, flags, icb */
778 int crypt_luksOpen(struct crypt_options *options)
779 {
780         struct crypt_device *cd = NULL;
781         uint32_t flags = 0;
782         int r;
783
784         if (!options->name)
785                 return -EINVAL;
786
787         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
788         if (r)
789                 return r;
790
791         if (options->flags & CRYPT_FLAG_READONLY)
792                 flags |= CRYPT_ACTIVATE_READONLY;
793
794         if (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS)
795                 flags |= CRYPT_ACTIVATE_NO_UUID;
796
797         if (options->key_file)
798                 r = crypt_activate_by_keyfile(cd, options->name,
799                         CRYPT_ANY_SLOT, options->key_file, options->key_size,
800                         flags);
801         else
802                 r = crypt_activate_by_passphrase(cd, options->name,
803                         CRYPT_ANY_SLOT, options->passphrase,
804                         options->passphrase ? strlen(options->passphrase) : 0,
805                         flags);
806
807         crypt_free(cd);
808         return (r < 0) ? r : 0;
809 }
810
811 /* OPTIONS: device, keys_slot, key_file, timeout, flags, icb */
812 int crypt_luksKillSlot(struct crypt_options *options)
813 {
814         struct crypt_device *cd = NULL;
815         int r;
816
817         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
818         if (r)
819                 return r;
820
821         r = luks_remove_helper(cd, options->key_slot, options->key_file, NULL,
822                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
823
824         crypt_free(cd);
825         return (r < 0) ? r : 0;
826 }
827
828 /* OPTIONS: device, new_key_file, key_file, timeout, flags, icb */
829 int crypt_luksRemoveKey(struct crypt_options *options)
830 {
831         struct crypt_device *cd = NULL;
832         int r;
833
834         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
835         if (r)
836                 return r;
837
838         r = luks_remove_helper(cd, CRYPT_ANY_SLOT, options->key_file, options->new_key_file,
839                                options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY);
840
841         crypt_free(cd);
842         return (r < 0) ? r : 0;
843 }
844
845
846 /* OPTIONS: device, new_key_file, key_file, key_slot, flags,
847             iteration_time, timeout, icb */
848 int crypt_luksAddKey(struct crypt_options *options)
849 {
850         struct crypt_device *cd = NULL;
851         int r = -EINVAL;
852
853         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 1);
854         if (r)
855                 return r;
856
857         if (options->key_file || options->new_key_file)
858                 r = crypt_keyslot_add_by_keyfile(cd, options->key_slot,
859                                                  options->key_file, 0,
860                                                  options->new_key_file, 0);
861         else
862                 r = crypt_keyslot_add_by_passphrase(cd, options->key_slot,
863                                                     NULL, 0, NULL, 0);
864
865         crypt_free(cd);
866         return (r < 0) ? r : 0;
867 }
868
869 /* OPTIONS: device, icb */
870 int crypt_luksUUID(struct crypt_options *options)
871 {
872         struct crypt_device *cd = NULL;
873         char *uuid;
874         int r;
875
876         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
877         if (r)
878                 return r;
879
880         uuid = (char *)crypt_get_uuid(cd);
881         log_std(cd, uuid ?: "");
882         log_std(cd, "\n");
883         crypt_free(cd);
884         return 0;
885 }
886
887 /* OPTIONS: device, icb */
888 int crypt_isLuks(struct crypt_options *options)
889 {
890         struct crypt_device *cd = NULL;
891         int r;
892
893         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
894         if (!r)
895                 crypt_free(cd);
896         return r;
897 }
898
899 /* OPTIONS: device, icb */
900 int crypt_luksDump(struct crypt_options *options)
901 {
902         struct crypt_device *cd = NULL;
903         int r;
904
905         r = _crypt_init(&cd, CRYPT_LUKS1, options, 1, 0);
906         if(r < 0)
907                 return r;
908
909         r = crypt_dump(cd);
910
911         crypt_free(cd);
912         return 0;
913 }
914
915 void crypt_get_error(char *buf, size_t size)
916 {
917         const char *error = get_error();
918
919         if (!buf || size < 1)
920                 set_error(NULL);
921         else if (error) {
922                 strncpy(buf, error, size - 1);
923                 buf[size - 1] = '\0';
924                 set_error(NULL);
925         } else
926                 buf[0] = '\0';
927 }
928
929 void crypt_put_options(struct crypt_options *options)
930 {
931         if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
932                 free((char *)options->device);
933                 options->device = NULL;
934                 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
935         }
936         if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
937                 free((char *)options->cipher);
938                 options->cipher = NULL;
939                 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
940         }
941 }
942
943 const char *crypt_get_dir(void)
944 {
945         return dm_get_dir();
946 }
947
948 /////////////////////////////////
949 //
950 // New API
951 //
952
953 int crypt_init(struct crypt_device **cd, const char *device)
954 {
955         struct crypt_device *h = NULL;
956
957         if (!cd)
958                 return -EINVAL;
959
960         log_dbg("Allocating crypt device %s context.", device);
961
962         if (!device_ready(NULL, device, O_RDONLY))
963                 return -ENOTBLK;
964
965         if (!(h = malloc(sizeof(struct crypt_device))))
966                 return -ENOMEM;
967
968         memset(h, 0, sizeof(*h));
969
970         h->device = strdup(device);
971         if (!h->device) {
972                 free(h);
973                 return -ENOMEM;
974         }
975
976         if (!dm_init(h, 1) < 0) {
977                 free(h);
978                 return -ENOSYS;
979         }
980
981         h->iteration_time = 1000;
982         h->password_verify = 0;
983         h->tries = 3;
984         *cd = h;
985         return 0;
986 }
987
988 int crypt_init_by_name(struct crypt_device **cd, const char *name)
989 {
990         crypt_status_info ci;
991         char *device = NULL;
992         int r;
993
994         log_dbg("Allocating crypt device context by device %s.", name);
995
996         ci = crypt_status(NULL, name);
997         if (ci < ACTIVE) {
998                 log_err(NULL, _("Device %s is not active.\n"), name);
999                 return -ENODEV;
1000         }
1001
1002         r = dm_query_device(name, &device, NULL, NULL, NULL,
1003                             NULL, NULL, NULL, NULL, NULL, NULL);
1004         if (r >= 0)
1005                 r = crypt_init(cd, device);
1006
1007         free(device);
1008         return r;
1009 }
1010
1011 static int _crypt_format_plain(struct crypt_device *cd,
1012                                const char *cipher,
1013                                const char *cipher_mode,
1014                                const char *uuid,
1015                                struct crypt_params_plain *params)
1016 {
1017         if (!cipher || !cipher_mode || !params || !params->hash) {
1018                 log_err(cd, _("Invalid plain crypt parameters.\n"));
1019                 return -EINVAL;
1020         }
1021
1022         if (cd->volume_key->keyLength > 1024) {
1023                 log_err(cd, _("Invalid key size.\n"));
1024                 return -EINVAL;
1025         }
1026
1027         cd->plain_cipher = strdup(cipher);
1028         cd->plain_cipher_mode = strdup(cipher_mode);
1029
1030         if (uuid)
1031                 cd->plain_uuid = strdup(uuid);
1032
1033         if (params->hash)
1034                 cd->plain_hdr.hash = strdup(params->hash);
1035
1036         cd->plain_hdr.offset = params->offset;
1037         cd->plain_hdr.skip = params->skip;
1038
1039         if ((params->hash && !cd->plain_hdr.hash) ||
1040             !cd->plain_cipher || !cd->plain_cipher_mode)
1041                 return -ENOMEM;
1042
1043         return 0;
1044 }
1045
1046 static int _crypt_format_luks1(struct crypt_device *cd,
1047                                const char *cipher,
1048                                const char *cipher_mode,
1049                                const char *uuid,
1050                                struct crypt_params_luks1 *params)
1051 {
1052         int r;
1053
1054         r = LUKS_generate_phdr(&cd->hdr, cd->volume_key, cipher, cipher_mode,
1055                                (params && params->hash) ? params->hash : "sha1",
1056                                uuid, LUKS_STRIPES,
1057                                params ? params->data_alignment: DEFAULT_ALIGNMENT, cd);
1058         if(r < 0)
1059                 return r;
1060
1061         /* Wipe first 8 sectors - fs magic numbers etc. */
1062         r = wipe_device_header(cd->device, 8);
1063         if(r < 0) {
1064                 log_err(cd, _("Can't wipe header on device %s.\n"), cd->device);
1065                 return r;
1066         }
1067
1068         r = LUKS_write_phdr(cd->device, &cd->hdr, cd);
1069
1070         return r;
1071 }
1072
1073 int crypt_format(struct crypt_device *cd,
1074         const char *type,
1075         const char *cipher,
1076         const char *cipher_mode,
1077         const char *uuid,
1078         const char *volume_key,
1079         size_t volume_key_size,
1080         void *params)
1081 {
1082         int r;
1083
1084         log_dbg("Formatting device %s as type %s.", cd->device, cd->type ?: "(none)");
1085
1086         if (!type)
1087                 return -EINVAL;
1088
1089         if (volume_key)
1090                 cd->volume_key = LUKS_alloc_masterkey(volume_key_size, 
1091                                                       volume_key);
1092         else
1093                 cd->volume_key = LUKS_generate_masterkey(volume_key_size);
1094
1095         if(!cd->volume_key)
1096                 return -ENOMEM;
1097
1098         if (isPLAIN(type))
1099                 r = _crypt_format_plain(cd, cipher, cipher_mode,
1100                                         uuid, params);
1101         else if (isLUKS(type))
1102                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
1103                                         uuid, params);
1104         else {
1105                 /* FIXME: allow plugins here? */
1106                 log_err(cd, _("Unkown crypt device type %s requesed.\n"), type);
1107                 r = -EINVAL;
1108         }
1109
1110         if (!r && !(cd->type = strdup(type)))
1111                 r = -ENOMEM;
1112
1113         if (r < 0) {
1114                 LUKS_dealloc_masterkey(cd->volume_key);
1115                 cd->volume_key = NULL;
1116         }
1117
1118         return r;
1119 }
1120
1121 int crypt_load(struct crypt_device *cd,
1122                const char *requested_type,
1123                void *params)
1124 {
1125         struct luks_phdr hdr;
1126         int r;
1127
1128         log_dbg("Trying to load %s crypt type from device %s.",
1129                 requested_type ?: "any", cd->device);
1130
1131         if (requested_type && !isPLAIN(requested_type) && !isLUKS(requested_type))
1132                 return -EINVAL;
1133
1134         /* Some hash functions need initialized gcrypt library */
1135         if (init_crypto()) {
1136                 log_err(cd, _("Cannot initialize crypto backend.\n"));
1137                 return -ENOSYS;
1138         }
1139
1140         r = LUKS_read_phdr(cd->device, &hdr, 0, cd);
1141
1142         if (!r) {
1143                 memcpy(&cd->hdr, &hdr, sizeof(hdr));
1144                 cd->type = strdup(requested_type);
1145                 if (!cd->type)
1146                         r = -ENOMEM;
1147         }
1148
1149         return r;
1150 }
1151
1152 int crypt_header_backup(struct crypt_device *cd,
1153                         const char *requested_type,
1154                         const char *backup_file)
1155 {
1156         if ((requested_type && !isLUKS(requested_type)) || !backup_file)
1157                 return -EINVAL;
1158
1159         log_dbg("Requested header backup of device %s (%s) to "
1160                 "file %s.", cd->device, requested_type, backup_file);
1161
1162         return LUKS_hdr_backup(backup_file, cd->device, &cd->hdr, cd);
1163 }
1164
1165 int crypt_header_restore(struct crypt_device *cd,
1166                          const char *requested_type,
1167                          const char *backup_file)
1168 {
1169         if (requested_type && !isLUKS(requested_type))
1170                 return -EINVAL;
1171
1172         log_dbg("Requested header restore to device %s (%s) from "
1173                 "file %s.", cd->device, requested_type, backup_file);
1174
1175         return LUKS_hdr_restore(backup_file, cd->device, &cd->hdr, cd);
1176 }
1177
1178 void crypt_free(struct crypt_device *cd)
1179 {
1180         if (cd) {
1181                 log_dbg("Releasing crypt device %s context.", cd->device);
1182
1183                 dm_exit();
1184                 if (cd->volume_key)
1185                         LUKS_dealloc_masterkey(cd->volume_key);
1186
1187                 free(cd->device);
1188                 free(cd->type);
1189
1190                 /* used in plain device only */
1191                 free((char*)cd->plain_hdr.hash);
1192                 free(cd->plain_cipher);
1193                 free(cd->plain_cipher_mode);
1194                 free(cd->plain_uuid);
1195
1196                 free(cd);
1197         }
1198 }
1199
1200 int crypt_suspend(struct crypt_device *cd,
1201                   const char *name)
1202 {
1203         crypt_status_info ci;
1204         int r, suspended = 0;
1205
1206         log_dbg("Suspending volume %s.", name);
1207
1208         ci = crypt_status(NULL, name);
1209         if (ci < ACTIVE) {
1210                 log_err(cd, _("Volume %s is not active.\n"), name);
1211                 return -EINVAL;
1212         }
1213
1214         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1215                             NULL, NULL, NULL, NULL, &suspended, NULL);
1216         if (r < 0)
1217                 return r;
1218
1219         if (suspended) {
1220                 log_err(cd, _("Volume %s is already suspended.\n"), name);
1221                 return -EINVAL;
1222         }
1223
1224         r = dm_suspend_and_wipe_key(name);
1225         if (r)
1226                 log_err(cd, "Error during suspending device %s.\n", name);
1227
1228         return r;
1229 }
1230
1231 int crypt_resume_by_passphrase(struct crypt_device *cd,
1232                                const char *name,
1233                                int keyslot,
1234                                const char *passphrase,
1235                                size_t passphrase_size)
1236 {
1237         struct luks_masterkey *mk = NULL;
1238         int r, suspended = 0;
1239
1240         log_dbg("Resuming volume %s.", name);
1241
1242         if (!isLUKS(cd->type)) {
1243                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1244                 r = -EINVAL;
1245                 goto out;
1246         }
1247
1248         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1249                             NULL, NULL, NULL, NULL, &suspended, NULL);
1250         if (r < 0)
1251                 return r;
1252
1253         if (!suspended) {
1254                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1255                 return -EINVAL;
1256         }
1257
1258         if (passphrase) {
1259                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1260                                            passphrase_size, &cd->hdr, &mk, cd);
1261         } else
1262                 r = volume_key_by_terminal_passphrase(cd, keyslot, &mk);
1263
1264         if (r >= 0) {
1265                 keyslot = r;
1266                 r = dm_resume_and_reinstate_key(name, mk->keyLength, mk->key);
1267                 if (r)
1268                         log_err(cd, "Error during resuming device %s.\n", name);
1269         } else
1270                 r = keyslot;
1271 out:
1272         LUKS_dealloc_masterkey(mk);
1273         return r < 0 ? r : keyslot;
1274 }
1275
1276 int crypt_resume_by_keyfile(struct crypt_device *cd,
1277                             const char *name,
1278                             int keyslot,
1279                             const char *keyfile,
1280                             size_t keyfile_size)
1281 {
1282         struct luks_masterkey *mk = NULL;
1283         char *passphrase_read = NULL;
1284         unsigned int passphrase_size_read;
1285         int r, suspended = 0;
1286
1287         log_dbg("Resuming volume %s.", name);
1288
1289         if (!isLUKS(cd->type)) {
1290                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1291                 r = -EINVAL;
1292                 goto out;
1293         }
1294
1295         r = dm_query_device(name, NULL, NULL, NULL, NULL,
1296                             NULL, NULL, NULL, NULL, &suspended, NULL);
1297         if (r < 0)
1298                 return r;
1299
1300         if (!suspended) {
1301                 log_err(cd, _("Volume %s is not suspended.\n"), name);
1302                 return -EINVAL;
1303         }
1304
1305         if (!keyfile)
1306                 return -EINVAL;
1307
1308         key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1309                       &passphrase_size_read, keyfile, keyfile_size);
1310
1311         if(!passphrase_read)
1312                 r = -EINVAL;
1313         else {
1314                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1315                                            passphrase_size_read, &cd->hdr, &mk, cd);
1316                 safe_free(passphrase_read);
1317         }
1318
1319         if (r >= 0) {
1320                 keyslot = r;
1321                 r = dm_resume_and_reinstate_key(name, mk->keyLength, mk->key);
1322                 if (r)
1323                         log_err(cd, "Error during resuming device %s.\n", name);
1324         } else
1325                 r = keyslot;
1326 out:
1327         LUKS_dealloc_masterkey(mk);
1328         return r < 0 ? r : keyslot;
1329 }
1330
1331 // slot manipulation
1332 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
1333         int keyslot, // -1 any
1334         const char *passphrase, // NULL -> terminal
1335         size_t passphrase_size,
1336         const char *new_passphrase, // NULL -> terminal
1337         size_t new_passphrase_size)
1338 {
1339         struct luks_masterkey *mk = NULL;
1340         char *password = NULL, *new_password = NULL;
1341         unsigned int passwordLen, new_passwordLen;
1342         int r;
1343
1344         log_dbg("Adding new keyslot, existing passphrase %sprovided,"
1345                 "new passphrase %sprovided.",
1346                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
1347
1348         if (!isLUKS(cd->type)) {
1349                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1350                 return -EINVAL;
1351         }
1352
1353         r = keyslot_verify_or_find_empty(cd, &keyslot);
1354         if (r)
1355                 return r;
1356
1357         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1358                 /* No slots used, try to use pre-generated key in header */
1359                 if (cd->volume_key) {
1360                         mk = LUKS_alloc_masterkey(cd->volume_key->keyLength, cd->volume_key->key);
1361                         r = mk ? 0 : -ENOMEM;
1362                 } else {
1363                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1364                         return -EINVAL;
1365                 }
1366         } else if (passphrase) {
1367                 /* Passphrase provided, use it to unlock existing keyslot */
1368                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, passphrase,
1369                                            passphrase_size, &cd->hdr, &mk, cd);
1370         } else {
1371                 /* Passphrase not provided, ask first and use it to unlock existing keyslot */
1372                 key_from_terminal(cd, _("Enter any passphrase: "),
1373                                   &password, &passwordLen, 0);
1374                 if (!password) {
1375                         r = -EINVAL;
1376                         goto out;
1377                 }
1378
1379                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password,
1380                                            passwordLen, &cd->hdr, &mk, cd);
1381                 safe_free(password);
1382         }
1383
1384         if(r < 0)
1385                 goto out;
1386
1387         if (new_passphrase) {
1388                 new_password = (char *)new_passphrase;
1389                 new_passwordLen = new_passphrase_size;
1390         } else {
1391                 key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1392                                   &new_password, &new_passwordLen, 1);
1393                 if(!new_password) {
1394                         r = -EINVAL;
1395                         goto out;
1396                 }
1397         }
1398
1399         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1400                          &cd->hdr, mk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1401         if(r < 0) goto out;
1402
1403         r = 0;
1404 out:
1405         if (!new_passphrase)
1406                 safe_free(new_password);
1407         LUKS_dealloc_masterkey(mk);
1408         return r ?: keyslot;
1409 }
1410
1411 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
1412         int keyslot,
1413         const char *keyfile,
1414         size_t keyfile_size,
1415         const char *new_keyfile,
1416         size_t new_keyfile_size)
1417 {
1418         struct luks_masterkey *mk=NULL;
1419         char *password=NULL; unsigned int passwordLen;
1420         char *new_password = NULL; unsigned int new_passwordLen;
1421         int r;
1422
1423         log_dbg("Adding new keyslot, existing keyfile %s, new keyfile %s.",
1424                 keyfile ?: "[none]", new_keyfile ?: "[none]");
1425
1426         if (!isLUKS(cd->type)) {
1427                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1428                 return -EINVAL;
1429         }
1430
1431         r = keyslot_verify_or_find_empty(cd, &keyslot);
1432         if (r)
1433                 return r;
1434
1435         if (!LUKS_keyslot_active_count(&cd->hdr)) {
1436                 /* No slots used, try to use pre-generated key in header */
1437                 if (cd->volume_key) {
1438                         mk = LUKS_alloc_masterkey(cd->volume_key->keyLength, cd->volume_key->key);
1439                         r = mk ? 0 : -ENOMEM;
1440                 } else {
1441                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided.\n"));
1442                         return -EINVAL;
1443                 }
1444         } else {
1445                 /* Read password from file of (if NULL) from terminal */
1446                 if (keyfile)
1447                         key_from_file(cd, _("Enter any passphrase: "), &password, &passwordLen,
1448                                       keyfile, keyfile_size);
1449                 else
1450                         key_from_terminal(cd, _("Enter any passphrase: "),
1451                                         &password, &passwordLen, 1);
1452
1453                 if (!password)
1454                         return -EINVAL;
1455
1456                 r = LUKS_open_key_with_hdr(cd->device, CRYPT_ANY_SLOT, password, passwordLen,
1457                                            &cd->hdr, &mk, cd);
1458                 safe_free(password);
1459         }
1460
1461         if(r < 0)
1462                 goto out;
1463
1464         if (new_keyfile)
1465                 key_from_file(cd, _("Enter new passphrase for key slot: "),
1466                               &new_password, &new_passwordLen, new_keyfile,
1467                               new_keyfile_size);
1468         else
1469                 key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1470                                   &new_password, &new_passwordLen, 1);
1471
1472         if(!new_password) {
1473                 r = -EINVAL;
1474                 goto out;
1475         }
1476
1477         r = LUKS_set_key(cd->device, keyslot, new_password, new_passwordLen,
1478                          &cd->hdr, mk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1479 out:
1480         safe_free(new_password);
1481         LUKS_dealloc_masterkey(mk);
1482         return r < 0 ? r : keyslot;
1483 }
1484
1485 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
1486         int keyslot,
1487         const char *volume_key,
1488         size_t volume_key_size,
1489         const char *passphrase,
1490         size_t passphrase_size)
1491 {
1492         struct luks_masterkey *mk = NULL;
1493         int r = -EINVAL;
1494         char *new_password = NULL; unsigned int new_passwordLen;
1495
1496         log_dbg("Adding new keyslot %d using volume key.", keyslot);
1497
1498         if (!isLUKS(cd->type)) {
1499                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1500                 return -EINVAL;
1501         }
1502
1503         if (volume_key)
1504                 mk = LUKS_alloc_masterkey(volume_key_size, volume_key);
1505         else if (cd->volume_key)
1506                 mk = LUKS_alloc_masterkey(cd->volume_key->keyLength, cd->volume_key->key);
1507
1508         if (!mk)
1509                 return -ENOMEM;
1510
1511         r = LUKS_verify_master_key(&cd->hdr, mk);
1512         if (r < 0) {
1513                 log_err(cd, _("Volume key does not match the volume.\n"));
1514                 goto out;
1515         }
1516
1517         r = keyslot_verify_or_find_empty(cd, &keyslot);
1518         if (r)
1519                 goto out;
1520
1521         if (!passphrase) {
1522                 key_from_terminal(cd, _("Enter new passphrase for key slot: "),
1523                                   &new_password, &new_passwordLen, 1);
1524                 passphrase = new_password;
1525                 passphrase_size = new_passwordLen;
1526         }
1527
1528         r = LUKS_set_key(cd->device, keyslot, passphrase, passphrase_size,
1529                          &cd->hdr, mk, cd->iteration_time, &cd->PBKDF2_per_sec, cd);
1530 out:
1531         if (new_password)
1532                 safe_free(new_password);
1533         LUKS_dealloc_masterkey(mk);
1534         return r ?: keyslot;
1535 }
1536
1537 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
1538 {
1539         crypt_keyslot_info ki;
1540
1541         log_dbg("Destroying keyslot %d.", keyslot);
1542
1543         if (!isLUKS(cd->type)) {
1544                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1545                 return -EINVAL;
1546         }
1547
1548         ki = crypt_keyslot_status(cd, keyslot);
1549         if (ki == SLOT_INVALID) {
1550                 log_err(cd, _("Key slot %d is invalid.\n"), keyslot);
1551                 return -EINVAL;
1552         }
1553
1554         if (ki == SLOT_INACTIVE) {
1555                 log_err(cd, _("Key slot %d is not used.\n"), keyslot);
1556                 return -EINVAL;
1557         }
1558
1559         return LUKS_del_key(cd->device, keyslot, &cd->hdr, cd);
1560 }
1561
1562 // activation/deactivation of device mapping
1563 int crypt_activate_by_passphrase(struct crypt_device *cd,
1564         const char *name,
1565         int keyslot,
1566         const char *passphrase,
1567         size_t passphrase_size,
1568         uint32_t flags)
1569 {
1570         crypt_status_info ci;
1571         struct luks_masterkey *mk = NULL;
1572         char *prompt = NULL;
1573         int r;
1574
1575         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1576                 name ? "Activating" : "Checking", name ?: "",
1577                 keyslot, passphrase ? "" : "[none] ");
1578
1579         if (!name)
1580                 return -EINVAL;
1581
1582         /* plain, use hashed passphrase */
1583         if (isPLAIN(cd->type))
1584                 return create_device_helper(cd, name, cd->plain_hdr.hash,
1585                         cd->plain_cipher, cd->plain_cipher_mode, NULL, passphrase, passphrase_size,
1586                         cd->volume_key->keyLength, 0, cd->plain_hdr.skip,
1587                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1588
1589         if (name) {
1590                 ci = crypt_status(NULL, name);
1591                 if (ci == INVALID)
1592                         return -EINVAL;
1593                 else if (ci >= ACTIVE) {
1594                         log_err(cd, _("Device %s already exists.\n"), name);
1595                         return -EEXIST;
1596                 }
1597         }
1598
1599         if(asprintf(&prompt, _("Enter passphrase for %s: "), cd->device) < 0)
1600                 return -ENOMEM;
1601
1602         /* provided passphrase, do not retry */
1603         if (passphrase) {
1604                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1605                                            passphrase_size, &cd->hdr, &mk, cd);
1606         } else
1607                 r = volume_key_by_terminal_passphrase(cd, keyslot, &mk);
1608
1609         if (r >= 0) {
1610                 keyslot = r;
1611                 if (name)
1612                         r = open_from_hdr_and_mk(cd, mk, name, flags);
1613         }
1614
1615         LUKS_dealloc_masterkey(mk);
1616         free(prompt);
1617
1618         return r < 0  ? r : keyslot;
1619 }
1620
1621 int crypt_activate_by_keyfile(struct crypt_device *cd,
1622         const char *name,
1623         int keyslot,
1624         const char *keyfile,
1625         size_t keyfile_size,
1626         uint32_t flags)
1627 {
1628         crypt_status_info ci;
1629         struct luks_masterkey *mk = NULL;
1630         char *passphrase_read = NULL;
1631         unsigned int passphrase_size_read;
1632         int r;
1633
1634         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1635                 name, keyslot, keyfile ?: "[none]");
1636
1637         if (!isLUKS(cd->type)) {
1638                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1639                 return -EINVAL;
1640         }
1641
1642         if (name) {
1643                 ci = crypt_status(NULL, name);
1644                 if (ci == INVALID)
1645                         return -EINVAL;
1646                 else if (ci >= ACTIVE) {
1647                         log_err(cd, _("Device %s already exists.\n"), name);
1648                         return -EEXIST;
1649                 }
1650         }
1651
1652         if (!keyfile)
1653                 return -EINVAL;
1654
1655         key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1656                       &passphrase_size_read, keyfile, keyfile_size);
1657         if(!passphrase_read)
1658                 r = -EINVAL;
1659         else {
1660                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1661                                            passphrase_size_read, &cd->hdr, &mk, cd);
1662                 safe_free(passphrase_read);
1663         }
1664
1665         if (r >= 0) {
1666                 keyslot = r;
1667                 r = open_from_hdr_and_mk(cd, mk, name, flags);
1668         }
1669
1670         LUKS_dealloc_masterkey(mk);
1671
1672         return r < 0 ? r : keyslot;
1673 }
1674
1675 int crypt_activate_by_volume_key(struct crypt_device *cd,
1676         const char *name,
1677         const char *volume_key,
1678         size_t volume_key_size,
1679         uint32_t flags)
1680 {
1681         crypt_status_info ci;
1682         struct luks_masterkey *mk;
1683         int r;
1684
1685         log_dbg("Activating volume %s by volume key.", name);
1686
1687         /* use key directly, no hash */
1688         if (isPLAIN(cd->type))
1689                 return create_device_helper(cd, name, NULL,
1690                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
1691                         cd->volume_key->keyLength, 0, cd->plain_hdr.skip,
1692                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1693
1694         if (!isLUKS(cd->type)) {
1695                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1696                 return -EINVAL;
1697         }
1698
1699         if (name) {
1700                 ci = crypt_status(NULL, name);
1701                 if (ci == INVALID)
1702                         return -EINVAL;
1703                 else if (ci >= ACTIVE) {
1704                         log_err(cd, _("Device %s already exists.\n"), name);
1705                         return -EEXIST;
1706                 }
1707         }
1708
1709         mk = LUKS_alloc_masterkey(volume_key_size, volume_key);
1710         if (!mk)
1711                 return -ENOMEM;
1712         r = LUKS_verify_master_key(&cd->hdr, mk);
1713
1714         if (r == -EPERM)
1715                 log_err(cd, _("Volume key does not match the volume.\n"));
1716
1717         if (!r && name)
1718                 r = open_from_hdr_and_mk(cd, mk, name, flags);
1719
1720         LUKS_dealloc_masterkey(mk);
1721
1722         return r;
1723 }
1724
1725 int crypt_deactivate(struct crypt_device *cd, const char *name)
1726 {
1727         if (!name)
1728                 return -EINVAL;
1729
1730         log_dbg("Deactivating volume %s.", name);
1731
1732         switch (crypt_status(cd, name)) {
1733                 case ACTIVE:    return dm_remove_device(name, 0, 0);
1734                 case BUSY:      log_err(cd, _("Device %s is busy."), name);
1735                                 return -EBUSY;
1736                 case INACTIVE:  log_err(cd, _("Device %s is not active."), name);
1737                                 return -ENODEV;
1738                 default:        log_err(cd, _("Invalid device %s."), name);
1739                                 return -EINVAL;
1740         }
1741 }
1742
1743 // misc helper functions
1744 int crypt_volume_key_get(struct crypt_device *cd,
1745         int keyslot,
1746         char *volume_key,
1747         size_t *volume_key_size,
1748         const char *passphrase,
1749         size_t passphrase_size)
1750 {
1751         struct luks_masterkey *mk;
1752         char *processed_key = NULL;
1753         int r, key_len;
1754
1755         key_len = crypt_get_volume_key_size(cd);
1756         if (key_len > *volume_key_size) {
1757                 log_err(cd, _("Volume key buffer too small.\n"));
1758                 return -ENOMEM;
1759         }
1760
1761         if (isPLAIN(cd->type)) {
1762                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
1763                                             passphrase, passphrase_size);
1764                 if (!processed_key) {
1765                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
1766                         return -EINVAL;
1767                 }
1768                 memcpy(volume_key, processed_key, key_len);
1769                 *volume_key_size = key_len;
1770                 safe_free(processed_key);
1771                 return 0;
1772         }
1773
1774         if (isLUKS(cd->type)) {
1775                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1776                                         passphrase_size, &cd->hdr, &mk, cd);
1777
1778                 if (r >= 0) {
1779                         memcpy(volume_key, mk->key, mk->keyLength);
1780                         *volume_key_size = mk->keyLength;
1781                 }
1782
1783                 LUKS_dealloc_masterkey(mk);
1784                 return r;
1785         }
1786
1787         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
1788         return -EINVAL;
1789 }
1790
1791 int crypt_volume_key_verify(struct crypt_device *cd,
1792         const char *volume_key,
1793         size_t volume_key_size)
1794 {
1795         struct luks_masterkey *mk;
1796         int r;
1797
1798         if (!isLUKS(cd->type)) {
1799                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1800                 return -EINVAL;
1801         }
1802
1803         mk = LUKS_alloc_masterkey(volume_key_size, volume_key);
1804         if (!mk)
1805                 return -ENOMEM;
1806
1807         r = LUKS_verify_master_key(&cd->hdr, mk);
1808
1809         if (r == -EPERM)
1810                 log_err(cd, _("Volume key does not match the volume.\n"));
1811
1812         LUKS_dealloc_masterkey(mk);
1813
1814         return r;
1815 }
1816
1817 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
1818 {
1819         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
1820         cd->timeout = timeout_sec;
1821 }
1822
1823 void crypt_set_password_retry(struct crypt_device *cd, int tries)
1824 {
1825         log_dbg("Password retry count set to %d.", tries);
1826         cd->tries = tries;
1827 }
1828
1829 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
1830 {
1831         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
1832         cd->iteration_time = iteration_time_ms;
1833 }
1834
1835 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
1836 {
1837         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
1838         cd->password_verify = password_verify ? 1 : 0;
1839 }
1840
1841 int crypt_memory_lock(struct crypt_device *cd, int lock)
1842 {
1843         return lock ? memlock_inc(cd) : memlock_dec(cd);
1844 }
1845
1846 // reporting
1847 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
1848 {
1849         int r;
1850
1851         r = dm_status_device(name);
1852
1853         if (r < 0 && r != -ENODEV)
1854                 return INVALID;
1855
1856         if (r == 0)
1857                 return ACTIVE;
1858
1859         if (r > 0)
1860                 return BUSY;
1861
1862         return INACTIVE;
1863 }
1864
1865 static void hexprintICB(struct crypt_device *cd, char *d, int n)
1866 {
1867         int i;
1868         for(i = 0; i < n; i++)
1869                 log_std(cd, "%02hhx ", (char)d[i]);
1870 }
1871
1872 int crypt_dump(struct crypt_device *cd)
1873 {
1874         int i;
1875         if (!isLUKS(cd->type)) { //FIXME
1876                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1877                 return -EINVAL;
1878         }
1879
1880         log_std(cd, "LUKS header information for %s\n\n", cd->device);
1881         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
1882         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
1883         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
1884         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
1885         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
1886         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
1887         log_std(cd, "MK digest:     \t");
1888         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
1889         log_std(cd, "\n");
1890         log_std(cd, "MK salt:       \t");
1891         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
1892         log_std(cd, "\n               \t");
1893         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1894         log_std(cd, "\n");
1895         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
1896         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
1897         for(i = 0; i < LUKS_NUMKEYS; i++) {
1898                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
1899                         log_std(cd, "Key Slot %d: ENABLED\n",i);
1900                         log_std(cd, "\tIterations:         \t%d\n",
1901                                 cd->hdr.keyblock[i].passwordIterations);
1902                         log_std(cd, "\tSalt:               \t");
1903                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
1904                                     LUKS_SALTSIZE/2);
1905                         log_std(cd, "\n\t                      \t");
1906                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
1907                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1908                         log_std(cd, "\n");
1909
1910                         log_std(cd, "\tKey material offset:\t%d\n",
1911                                 cd->hdr.keyblock[i].keyMaterialOffset);
1912                         log_std(cd, "\tAF stripes:            \t%d\n",
1913                                 cd->hdr.keyblock[i].stripes);
1914                 }
1915                 else 
1916                         log_std(cd, "Key Slot %d: DISABLED\n", i);
1917         }
1918         return 0;
1919 }
1920
1921 const char *crypt_get_cipher(struct crypt_device *cd)
1922 {
1923         if (isPLAIN(cd->type))
1924                 return cd->plain_cipher;
1925
1926         if (isLUKS(cd->type))
1927                 return cd->hdr.cipherName;
1928
1929         return NULL;
1930 }
1931
1932 const char *crypt_get_cipher_mode(struct crypt_device *cd)
1933 {
1934         if (isPLAIN(cd->type))
1935                 return cd->plain_cipher_mode;
1936
1937         if (isLUKS(cd->type))
1938                 return cd->hdr.cipherMode;
1939
1940         return NULL;
1941 }
1942
1943 const char *crypt_get_uuid(struct crypt_device *cd)
1944 {
1945         if (isLUKS(cd->type))
1946                 return cd->hdr.uuid;
1947
1948         return NULL;
1949 }
1950
1951 int crypt_get_volume_key_size(struct crypt_device *cd)
1952 {
1953         if (isPLAIN(cd->type))
1954                 return cd->volume_key->keyLength;
1955
1956         if (isLUKS(cd->type))
1957                 return cd->hdr.keyBytes;
1958
1959         return 0;
1960 }
1961
1962 uint64_t crypt_get_data_offset(struct crypt_device *cd)
1963 {
1964         if (isPLAIN(cd->type))
1965                 return cd->plain_hdr.offset;
1966
1967         if (isLUKS(cd->type))
1968                 return cd->hdr.payloadOffset;
1969
1970         return 0;
1971 }
1972
1973 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
1974 {
1975         if (!isLUKS(cd->type)) {
1976                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1977                 return SLOT_INVALID;
1978         }
1979
1980         return LUKS_keyslot_info(&cd->hdr, keyslot);
1981 }