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