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