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