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