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