0858c9296e533835d930587ebf7d67229297041e
[dragonfly.git] / lib / libtcplay / tcplay.c
1 /*
2  * Copyright (c) 2011 Alex Hornung <alex@alexhornung.com>.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
20  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
22  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 #include <machine/inttypes.h>
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <err.h>
38 #include <time.h>
39 #include <libdm.h>
40 #include <libutil.h>
41
42 #include "crc32.h"
43 #include "tcplay.h"
44
45
46 /* XXX TODO:
47  *  - LRW-benbi support? needs further work in dm-crypt and even opencrypto
48  *  - secure buffer review (i.e: is everything that needs it using secure mem?)
49  *  - mlockall? (at least MCL_FUTURE, which is the only one we support)
50  */
51
52 summary_fn_t summary_fn = NULL;
53 int tc_internal_verbose = 1;
54 char tc_internal_log_buffer[LOG_BUFFER_SZ];
55
56 void
57 tc_log(int is_err, const char *fmt, ...)
58 {
59         __va_list ap;
60         FILE *fp;
61
62         if (is_err)
63                 fp = stderr;
64         else
65                 fp = stdout;
66
67         __va_start(ap, fmt);
68
69         vsnprintf(tc_internal_log_buffer, LOG_BUFFER_SZ, fmt, ap);
70
71         if (tc_internal_verbose)
72                 vfprintf(fp, fmt, ap);
73
74         __va_end(ap);
75 }
76
77 /* Supported algorithms */
78 struct pbkdf_prf_algo pbkdf_prf_algos[] = {
79         { "RIPEMD160",  2000 }, /* needs to come before the other RIPEMD160 */
80         { "RIPEMD160",  1000 },
81         { "SHA512",     1000 },
82         { "whirlpool",  1000 },
83         { NULL,         0    }
84 };
85
86 struct tc_crypto_algo tc_crypto_algos[] = {
87 #if 0
88         /* XXX: turns out TC doesn't support AES-128-XTS */
89         { "AES-128-XTS",        "aes-xts-plain",        32,     8 },
90         { "TWOFISH-128-XTS",    "twofish-xts-plain",    32,     8 },
91         { "SERPENT-128-XTS",    "serpent-xts-plain",    32,     8 },
92 #endif
93         { "AES-256-XTS",        "aes-xts-plain",        64,     8 },
94         { "TWOFISH-256-XTS",    "twofish-xts-plain",    64,     8 },
95         { "SERPENT-256-XTS",    "serpent-xts-plain",    64,     8 },
96         { NULL,                 NULL,                   0,      0 }
97 };
98
99 const char *valid_cipher_chains[][MAX_CIPHER_CHAINS] = {
100         { "AES-256-XTS", NULL },
101         { "TWOFISH-256-XTS", NULL },
102         { "SERPENT-256-XTS", NULL },
103         { "AES-256-XTS", "TWOFISH-256-XTS", "SERPENT-256-XTS", NULL },
104         { "SERPENT-256-XTS", "TWOFISH-256-XTS", "AES-256-XTS", NULL },
105 #if 0
106         /* It seems that all the two-way cascades are the other way round... */
107         { "AES-256-XTS", "TWOFISH-256-XTS", NULL },
108         { "SERPENT-256-XTS", "AES-256-XTS", NULL },
109         { "TWOFISH-256-XTS", "SERPENT-256-XTS", NULL },
110
111 #endif
112         { "TWOFISH-256-XTS", "AES-256-XTS", NULL },
113         { "AES-256-XTS", "SERPENT-256-XTS", NULL },
114         { "SERPENT-256-XTS", "TWOFISH-256-XTS", NULL },
115         { NULL }
116 };
117
118 struct tc_cipher_chain *tc_cipher_chains[MAX_CIPHER_CHAINS];
119
120 static
121 int
122 tc_build_cipher_chains(void)
123 {
124         struct tc_cipher_chain *chain, *elem, *prev;
125         int i = 0;
126         int k;
127
128         while (valid_cipher_chains[i][0] != NULL) {
129                 chain = NULL;
130                 prev = NULL;
131                 k = 0;
132
133                 while (valid_cipher_chains[i][k] != NULL) {
134                         if ((elem = alloc_safe_mem(sizeof(*elem))) == NULL) {
135                                 tc_log(1, "Error allocating memory for "
136                                    "cipher chain\n");
137                                 return -1;
138                         }
139
140                         /* Initialize first element of chain */
141                         if (chain == NULL) {
142                                 chain = elem;
143                                 elem->prev = NULL;
144                         }
145
146                         /* Populate previous element */
147                         if (prev != NULL) {
148                                 prev->next = elem;
149                                 elem->prev = prev;
150                         }
151
152                         /* Assume we are the last element in the chain */
153                         elem->next = NULL;
154
155                         /* Initialize other fields */
156                         elem->cipher = check_cipher(valid_cipher_chains[i][k], 0);
157                         if (elem->cipher == NULL)
158                                 return -1;
159
160                         elem->key = NULL;
161
162                         prev = elem;
163                         ++k;
164                 }
165
166                 /* Store cipher chain */
167                 tc_cipher_chains[i++] = chain;
168
169                 /* Integrity check */
170                 if (i >= MAX_CIPHER_CHAINS) {
171                         tc_log(1, "FATAL: tc_cipher_chains is full!!\n");
172                         return -1;
173                 }
174
175                 /* Make sure array is NULL terminated */
176                 tc_cipher_chains[i] = NULL;
177         }
178
179         return 0;
180 }
181
182 #ifdef DEBUG
183 static void
184 print_hex(unsigned char *buf, off_t start, size_t len)
185 {
186         size_t i;
187
188         for (i = start; i < start+len; i++)
189                 printf("%02x", buf[i]);
190
191         printf("\n");
192 }
193 #endif
194
195 void
196 print_info(struct tcplay_info *info)
197 {
198         struct tc_cipher_chain *cipher_chain;
199         int klen = 0;
200
201         printf("PBKDF2 PRF:\t\t%s\n", info->pbkdf_prf->name);
202         printf("PBKDF2 iterations:\t%d\n", info->pbkdf_prf->iteration_count);
203
204         printf("Cipher:\t\t\t");
205         for (cipher_chain = info->cipher_chain;
206             cipher_chain != NULL;
207             cipher_chain = cipher_chain->next) {
208                 printf("%s%c", cipher_chain->cipher->name,
209                     (cipher_chain->next != NULL) ? ',' : '\n');
210                 klen += cipher_chain->cipher->klen;
211         }
212
213         printf("Key Length:\t\t%d bits\n", klen*8);
214         printf("CRC Key Data:\t\t%#x\n", info->hdr->crc_keys);
215         printf("Sector size:\t\t%d\n", info->hdr->sec_sz);
216         printf("Volume size:\t\t%zu sectors\n", info->size);
217 }
218
219 static
220 struct tcplay_info *
221 new_info(const char *dev, struct tc_cipher_chain *cipher_chain,
222     struct pbkdf_prf_algo *prf, struct tchdr_dec *hdr, off_t start)
223 {
224         struct tcplay_info *info;
225         int i;
226         int error;
227
228         if ((info = (struct tcplay_info *)alloc_safe_mem(sizeof(*info))) == NULL) {
229                 tc_log(1, "could not allocate safe info memory\n");
230                 return NULL;
231         }
232
233         info->dev = dev;
234         info->cipher_chain = cipher_chain;
235         info->pbkdf_prf = prf;
236         info->start = start;
237         info->hdr = hdr;
238         info->size = hdr->sz_mk_scope / hdr->sec_sz;    /* volume size */
239         info->skip = hdr->off_mk_scope / hdr->sec_sz;   /* iv skip */
240         info->offset = hdr->off_mk_scope / hdr->sec_sz; /* block offset */
241
242         /* Associate a key out of the key pool with each cipher in the chain */
243         error = tc_cipher_chain_populate_keys(cipher_chain, hdr->keys);
244         if (error) {
245                 tc_log(1, "could not populate keys in cipher chain\n");
246                 return NULL;
247         }
248
249         for (; cipher_chain != NULL; cipher_chain = cipher_chain->next) {
250                 for (i = 0; i < cipher_chain->cipher->klen; i++)
251                         sprintf(&cipher_chain->dm_key[i*2], "%02x",
252                             cipher_chain->key[i]);
253         }
254
255         return info;
256 }
257
258 int
259 adjust_info(struct tcplay_info *info, struct tcplay_info *hinfo)
260 {
261         if (hinfo->hdr->sz_hidvol == 0)
262                 return 1;
263
264         info->size -= hinfo->hdr->sz_hidvol / hinfo->hdr->sec_sz;
265         return 0;
266 }
267
268 int
269 process_hdr(const char *dev, unsigned char *pass, int passlen,
270     struct tchdr_enc *ehdr, struct tcplay_info **pinfo)
271 {
272         struct tchdr_dec *dhdr;
273         struct tcplay_info *info;
274         unsigned char *key;
275         int i, j, found, error;
276
277         *pinfo = NULL;
278
279         if ((key = alloc_safe_mem(MAX_KEYSZ)) == NULL) {
280                 tc_log(1, "could not allocate safe key memory\n");
281                 return ENOMEM;
282         }
283
284         /* Start search for correct algorithm combination */
285         found = 0;
286         for (i = 0; !found && pbkdf_prf_algos[i].name != NULL; i++) {
287 #ifdef DEBUG
288                 printf("\nTrying PRF algo %s (%d)\n", pbkdf_prf_algos[i].name,
289                     pbkdf_prf_algos[i].iteration_count);
290                 printf("Salt: ");
291                 print_hex(ehdr->salt, 0, sizeof(ehdr->salt));
292 #endif
293                 error = pbkdf2(pass, passlen,
294                     ehdr->salt, sizeof(ehdr->salt),
295                     pbkdf_prf_algos[i].iteration_count,
296                     pbkdf_prf_algos[i].name, MAX_KEYSZ, key);
297
298                 if (error) {
299                         tc_log(1, "pbkdf failed for algorithm %s\n",
300                             pbkdf_prf_algos[i].name);
301                         return EINVAL;
302                 }
303
304 #if 0
305                 printf("Derived Key: ");
306                 print_hex(key, 0, MAX_KEYSZ);
307 #endif
308
309                 for (j = 0; !found && tc_cipher_chains[j] != NULL; j++) {
310 #ifdef DEBUG
311                         printf("\nTrying cipher chain %d\n", j);
312 #endif
313
314                         dhdr = decrypt_hdr(ehdr, tc_cipher_chains[j], key);
315                         if (dhdr == NULL) {
316                                 tc_log(1, "hdr decryption failed for cipher "
317                                     "chain %d\n", j);
318                                 return EINVAL;
319                         }
320
321                         if (verify_hdr(dhdr)) {
322 #ifdef DEBUG
323                                 printf("tc_str: %.4s, tc_ver: %zd, tc_min_ver: %zd, "
324                                     "crc_keys: %d, sz_vol: %"PRIu64", "
325                                     "off_mk_scope: %"PRIu64", sz_mk_scope: %"PRIu64", "
326                                     "flags: %d, sec_sz: %d crc_dhdr: %d\n",
327                                     dhdr->tc_str, dhdr->tc_ver, dhdr->tc_min_ver,
328                                     dhdr->crc_keys, dhdr->sz_vol, dhdr->off_mk_scope,
329                                     dhdr->sz_mk_scope, dhdr->flags, dhdr->sec_sz,
330                                     dhdr->crc_dhdr);
331 #endif
332                                 found = 1;
333                         } else {
334                                 free_safe_mem(dhdr);
335                         }
336                 }
337         }
338
339         free_safe_mem(key);
340
341         if (!found)
342                 return EINVAL;
343
344         if ((info = new_info(dev, tc_cipher_chains[j-1], &pbkdf_prf_algos[i-1],
345             dhdr, 0)) == NULL) {
346                 return ENOMEM;
347         }
348
349         *pinfo = info;
350         return 0;
351 }
352
353 int
354 create_volume(const char *dev, int hidden, const char *keyfiles[], int nkeyfiles,
355     const char *h_keyfiles[], int n_hkeyfiles, struct pbkdf_prf_algo *prf_algo,
356     struct tc_cipher_chain *cipher_chain, struct pbkdf_prf_algo *h_prf_algo,
357     struct tc_cipher_chain *h_cipher_chain, char *passphrase,
358     char *h_passphrase, size_t hidden_blocks_in, int interactive)
359 {
360         char *pass, *pass_again;
361         char *h_pass = NULL;
362         char buf[1024];
363         size_t blocks, blksz, hidden_blocks = 0;
364         struct tchdr_enc *ehdr, *hehdr = NULL;
365         int64_t tmp;
366         int error, r;
367
368         if (cipher_chain == NULL)
369                 cipher_chain = tc_cipher_chains[0];
370         if (prf_algo == NULL)
371                 prf_algo = &pbkdf_prf_algos[0];
372         if (h_cipher_chain == NULL)
373                 h_cipher_chain = cipher_chain;
374         if (h_prf_algo == NULL)
375                 h_prf_algo = prf_algo;
376
377         if ((error = get_disk_info(dev, &blocks, &blksz)) != 0) {
378                 tc_log(1, "could not get disk info\n");
379                 return -1;
380         }
381
382         if (blocks <= MIN_VOL_BLOCKS) {
383                 tc_log(1, "Cannot create volumes on devices with less "
384                     "than %d blocks/sectors\n", MIN_VOL_BLOCKS);
385                 return -1;
386         }
387
388         if (interactive) {
389                 if (((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) ||
390                    ((pass_again = alloc_safe_mem(MAX_PASSSZ)) == NULL)) {
391                         tc_log(1, "could not allocate safe passphrase memory\n");
392                         return -1;
393                 }
394
395                 if ((error = read_passphrase("Passphrase: ", pass, MAX_PASSSZ, 0) ||
396                    (read_passphrase("Repeat passphrase: ", pass_again,
397                    MAX_PASSSZ, 0)))) {
398                         tc_log(1, "could not read passphrase\n");
399                         return -1;
400                 }
401
402                 if (strcmp(pass, pass_again) != 0) {
403                         tc_log(1, "Passphrases don't match\n");
404                         return -1;
405                 }
406
407                 free_safe_mem(pass_again);
408         } else {
409                 /* In batch mode, use provided passphrase */
410                 if ((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
411                         tc_log(1, "could not allocate safe "
412                             "passphrase memory");
413                         return -1;
414                 }
415
416                 if (passphrase != NULL)
417                         strcpy(pass, passphrase);
418         }
419
420         if (nkeyfiles > 0) {
421                 /* Apply keyfiles to 'pass' */
422                 if ((error = apply_keyfiles(pass, MAX_PASSSZ, keyfiles,
423                     nkeyfiles))) {
424                         tc_log(1, "could not apply keyfiles\n");
425                 }
426         }
427
428         if (hidden) {
429                 if (interactive) {
430                         if (((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) ||
431                            ((pass_again = alloc_safe_mem(MAX_PASSSZ)) == NULL)) {
432                                 tc_log(1, "could not allocate safe "
433                                     "passphrase memory\n");
434                                 return -1;
435                         }
436
437                         if ((error = read_passphrase("Passphrase for hidden volume: ",
438                            h_pass, MAX_PASSSZ, 0) ||
439                            (read_passphrase("Repeat passphrase: ", pass_again,
440                            MAX_PASSSZ, 0)))) {
441                                 tc_log(1, "could not read passphrase\n");
442                                 return -1;
443                         }
444
445                         if (strcmp(h_pass, pass_again) != 0) {
446                                 tc_log(1, "Passphrases for hidden volume don't "
447                                     "match\n");
448                                 return -1;
449                         }
450
451                         free_safe_mem(pass_again);
452                 } else {
453                         /* In batch mode, use provided passphrase */
454                         if ((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
455                                 tc_log(1, "could not allocate safe "
456                                     "passphrase memory");
457                                 return -1;
458                         }
459
460                         if (h_passphrase != NULL)
461                                 strcpy(h_pass, h_passphrase);
462                 }
463
464                 if (n_hkeyfiles > 0) {
465                         /* Apply keyfiles to 'h_pass' */
466                         if ((error = apply_keyfiles(h_pass, MAX_PASSSZ, h_keyfiles,
467                         n_hkeyfiles))) {
468                                 tc_log(1, "could not apply keyfiles\n");
469                                 return -1;
470                         }
471                 }
472
473                 if (interactive) {
474                         hidden_blocks = 0;
475                 } else {
476                         hidden_blocks = hidden_blocks_in;
477                         if (hidden_blocks == 0) {
478                                 tc_log(1, "hidden_blocks to create volume "
479                                     "cannot be zero!\n");
480                                 return -1;
481                         }
482                 }
483
484                 /* This only happens in interactive mode */
485                 while (hidden_blocks == 0) {
486                         if ((r = humanize_number(buf, strlen("XXX MB"),
487                             (int64_t)(blocks * blksz), "B", 0, 0)) < 0) {
488                                 sprintf(buf, "%zu bytes", (blocks * blksz));
489                         }
490
491                         printf("The total volume size of %s is %s (bytes)\n", dev, buf);
492                         memset(buf, 0, sizeof(buf));
493                         printf("Size of hidden volume (e.g. 127M): ");
494                         fflush(stdout);
495
496                         if ((fgets(buf, sizeof(buf), stdin)) == NULL) {
497                                 tc_log(1, "Could not read from stdin\n");
498                                 return -1;
499                         }
500
501                         /* get rid of trailing newline */
502                         buf[strlen(buf)-1] = '\0';
503                         if ((error = dehumanize_number(buf,
504                             &tmp)) != 0) {
505                                 tc_log(1, "Could not interpret input: %s\n", buf);
506                                 return -1;
507                         }
508
509                         hidden_blocks = (size_t)tmp;
510                         hidden_blocks /= blksz;
511                         if (hidden_blocks >= blocks - MIN_VOL_BLOCKS) {
512                                 tc_log(1, "Hidden volume needs to be "
513                                     "smaller than the outer volume\n");
514                                 hidden_blocks = 0;
515                                 continue;
516                         }
517                 }
518         }
519
520         if (interactive) {
521                 /* Show summary and ask for confirmation */
522                 printf("Summary of actions:\n");
523                 printf(" - Completely erase *EVERYTHING* on %s\n", dev);
524                 printf(" - Create %svolume on %s\n", hidden?("outer "):"", dev);
525                 if (hidden) {
526                         printf(" - Create hidden volume of %zu bytes at end of "
527                             "outer volume\n",
528                             hidden_blocks * blksz);
529                 }
530
531                 printf("\n Are you sure you want to proceed? (y/n) ");
532                 fflush(stdout);
533                 if ((fgets(buf, sizeof(buf), stdin)) == NULL) {
534                         tc_log(1, "Could not read from stdin\n");
535                         return -1;
536                 }
537
538                 if ((buf[0] != 'y') && (buf[0] != 'Y')) {
539                         tc_log(1, "User cancelled action(s)\n");
540                         return -1;
541                 }
542         }
543
544         /* erase volume */
545         if ((error = secure_erase(dev, blocks * blksz, blksz)) != 0) {
546                 tc_log(1, "could not securely erase device %s\n", dev);
547                 return -1;
548         }
549
550         /* create encrypted headers */
551         ehdr = create_hdr(pass, (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass),
552             prf_algo, cipher_chain, blksz, blocks, MIN_VOL_BLOCKS,
553             blocks-MIN_VOL_BLOCKS, 0);
554         if (ehdr == NULL) {
555                 tc_log(1, "Could not create header\n");
556                 return -1;
557         }
558
559         if (hidden) {
560                 hehdr = create_hdr(h_pass,
561                     (n_hkeyfiles > 0)?MAX_PASSSZ:strlen(h_pass), h_prf_algo,
562                     h_cipher_chain,
563                     blksz, blocks, blocks - hidden_blocks, hidden_blocks, 1);
564                 if (hehdr == NULL) {
565                         tc_log(1, "Could not create hidden volume header\n");
566                         return -1;
567                 }
568         }
569
570         if ((error = write_mem(dev, 0, blksz, ehdr, sizeof(*ehdr))) != 0) {
571                 tc_log(1, "Could not write volume header to device\n");
572                 return -1;
573         }
574
575         if (hidden) {
576                 if ((error = write_mem(dev, HDR_OFFSET_HIDDEN, blksz, hehdr,
577                     sizeof(*hehdr))) != 0) {
578                         tc_log(1, "Could not write hidden volume header to "
579                             "device\n");
580                         return -1;
581                 }
582         }
583
584         return 0;
585 }
586
587 static
588 struct tcplay_info *
589 info_map_common(const char *dev, int sflag, const char *sys_dev,
590     int protect_hidden, const char *keyfiles[], int nkeyfiles,
591     const char *h_keyfiles[], int n_hkeyfiles, char *passphrase,
592     char *passphrase_hidden, int interactive, int retries, time_t timeout)
593 {
594         struct tchdr_enc *ehdr, *hehdr = NULL;
595         struct tcplay_info *info, *hinfo = NULL;
596         char *pass;
597         char *h_pass;
598         int error, error2 = 0;
599         size_t sz;
600
601         info = NULL;
602         if (retries < 1)
603                 retries = 1;
604
605         while ((info == NULL) && retries-- > 0)
606         {
607                 h_pass = NULL;
608                 ehdr = NULL;
609                 hehdr = NULL;
610
611                 if ((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
612                         tc_log(1, "could not allocate safe passphrase memory\n");
613                         return NULL;
614                 }
615
616                 if (interactive) {
617                         if ((error = read_passphrase("Passphrase: ", pass,
618                             MAX_PASSSZ, timeout))) {
619                                 tc_log(1, "could not read passphrase\n");
620                                 return NULL;
621                         }
622                 } else {
623                         /* In batch mode, use provided passphrase */
624                         if (passphrase != NULL)
625                                 strcpy(pass, passphrase);
626                 }
627
628                 if (nkeyfiles > 0) {
629                         /* Apply keyfiles to 'pass' */
630                         if ((error = apply_keyfiles(pass, MAX_PASSSZ, keyfiles,
631                             nkeyfiles))) {
632                                 tc_log(1, "could not apply keyfiles");
633                                 return NULL;
634                         }
635                 }
636
637                 if (protect_hidden) {
638                         if ((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
639                                 tc_log(1, "could not allocate safe passphrase memory\n");
640                                 return NULL;
641                         }
642
643                         if (interactive) {
644                                 if ((error = read_passphrase(
645                                     "Passphrase for hidden volume: ", h_pass,
646                                     MAX_PASSSZ, timeout))) {
647                                         tc_log(1, "could not read passphrase\n");
648                                         return NULL;
649                                 }
650                         } else {
651                                 /* In batch mode, use provided passphrase */
652                                 if (passphrase_hidden != NULL)
653                                         strcpy(h_pass, passphrase_hidden);
654                         }
655
656                         if (n_hkeyfiles > 0) {
657                                 /* Apply keyfiles to 'pass' */
658                                 if ((error = apply_keyfiles(h_pass, MAX_PASSSZ, h_keyfiles,
659                                     n_hkeyfiles))) {
660                                         tc_log(1, "could not apply keyfiles");
661                                         return NULL;
662                                 }
663                         }
664                 }
665
666                 sz = HDRSZ;
667                 ehdr = (struct tchdr_enc *)read_to_safe_mem((sflag) ? sys_dev : dev,
668                     (sflag) ? HDR_OFFSET_SYS : 0, &sz);
669                 if (ehdr == NULL) {
670                         tc_log(1, "error read hdr_enc: %s", dev);
671                         return NULL;
672                 }
673
674                 if (!sflag) {
675                         sz = HDRSZ;
676                         hehdr = (struct tchdr_enc *)read_to_safe_mem(dev,
677                             HDR_OFFSET_HIDDEN, &sz);
678                         if (hehdr == NULL) {
679                                 tc_log(1, "error read hdr_enc: %s", dev);
680                                 return NULL;
681                         }
682                 } else {
683                         hehdr = NULL;
684                 }
685
686                 error = process_hdr(dev, pass, (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass),
687                     ehdr, &info);
688
689                 /*
690                  * Try to process hidden header if we have to protect the hidden
691                  * volume, or the decryption/verification of the main header
692                  * failed.
693                  */
694                 if (hehdr && (error || protect_hidden)) {
695                         if (error) {
696                                 error2 = process_hdr(dev, pass,
697                                     (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass), hehdr,
698                                     &info);
699                         } else if (protect_hidden) {
700                                 error2 = process_hdr(dev, h_pass,
701                                     (n_hkeyfiles > 0)?MAX_PASSSZ:strlen(h_pass), hehdr,
702                                     &hinfo);
703                         }
704                 }
705
706                 /* We need both to protect a hidden volume */
707                 if ((protect_hidden && (error || error2)) ||
708                     (error && error2)) {
709                         tc_log(1, "Incorrect password or not a TrueCrypt volume\n");
710                         info = NULL;
711                         hinfo = NULL;
712
713                         /* Try again (or finish) */
714                         free_safe_mem(pass);
715                         if (h_pass)
716                                 free_safe_mem(h_pass);
717                         if (ehdr)
718                                 free_safe_mem(ehdr);
719                         if (hehdr)
720                                 free_safe_mem(hehdr);
721                         continue;
722                 }
723
724                 if (protect_hidden) {
725                         if (adjust_info(info, hinfo) != 0) {
726                                 tc_log(1, "Could not protect hidden volume\n");
727                                 return NULL;
728                         }
729                 }
730         }
731
732         return info;
733 }
734
735 int
736 info_volume(const char *device, int sflag, const char *sys_dev,
737     int protect_hidden, const char *keyfiles[], int nkeyfiles,
738     const char *h_keyfiles[], int n_hkeyfiles,
739     char *passphrase, char *passphrase_hidden, int interactive, int retries,
740     time_t timeout)
741 {
742         struct tcplay_info *info;
743
744         info = info_map_common(device, sflag, sys_dev, protect_hidden,
745             keyfiles, nkeyfiles, h_keyfiles, n_hkeyfiles,
746             passphrase, passphrase_hidden, interactive, retries, timeout);
747
748         if (info != NULL) {
749                 if (interactive)
750                         print_info(info);
751         }
752
753         return (info != NULL) ? 0 : -1;
754 }
755
756 int
757 map_volume(const char *map_name, const char *device, int sflag,
758     const char *sys_dev, int protect_hidden, const char *keyfiles[],
759     int nkeyfiles, const char *h_keyfiles[], int n_hkeyfiles,
760     char *passphrase, char *passphrase_hidden, int interactive, int retries,
761     time_t timeout)
762
763 {
764         struct tcplay_info *info;
765         int error;
766
767         info = info_map_common(device, sflag, sys_dev, protect_hidden,
768             keyfiles, nkeyfiles, h_keyfiles, n_hkeyfiles,
769             passphrase, passphrase_hidden, interactive, retries, timeout);
770
771         if (info == NULL)
772                 return -1;
773
774         if ((error = dm_setup(map_name, info)) != 0) {
775                 tc_log(1, "Could not set up mapping %s\n", map_name);
776                 return -1;
777         }
778
779         if (interactive)
780                 printf("All ok!");
781
782         return 0;
783 }
784
785 static
786 int
787 dm_remove_device(const char *name)
788 {
789         struct dm_task *dmt = NULL;
790         int ret = EINVAL;
791
792         if ((dmt = dm_task_create(DM_DEVICE_REMOVE)) == NULL)
793                 goto out;
794
795         if ((dm_task_set_name(dmt, name)) == 0)
796                 goto out;
797
798         if ((dm_task_run(dmt)) == 0)
799                 goto out;
800
801         ret = 0;
802 out:
803         if (dmt)
804                 dm_task_destroy(dmt);
805
806         return ret;
807 }
808
809 int
810 dm_setup(const char *mapname, struct tcplay_info *info)
811 {
812         struct tc_cipher_chain *cipher_chain;
813         struct dm_task *dmt = NULL;
814         struct dm_info dmi;
815         char *params = NULL;
816         char *uu;
817         char *uu_stack[64];
818         int uu_stack_idx;
819         uint32_t status;
820         int ret = 0;
821         int j;
822         off_t start, offset;
823         char dev[PATH_MAX];
824         char map[PATH_MAX];
825
826         if ((params = alloc_safe_mem(512)) == NULL) {
827                 tc_log(1, "could not allocate safe parameters memory");
828                 return ENOMEM;
829         }
830
831         strcpy(dev, info->dev);
832         start = info->start;
833         offset = info->offset;
834         uu_stack_idx = 0;
835
836         /* Get to the end of the chain */
837         for (cipher_chain = info->cipher_chain; cipher_chain->next != NULL;
838             cipher_chain = cipher_chain->next)
839                 ;
840
841         for (j= 0; cipher_chain != NULL;
842             cipher_chain = cipher_chain->prev, j++) {
843                 /* aes-cbc-essiv:sha256 7997f8af... 0 /dev/ad0s0a 8 */
844                 /*                         iv off---^  block off--^ */
845                 snprintf(params, 512, "%s %s %"PRIu64 " %s %"PRIu64,
846                     cipher_chain->cipher->dm_crypt_str, cipher_chain->dm_key,
847                     info->skip, dev, offset);
848 #ifdef DEBUG
849                 printf("Params: %s\n", params);
850 #endif
851
852                 if ((dmt = dm_task_create(DM_DEVICE_CREATE)) == NULL) {
853                         tc_log(1, "dm_task_create failed\n");
854                         ret = -1;
855                         goto out;
856                 }
857
858                 /*
859                  * If this is the last element in the cipher chain, use the
860                  * final map name. Otherwise pick a secondary name...
861                  */
862                 if (cipher_chain->prev == NULL)
863                         strcpy(map, mapname);
864                 else
865                         sprintf(map, "%s.%d", mapname, j);
866
867                 if ((dm_task_set_name(dmt, map)) == 0) {
868                         tc_log(1, "dm_task_set_name failed\n");
869                         ret = -1;
870                         goto out;
871                 }
872
873                 uuid_create(&info->uuid, &status);
874                 if (status != uuid_s_ok) {
875                         tc_log(1, "uuid_create failed\n");
876                         ret = -1;
877                         goto out;
878                 }
879
880                 uuid_to_string(&info->uuid, &uu, &status);
881                 if (uu == NULL) {
882                         tc_log(1, "uuid_to_string failed\n");
883                         ret = -1;
884                         goto out;
885                 }
886
887                 if ((dm_task_set_uuid(dmt, uu)) == 0) {
888                         free(uu);
889                         tc_log(1, "dm_task_set_uuid failed\n");
890                         ret = -1;
891                         goto out;
892                 }
893
894                 free(uu);
895
896                 if ((dm_task_add_target(dmt, start, info->size, "crypt", params)) == 0) {
897                         tc_log(1, "dm_task_add_target failed\n");
898                         ret = -1;
899                         goto out;
900                 }
901
902                 if ((dm_task_run(dmt)) == 0) {
903                         tc_log(1, "dm_task_task_run failed\n");
904                         ret = -1;
905                         goto out;
906                 }
907
908                 if ((dm_task_get_info(dmt, &dmi)) == 0) {
909                         tc_log(1, "dm_task_get info failed\n");
910                         /* XXX: probably do more than just erroring out... */
911                         ret = -1;
912                         goto out;
913                 }
914
915                 asprintf(&uu_stack[uu_stack_idx++], "%s", map);
916
917                 offset = 0;
918                 start = 0;
919                 sprintf(dev, "/dev/mapper/%s.%d", mapname, j);
920
921                 dm_task_destroy(dmt);
922         }
923
924 out:
925         /*
926          * If an error occured, try to unroll changes made before it
927          * happened.
928          */
929         if (ret) {
930                 j = uu_stack_idx;
931                 while (j > 0) {
932 #ifdef DEBUG
933                         printf("Unrolling dm changes! j = %d (%s)\n", j-1,
934                             uu_stack[j-1]);
935 #endif
936                         if ((ret = dm_remove_device(uu_stack[--j])) != 0) {
937                                 tc_log(1, "Tried to unroll dm changes, "
938                                     "giving up.\n");
939                                 break;
940                         }
941                 }
942         }
943
944         while (uu_stack_idx > 0)
945                 free(uu_stack[--uu_stack_idx]);
946
947         free_safe_mem(params);
948
949         return ret;
950 }
951
952 int
953 dm_teardown(const char *mapname, const char *device __unused)
954 {
955 #if 0
956         struct dm_task *dmt = NULL;
957         struct dm_info dmi;
958 #endif
959         char map[PATH_MAX];
960         int i, error;
961
962         if ((error = dm_remove_device(mapname)) != 0) {
963                 tc_log(1, "Could not remove mapping %s\n", mapname);
964                 return error;
965         }
966
967         /* Try to remove other cascade devices */
968         for (i = 2; i >= 0; i--) {
969                 sprintf(map, "%s.%d", mapname, i);
970                 dm_remove_device(map);
971         }
972
973         return 0;
974 }
975
976 struct tc_crypto_algo *
977 check_cipher(const char *cipher, int quiet)
978 {
979         int i, found = 0;
980
981         for (i = 0; tc_crypto_algos[i].name != NULL; i++) {
982                 if (strcmp(cipher, tc_crypto_algos[i].name) == 0) {
983                         found = 1;
984                         break;
985                 }
986         }
987
988         if (!found && !quiet) {
989                 fprintf(stderr, "Valid ciphers are: ");
990                 for (i = 0; tc_crypto_algos[i].name != NULL; i++)
991                         fprintf(stderr, "%s ", tc_crypto_algos[i].name);
992                 fprintf(stderr, "\n");
993                 return NULL;
994         }
995
996         return &tc_crypto_algos[i];
997 }
998
999 struct tc_cipher_chain *
1000 check_cipher_chain(char *cipher_chain, int quiet)
1001 {
1002         struct tc_cipher_chain *cipher = NULL;
1003         int i,k, nciphers = 0, mismatch = 0;
1004         char *ciphers[8];
1005         char *tmp_chain, *tmp_chain_free;
1006         char *token;
1007
1008         if ((tmp_chain = strdup(cipher_chain)) == NULL) {
1009                 tc_log(1, "Could not allocate strdup memory\n");
1010                 return NULL;
1011         }
1012
1013         tmp_chain_free = tmp_chain;
1014
1015         while ((token = strsep(&tmp_chain, ",")) != NULL)
1016                 ciphers[nciphers++] = token;
1017
1018         cipher = NULL;
1019
1020         for (i = 0; valid_cipher_chains[i][0] != NULL; i++) {
1021                 mismatch = 0;
1022
1023                 for (k = 0; (valid_cipher_chains[i][k] != NULL); k++) {
1024                         /*
1025                          * If there are more ciphers in the chain than in the
1026                          * ciphers[] variable this is not the right chain.
1027                          */
1028                         if (k == nciphers) {
1029                                 mismatch = 1;
1030                                 break;
1031                         }
1032
1033                         if (strcmp(ciphers[k], valid_cipher_chains[i][k]) != 0)
1034                                 mismatch = 1;
1035                 }
1036
1037                 /*
1038                  * If all ciphers matched and there are exactly nciphers,
1039                  * then we found the right cipher chain.
1040                  */
1041                 if ((k == nciphers) && !mismatch) {
1042                         cipher = tc_cipher_chains[i];
1043                         break;
1044                 }
1045         }
1046
1047         if (cipher == NULL) {
1048                 tc_log(1, "Invalid cipher: %s\n", cipher_chain);
1049                 if (!quiet) {
1050                         fprintf(stderr, "Valid cipher chains are:\n");
1051                         for (i = 0; valid_cipher_chains[i][0] != NULL; i++) {
1052                                 for (k = 0; valid_cipher_chains[i][k] != NULL;
1053                                     k++) {
1054                                         fprintf(stderr, "%s%c",
1055                                             valid_cipher_chains[i][k],
1056                                             (valid_cipher_chains[i][k+1] != NULL) ?
1057                                             ',' : '\0');
1058                                 }
1059                                 fprintf(stderr, "\n");
1060                         }
1061                 }
1062         }
1063
1064         free(tmp_chain_free);
1065         return cipher;
1066 }
1067
1068 struct pbkdf_prf_algo *
1069 check_prf_algo(char *algo, int quiet)
1070 {
1071         int i, found = 0;
1072
1073         for (i = 0; pbkdf_prf_algos[i].name != NULL; i++) {
1074                 if (strcmp(algo, pbkdf_prf_algos[i].name) == 0) {
1075                         found = 1;
1076                         break;
1077                 }
1078         }
1079
1080         if (!found && !quiet) {
1081                 fprintf(stderr, "Valid PBKDF PRF algorithms are: ");
1082                 for (i = 0; pbkdf_prf_algos[i].name != NULL; i++)
1083                         fprintf(stderr, "%s ", pbkdf_prf_algos[i].name);
1084                 fprintf(stderr, "\n");
1085                 return NULL;
1086         }
1087
1088         return &pbkdf_prf_algos[i];
1089 }
1090
1091 int
1092 tc_play_init(void)
1093 {
1094         int error;
1095
1096         if ((error = tc_build_cipher_chains()) != 0)
1097                 return error;
1098
1099         if ((error = tc_crypto_init()) != 0)
1100                 return error;
1101
1102         return 0;
1103 }