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