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