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