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