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