* Remove old API code helper functions.
[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                 return -EINVAL;
1270
1271         if (ki == SLOT_INACTIVE)
1272                 return 0;
1273
1274         return LUKS_del_key(cd->device, keyslot, cd);
1275 }
1276
1277 // activation/deactivation of device mapping
1278 int crypt_activate_by_passphrase(struct crypt_device *cd,
1279         const char *name,
1280         int keyslot,
1281         const char *passphrase,
1282         size_t passphrase_size,
1283         uint32_t flags)
1284 {
1285         crypt_status_info ci;
1286         struct luks_masterkey *mk = NULL;
1287         char *prompt = NULL, *passphrase_read = NULL;
1288         unsigned int passphrase_size_read;
1289         int r, tries = cd->tries;
1290
1291         log_dbg("%s volume %s [keyslot %d] using %spassphrase.",
1292                 name ? "Activating" : "Checking", name ?: "",
1293                 keyslot, passphrase ? "" : "[none] ");
1294
1295         if (!name)
1296                 return -EINVAL;
1297
1298         /* plain, use hashed passphrase */
1299         if (isPLAIN(cd->type))
1300                 return create_device_helper(cd, name, cd->plain_hdr.hash,
1301                         cd->plain_cipher, cd->plain_cipher_mode, NULL, passphrase, passphrase_size,
1302                         cd->volume_key->keyLength, 0, cd->plain_hdr.skip,
1303                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1304
1305         if (name) {
1306                 ci = crypt_status(NULL, name);
1307                 if (ci == INVALID)
1308                         return -EINVAL;
1309                 else if (ci >= ACTIVE) {
1310                         log_err(cd, _("Device %s already exists.\n"), name);
1311                         return -EEXIST;
1312                 }
1313         }
1314
1315         if(asprintf(&prompt, _("Enter passphrase for %s: "), cd->device) < 0)
1316                 return -ENOMEM;
1317
1318         /* provided passphrase, do not retry */
1319         if (passphrase) {
1320                         r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1321                                                    passphrase_size, &cd->hdr, &mk, cd);
1322         } else do {
1323                 if (mk)
1324                         LUKS_dealloc_masterkey(mk);
1325                 mk = NULL;
1326
1327                 key_from_terminal(cd, prompt, &passphrase_read,
1328                                   &passphrase_size_read, 0);
1329                 if(!passphrase_read) {
1330                         r = -EINVAL;
1331                         break;
1332                 }
1333
1334                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1335                                            passphrase_size_read, &cd->hdr, &mk, cd);
1336                 safe_free(passphrase_read);
1337                 passphrase_read = NULL;
1338         } while (r == -EPERM && (--tries > 0));
1339
1340         if (r >= 0) {
1341                 keyslot = r;
1342                 if (name)
1343                         r = open_from_hdr_and_mk(cd, mk, name, flags);
1344         }
1345
1346         LUKS_dealloc_masterkey(mk);
1347         free(prompt);
1348
1349         return r < 0  ? r : keyslot;
1350 }
1351
1352 int crypt_activate_by_keyfile(struct crypt_device *cd,
1353         const char *name,
1354         int keyslot,
1355         const char *keyfile,
1356         size_t keyfile_size,
1357         uint32_t flags)
1358 {
1359         crypt_status_info ci;
1360         struct luks_masterkey *mk = NULL;
1361         char *passphrase_read = NULL;
1362         unsigned int passphrase_size_read;
1363         int r;
1364
1365         log_dbg("Activating volume %s [keyslot %d] using keyfile %s.",
1366                 name, keyslot, keyfile ?: "[none]");
1367
1368         if (!isLUKS(cd->type)) {
1369                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1370                 return -EINVAL;
1371         }
1372
1373         if (name) {
1374                 ci = crypt_status(NULL, name);
1375                 if (ci == INVALID)
1376                         return -EINVAL;
1377                 else if (ci >= ACTIVE) {
1378                         log_err(cd, _("Device %s already exists.\n"), name);
1379                         return -EEXIST;
1380                 }
1381         }
1382
1383         if (!keyfile)
1384                 return -EINVAL;
1385
1386         key_from_file(cd, _("Enter passphrase: "), &passphrase_read,
1387                       &passphrase_size_read, keyfile, keyfile_size);
1388         if(!passphrase_read)
1389                 r = -EINVAL;
1390         else {
1391                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase_read,
1392                                            passphrase_size_read, &cd->hdr, &mk, cd);
1393                 safe_free(passphrase_read);
1394         }
1395
1396         if (r >= 0) {
1397                 keyslot = r;
1398                 r = open_from_hdr_and_mk(cd, mk, name, flags);
1399         }
1400
1401         LUKS_dealloc_masterkey(mk);
1402
1403         return r < 0 ? r : keyslot;
1404 }
1405
1406 int crypt_activate_by_volume_key(struct crypt_device *cd,
1407         const char *name,
1408         const char *volume_key,
1409         size_t volume_key_size,
1410         uint32_t flags)
1411 {
1412         crypt_status_info ci;
1413         struct luks_masterkey *mk;
1414         int r;
1415
1416         log_dbg("Activating volume %s by volume key.", name);
1417
1418         /* use key directly, no hash */
1419         if (isPLAIN(cd->type))
1420                 return create_device_helper(cd, name, NULL,
1421                         cd->plain_cipher, cd->plain_cipher_mode, NULL, volume_key, volume_key_size,
1422                         cd->volume_key->keyLength, 0, cd->plain_hdr.skip,
1423                         cd->plain_hdr.offset, cd->plain_uuid, flags & CRYPT_ACTIVATE_READONLY, 0, 0);
1424
1425         if (!isLUKS(cd->type)) {
1426                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1427                 return -EINVAL;
1428         }
1429
1430         if (name) {
1431                 ci = crypt_status(NULL, name);
1432                 if (ci == INVALID)
1433                         return -EINVAL;
1434                 else if (ci >= ACTIVE) {
1435                         log_err(cd, _("Device %s already exists.\n"), name);
1436                         return -EEXIST;
1437                 }
1438         }
1439
1440         mk = LUKS_alloc_masterkey(volume_key_size, volume_key);
1441         if (!mk)
1442                 return -ENOMEM;
1443         r = LUKS_verify_master_key(&cd->hdr, mk);
1444
1445         if (r == -EPERM)
1446                 log_err(cd, _("Volume key does not match the volume.\n"));
1447
1448         if (!r && name)
1449                 r = open_from_hdr_and_mk(cd, mk, name, flags);
1450
1451         LUKS_dealloc_masterkey(mk);
1452
1453         return r;
1454 }
1455
1456 int crypt_deactivate(struct crypt_device *cd, const char *name)
1457 {
1458         if (!name)
1459                 return -EINVAL;
1460
1461         log_dbg("Deactivating volume %s.", name);
1462
1463         switch (crypt_status(cd, name)) {
1464                 case ACTIVE:    return dm_remove_device(name, 0, 0);
1465                 case BUSY:      log_err(cd, _("Device %s is busy."), name);
1466                                 return -EBUSY;
1467                 case INACTIVE:  return -ENODEV;
1468                 default:        log_err(cd, _("Invalid device %s."), name);
1469                                 return -EINVAL;
1470         }
1471 }
1472
1473 // misc helper functions
1474 int crypt_volume_key_get(struct crypt_device *cd,
1475         int keyslot,
1476         char *volume_key,
1477         size_t *volume_key_size,
1478         const char *passphrase,
1479         size_t passphrase_size)
1480 {
1481         struct luks_masterkey *mk;
1482         char *processed_key = NULL;
1483         int r, key_len;
1484
1485         key_len = crypt_get_volume_key_size(cd);
1486         if (key_len > *volume_key_size) {
1487                 log_err(cd, _("Volume key buffer too small.\n"));
1488                 return -ENOMEM;
1489         }
1490
1491         if (isPLAIN(cd->type)) {
1492                 processed_key = process_key(cd, cd->plain_hdr.hash, NULL, key_len,
1493                                             passphrase, passphrase_size);
1494                 if (!processed_key) {
1495                         log_err(cd, _("Cannot retrieve volume key for plain device.\n"));
1496                         return -EINVAL;
1497                 }
1498                 memcpy(volume_key, processed_key, key_len);
1499                 *volume_key_size = key_len;
1500                 safe_free(processed_key);
1501                 return 0;
1502         }
1503
1504         if (isLUKS(cd->type)) {
1505                 r = LUKS_open_key_with_hdr(cd->device, keyslot, passphrase,
1506                                         passphrase_size, &cd->hdr, &mk, cd);
1507
1508                 if (r >= 0) {
1509                         memcpy(volume_key, mk->key, mk->keyLength);
1510                         *volume_key_size = mk->keyLength;
1511                 }
1512
1513                 LUKS_dealloc_masterkey(mk);
1514                 return r;
1515         }
1516
1517         log_err(cd, _("This operation is not supported for %s crypt device.\n"), cd->type ?: "(none)");
1518         return -EINVAL;
1519 }
1520
1521 int crypt_volume_key_verify(struct crypt_device *cd,
1522         const char *volume_key,
1523         size_t volume_key_size)
1524 {
1525         struct luks_masterkey *mk;
1526         int r;
1527
1528         if (!isLUKS(cd->type)) {
1529                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1530                 return -EINVAL;
1531         }
1532
1533         mk = LUKS_alloc_masterkey(volume_key_size, volume_key);
1534         if (!mk)
1535                 return -ENOMEM;
1536
1537         r = LUKS_verify_master_key(&cd->hdr, mk);
1538
1539         if (r == -EPERM)
1540                 log_err(cd, _("Volume key does not match the volume.\n"));
1541
1542         LUKS_dealloc_masterkey(mk);
1543
1544         return r;
1545 }
1546
1547 void crypt_set_timeout(struct crypt_device *cd, uint64_t timeout_sec)
1548 {
1549         log_dbg("Timeout set to %" PRIu64 " miliseconds.", timeout_sec);
1550         cd->timeout = timeout_sec;
1551 }
1552
1553 void crypt_set_password_retry(struct crypt_device *cd, int tries)
1554 {
1555         log_dbg("Password retry count set to %d.", tries);
1556         cd->tries = tries;
1557 }
1558
1559 void crypt_set_iterarion_time(struct crypt_device *cd, uint64_t iteration_time_ms)
1560 {
1561         log_dbg("Iteration time set to %" PRIu64 " miliseconds.", iteration_time_ms);
1562         cd->iteration_time = iteration_time_ms;
1563 }
1564
1565 void crypt_set_password_verify(struct crypt_device *cd, int password_verify)
1566 {
1567         log_dbg("Password verification %s.", password_verify ? "enabled" : "disabled");
1568         cd->password_verify = password_verify ? 1 : 0;
1569 }
1570
1571 int crypt_memory_lock(struct crypt_device *cd, int lock)
1572 {
1573         return lock ? memlock_inc(cd) : memlock_dec(cd);
1574 }
1575
1576 // reporting
1577 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
1578 {
1579         int r;
1580
1581         r = dm_status_device(name);
1582
1583         if (r < 0 && r != -ENODEV)
1584                 return INVALID;
1585
1586         if (r == 0)
1587                 return ACTIVE;
1588
1589         if (r > 0)
1590                 return BUSY;
1591
1592         return INACTIVE;
1593 }
1594
1595 static void hexprintICB(struct crypt_device *cd, char *d, int n)
1596 {
1597         int i;
1598         for(i = 0; i < n; i++)
1599                 log_std(cd, "%02hhx ", (char)d[i]);
1600 }
1601
1602 int crypt_dump(struct crypt_device *cd)
1603 {
1604         int i;
1605         if (!isLUKS(cd->type)) { //FIXME
1606                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1607                 return -EINVAL;
1608         }
1609
1610         log_std(cd, "LUKS header information for %s\n\n", cd->device);
1611         log_std(cd, "Version:       \t%d\n", cd->hdr.version);
1612         log_std(cd, "Cipher name:   \t%s\n", cd->hdr.cipherName);
1613         log_std(cd, "Cipher mode:   \t%s\n", cd->hdr.cipherMode);
1614         log_std(cd, "Hash spec:     \t%s\n", cd->hdr.hashSpec);
1615         log_std(cd, "Payload offset:\t%d\n", cd->hdr.payloadOffset);
1616         log_std(cd, "MK bits:       \t%d\n", cd->hdr.keyBytes * 8);
1617         log_std(cd, "MK digest:     \t");
1618         hexprintICB(cd, cd->hdr.mkDigest, LUKS_DIGESTSIZE);
1619         log_std(cd, "\n");
1620         log_std(cd, "MK salt:       \t");
1621         hexprintICB(cd, cd->hdr.mkDigestSalt, LUKS_SALTSIZE/2);
1622         log_std(cd, "\n               \t");
1623         hexprintICB(cd, cd->hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1624         log_std(cd, "\n");
1625         log_std(cd, "MK iterations: \t%d\n", cd->hdr.mkDigestIterations);
1626         log_std(cd, "UUID:          \t%s\n\n", cd->hdr.uuid);
1627         for(i = 0; i < LUKS_NUMKEYS; i++) {
1628                 if(cd->hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
1629                         log_std(cd, "Key Slot %d: ENABLED\n",i);
1630                         log_std(cd, "\tIterations:         \t%d\n",
1631                                 cd->hdr.keyblock[i].passwordIterations);
1632                         log_std(cd, "\tSalt:               \t");
1633                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt,
1634                                     LUKS_SALTSIZE/2);
1635                         log_std(cd, "\n\t                      \t");
1636                         hexprintICB(cd, cd->hdr.keyblock[i].passwordSalt +
1637                                     LUKS_SALTSIZE/2, LUKS_SALTSIZE/2);
1638                         log_std(cd, "\n");
1639
1640                         log_std(cd, "\tKey material offset:\t%d\n",
1641                                 cd->hdr.keyblock[i].keyMaterialOffset);
1642                         log_std(cd, "\tAF stripes:            \t%d\n",
1643                                 cd->hdr.keyblock[i].stripes);
1644                 }
1645                 else 
1646                         log_std(cd, "Key Slot %d: DISABLED\n", i);
1647         }
1648         return 0;
1649 }
1650
1651 const char *crypt_get_cipher(struct crypt_device *cd)
1652 {
1653         if (isPLAIN(cd->type))
1654                 return cd->plain_cipher;
1655
1656         if (isLUKS(cd->type))
1657                 return cd->hdr.cipherName;
1658
1659         return NULL;
1660 }
1661
1662 const char *crypt_get_cipher_mode(struct crypt_device *cd)
1663 {
1664         if (isPLAIN(cd->type))
1665                 return cd->plain_cipher_mode;
1666
1667         if (isLUKS(cd->type))
1668                 return cd->hdr.cipherMode;
1669
1670         return NULL;
1671 }
1672
1673 const char *crypt_get_uuid(struct crypt_device *cd)
1674 {
1675         if (isLUKS(cd->type))
1676                 return cd->hdr.uuid;
1677
1678         return NULL;
1679 }
1680
1681 int crypt_get_volume_key_size(struct crypt_device *cd)
1682 {
1683         if (isPLAIN(cd->type))
1684                 return cd->volume_key->keyLength;
1685
1686         if (isLUKS(cd->type))
1687                 return cd->hdr.keyBytes;
1688
1689         return 0;
1690 }
1691
1692 uint64_t crypt_get_data_offset(struct crypt_device *cd)
1693 {
1694         if (isPLAIN(cd->type))
1695                 return cd->plain_hdr.offset;
1696
1697         if (isLUKS(cd->type))
1698                 return cd->hdr.payloadOffset;
1699
1700         return 0;
1701 }
1702
1703 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
1704 {
1705         if (!isLUKS(cd->type)) {
1706                 log_err(cd, _("This operation is supported only for LUKS device.\n"));
1707                 return SLOT_INVALID;
1708         }
1709
1710         return LUKS_keyslot_info(&cd->hdr, keyslot);
1711 }