sh: Make patmatch() non-recursive.
[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
30 #if defined(__linux__)
31 #define _GNU_SOURCE /* for asprintf */
32 #endif
33
34 #include <sys/types.h>
35
36 #if defined(__DragonFly__)
37 #include <sys/param.h>
38 #endif
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <inttypes.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include <string.h>
47 #include <err.h>
48 #include <time.h>
49 #if defined(__linux__)
50 #include <libdevmapper.h>
51 #include <uuid/uuid.h>
52 #elif defined(__DragonFly__)
53 #include <libdm.h>
54 #include <uuid.h>
55 #endif
56
57 #include "crc32.h"
58 #include "tcplay.h"
59 #include "humanize.h"
60
61
62 /* XXX TODO:
63  *  - LRW-benbi support? needs further work in dm-crypt and even opencrypto
64  *  - secure buffer review (i.e: is everything that needs it using secure mem?)
65  *  - mlockall? (at least MCL_FUTURE, which is the only one we support)
66  */
67
68 summary_fn_t summary_fn = NULL;
69 int tc_internal_verbose = 1;
70 char tc_internal_log_buffer[LOG_BUFFER_SZ];
71
72 void
73 tc_log(int is_err, const char *fmt, ...)
74 {
75         va_list ap;
76         FILE *fp;
77
78         if (is_err)
79                 fp = stderr;
80         else
81                 fp = stdout;
82
83         va_start(ap, fmt);
84
85         vsnprintf(tc_internal_log_buffer, LOG_BUFFER_SZ, fmt, ap);
86
87         va_end(ap);
88
89         if (tc_internal_verbose)
90             fprintf(fp, "%s", tc_internal_log_buffer);
91 }
92
93 /* Supported algorithms */
94 struct pbkdf_prf_algo pbkdf_prf_algos[] = {
95         { "RIPEMD160",  2000 }, /* needs to come before the other RIPEMD160 */
96         { "RIPEMD160",  1000 },
97         { "SHA512",     1000 },
98         { "whirlpool",  1000 },
99         { NULL,         0    }
100 };
101
102 struct tc_crypto_algo tc_crypto_algos[] = {
103 #if 0
104         /* XXX: turns out TC doesn't support AES-128-XTS */
105         { "AES-128-XTS",        "aes-xts-plain",        32,     8 },
106         { "TWOFISH-128-XTS",    "twofish-xts-plain",    32,     8 },
107         { "SERPENT-128-XTS",    "serpent-xts-plain",    32,     8 },
108 #endif
109         { "AES-256-XTS",        "aes-xts-plain",        64,     8 },
110         { "TWOFISH-256-XTS",    "twofish-xts-plain",    64,     8 },
111         { "SERPENT-256-XTS",    "serpent-xts-plain",    64,     8 },
112         { NULL,                 NULL,                   0,      0 }
113 };
114
115 const char *valid_cipher_chains[][MAX_CIPHER_CHAINS] = {
116         { "AES-256-XTS", NULL },
117         { "TWOFISH-256-XTS", NULL },
118         { "SERPENT-256-XTS", NULL },
119         { "AES-256-XTS", "TWOFISH-256-XTS", "SERPENT-256-XTS", NULL },
120         { "SERPENT-256-XTS", "TWOFISH-256-XTS", "AES-256-XTS", NULL },
121 #if 0
122         /* It seems that all the two-way cascades are the other way round... */
123         { "AES-256-XTS", "TWOFISH-256-XTS", NULL },
124         { "SERPENT-256-XTS", "AES-256-XTS", NULL },
125         { "TWOFISH-256-XTS", "SERPENT-256-XTS", NULL },
126
127 #endif
128         { "TWOFISH-256-XTS", "AES-256-XTS", NULL },
129         { "AES-256-XTS", "SERPENT-256-XTS", NULL },
130         { "SERPENT-256-XTS", "TWOFISH-256-XTS", NULL },
131         { NULL }
132 };
133
134 struct tc_cipher_chain *tc_cipher_chains[MAX_CIPHER_CHAINS];
135
136 static
137 int
138 tc_build_cipher_chains(void)
139 {
140         struct tc_cipher_chain *chain, *elem, *prev;
141         int i = 0;
142         int k;
143
144         while (valid_cipher_chains[i][0] != NULL) {
145                 chain = NULL;
146                 prev = NULL;
147                 k = 0;
148
149                 while (valid_cipher_chains[i][k] != NULL) {
150                         if ((elem = alloc_safe_mem(sizeof(*elem))) == NULL) {
151                                 tc_log(1, "Error allocating memory for "
152                                    "cipher chain\n");
153                                 return -1;
154                         }
155
156                         /* Initialize first element of chain */
157                         if (chain == NULL) {
158                                 chain = elem;
159                                 elem->prev = NULL;
160                         }
161
162                         /* Populate previous element */
163                         if (prev != NULL) {
164                                 prev->next = elem;
165                                 elem->prev = prev;
166                         }
167
168                         /* Assume we are the last element in the chain */
169                         elem->next = NULL;
170
171                         /* Initialize other fields */
172                         elem->cipher = check_cipher(valid_cipher_chains[i][k], 0);
173                         if (elem->cipher == NULL)
174                                 return -1;
175
176                         elem->key = NULL;
177
178                         prev = elem;
179                         ++k;
180                 }
181
182                 /* Store cipher chain */
183                 tc_cipher_chains[i++] = chain;
184
185                 /* Integrity check */
186                 if (i >= MAX_CIPHER_CHAINS) {
187                         tc_log(1, "FATAL: tc_cipher_chains is full!!\n");
188                         return -1;
189                 }
190
191                 /* Make sure array is NULL terminated */
192                 tc_cipher_chains[i] = NULL;
193         }
194
195         return 0;
196 }
197
198 #ifdef DEBUG
199 static void
200 print_hex(unsigned char *buf, off_t start, size_t len)
201 {
202         size_t i;
203
204         for (i = start; i < start+len; i++)
205                 printf("%02x", buf[i]);
206
207         printf("\n");
208 }
209 #endif
210
211 void
212 print_info(struct tcplay_info *info)
213 {
214         struct tc_cipher_chain *cipher_chain;
215         int klen = 0;
216
217         printf("PBKDF2 PRF:\t\t%s\n", info->pbkdf_prf->name);
218         printf("PBKDF2 iterations:\t%d\n", info->pbkdf_prf->iteration_count);
219
220         printf("Cipher:\t\t\t");
221         for (cipher_chain = info->cipher_chain;
222             cipher_chain != NULL;
223             cipher_chain = cipher_chain->next) {
224                 printf("%s%c", cipher_chain->cipher->name,
225                     (cipher_chain->next != NULL) ? ',' : '\n');
226                 klen += cipher_chain->cipher->klen;
227         }
228
229         printf("Key Length:\t\t%d bits\n", klen*8);
230         printf("CRC Key Data:\t\t%#x\n", info->hdr->crc_keys);
231         printf("Sector size:\t\t%d\n", info->hdr->sec_sz);
232         printf("Volume size:\t\t%zu sectors\n", info->size);
233 #if 0
234         /* Don't print this; it's always 0 and is rather confusing */
235         printf("Volume offset:\t\t%"PRIu64"\n", (uint64_t)info->start);
236 #endif
237         printf("IV offset:\t\t%"PRIu64"\n", (uint64_t)info->skip);
238         printf("Block offset:\t\t%"PRIu64"\n", (uint64_t)info->offset);
239 }
240
241 static
242 struct tcplay_info *
243 new_info(const char *dev, struct tc_cipher_chain *cipher_chain,
244     struct pbkdf_prf_algo *prf, struct tchdr_dec *hdr, off_t start)
245 {
246         struct tc_cipher_chain *chain_start;
247         struct tcplay_info *info;
248         int i;
249         int error;
250
251         chain_start = cipher_chain;
252
253         if ((info = (struct tcplay_info *)alloc_safe_mem(sizeof(*info))) == NULL) {
254                 tc_log(1, "could not allocate safe info memory\n");
255                 return NULL;
256         }
257
258         info->dev = dev;
259         info->cipher_chain = cipher_chain;
260         info->pbkdf_prf = prf;
261         info->start = start;
262         info->hdr = hdr;
263         info->size = hdr->sz_mk_scope / hdr->sec_sz;    /* volume size */
264         info->skip = hdr->off_mk_scope / hdr->sec_sz;   /* iv skip */
265         info->offset = hdr->off_mk_scope / hdr->sec_sz; /* block offset */
266
267         /* Associate a key out of the key pool with each cipher in the chain */
268         error = tc_cipher_chain_populate_keys(cipher_chain, hdr->keys);
269         if (error) {
270                 tc_log(1, "could not populate keys in cipher chain\n");
271                 return NULL;
272         }
273
274         for (; cipher_chain != NULL; cipher_chain = cipher_chain->next) {
275                 for (i = 0; i < cipher_chain->cipher->klen; i++)
276                         sprintf(&cipher_chain->dm_key[i*2], "%02x",
277                             cipher_chain->key[i]);
278         }
279
280         tc_cipher_chain_free_keys(chain_start);
281
282         return info;
283 }
284
285 int
286 adjust_info(struct tcplay_info *info, struct tcplay_info *hinfo)
287 {
288         if (hinfo->hdr->sz_hidvol == 0)
289                 return 1;
290
291         info->size -= hinfo->hdr->sz_hidvol / hinfo->hdr->sec_sz;
292         return 0;
293 }
294
295 int
296 process_hdr(const char *dev, unsigned char *pass, int passlen,
297     struct tchdr_enc *ehdr, struct tcplay_info **pinfo)
298 {
299         struct tchdr_dec *dhdr;
300         struct tcplay_info *info;
301         unsigned char *key;
302         int i, j, found, error;
303
304         *pinfo = NULL;
305
306         if ((key = alloc_safe_mem(MAX_KEYSZ)) == NULL) {
307                 tc_log(1, "could not allocate safe key memory\n");
308                 return ENOMEM;
309         }
310
311         /* Start search for correct algorithm combination */
312         found = 0;
313         for (i = 0; !found && pbkdf_prf_algos[i].name != NULL; i++) {
314 #ifdef DEBUG
315                 printf("\nTrying PRF algo %s (%d)\n", pbkdf_prf_algos[i].name,
316                     pbkdf_prf_algos[i].iteration_count);
317                 printf("Salt: ");
318                 print_hex(ehdr->salt, 0, sizeof(ehdr->salt));
319 #endif
320                 error = pbkdf2(&pbkdf_prf_algos[i], (char *)pass, passlen,
321                     ehdr->salt, sizeof(ehdr->salt),
322                     MAX_KEYSZ, key);
323
324                 if (error) {
325                         tc_log(1, "pbkdf failed for algorithm %s\n",
326                             pbkdf_prf_algos[i].name);
327                         free_safe_mem(key);
328                         return EINVAL;
329                 }
330
331 #if 0
332                 printf("Derived Key: ");
333                 print_hex(key, 0, MAX_KEYSZ);
334 #endif
335
336                 for (j = 0; !found && tc_cipher_chains[j] != NULL; j++) {
337 #ifdef DEBUG
338                         printf("\nTrying cipher chain %d\n", j);
339 #endif
340
341                         dhdr = decrypt_hdr(ehdr, tc_cipher_chains[j], key);
342                         if (dhdr == NULL) {
343                                 tc_log(1, "hdr decryption failed for cipher "
344                                     "chain %d\n", j);
345                                 free_safe_mem(key);
346                                 return EINVAL;
347                         }
348
349                         if (verify_hdr(dhdr)) {
350 #ifdef DEBUG
351                                 printf("tc_str: %.4s, tc_ver: %d, tc_min_ver: %d, "
352                                     "crc_keys: %d, sz_vol: %"PRIu64", "
353                                     "off_mk_scope: %"PRIu64", sz_mk_scope: %"PRIu64", "
354                                     "flags: %d, sec_sz: %d crc_dhdr: %d\n",
355                                     dhdr->tc_str, dhdr->tc_ver, dhdr->tc_min_ver,
356                                     dhdr->crc_keys, dhdr->sz_vol, dhdr->off_mk_scope,
357                                     dhdr->sz_mk_scope, dhdr->flags, dhdr->sec_sz,
358                                     dhdr->crc_dhdr);
359 #endif
360                                 found = 1;
361                         } else {
362                                 free_safe_mem(dhdr);
363                         }
364                 }
365         }
366
367         free_safe_mem(key);
368
369         if (!found)
370                 return EINVAL;
371
372         if ((info = new_info(dev, tc_cipher_chains[j-1], &pbkdf_prf_algos[i-1],
373             dhdr, 0)) == NULL) {
374                 free_safe_mem(dhdr);
375                 return ENOMEM;
376         }
377
378         *pinfo = info;
379
380         return 0;
381 }
382
383 int
384 create_volume(const char *dev, int hidden, const char *keyfiles[], int nkeyfiles,
385     const char *h_keyfiles[], int n_hkeyfiles, struct pbkdf_prf_algo *prf_algo,
386     struct tc_cipher_chain *cipher_chain, struct pbkdf_prf_algo *h_prf_algo,
387     struct tc_cipher_chain *h_cipher_chain, char *passphrase,
388     char *h_passphrase, size_t size_hidden_bytes_in, int interactive)
389 {
390         char *pass, *pass_again;
391         char *h_pass = NULL;
392         char buf[1024];
393         size_t blocks, blksz, hidden_blocks = 0;
394         struct tchdr_enc *ehdr, *hehdr;
395         struct tchdr_enc *ehdr_backup, *hehdr_backup;
396         uint64_t tmp;
397         int error, r, ret;
398
399         pass = h_pass = pass_again = NULL;
400         ehdr = hehdr = NULL;
401         ehdr_backup = hehdr_backup = NULL;
402         ret = -1; /* Default to returning error */
403
404         if (cipher_chain == NULL)
405                 cipher_chain = tc_cipher_chains[0];
406         if (prf_algo == NULL)
407                 prf_algo = &pbkdf_prf_algos[0];
408         if (h_cipher_chain == NULL)
409                 h_cipher_chain = cipher_chain;
410         if (h_prf_algo == NULL)
411                 h_prf_algo = prf_algo;
412
413         if ((error = get_disk_info(dev, &blocks, &blksz)) != 0) {
414                 tc_log(1, "could not get disk info\n");
415                 return -1;
416         }
417
418         if ((blocks*blksz) <= MIN_VOL_BYTES) {
419                 tc_log(1, "Cannot create volumes on devices with less "
420                     "than %d bytes\n", MIN_VOL_BYTES);
421                 return -1;
422         }
423
424         if (interactive) {
425                 if (((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) ||
426                    ((pass_again = alloc_safe_mem(MAX_PASSSZ)) == NULL)) {
427                         tc_log(1, "could not allocate safe passphrase memory\n");
428                         goto out;
429                 }
430
431                 if ((error = read_passphrase("Passphrase: ", pass, MAX_PASSSZ, 0) ||
432                    (read_passphrase("Repeat passphrase: ", pass_again,
433                    MAX_PASSSZ, 0)))) {
434                         tc_log(1, "could not read passphrase\n");
435                         goto out;
436                 }
437
438                 if (strcmp(pass, pass_again) != 0) {
439                         tc_log(1, "Passphrases don't match\n");
440                         goto out;
441                 }
442
443                 free_safe_mem(pass_again);
444                 pass_again = NULL;
445         } else {
446                 /* In batch mode, use provided passphrase */
447                 if ((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
448                         tc_log(1, "could not allocate safe "
449                             "passphrase memory");
450                         goto out;
451                 }
452
453                 if (passphrase != NULL)
454                         strcpy(pass, passphrase);
455         }
456
457         if (nkeyfiles > 0) {
458                 /* Apply keyfiles to 'pass' */
459                 if ((error = apply_keyfiles((unsigned char *)pass, MAX_PASSSZ,
460                     keyfiles, nkeyfiles))) {
461                         tc_log(1, "could not apply keyfiles\n");
462                         goto out;
463                 }
464         }
465
466         if (hidden) {
467                 if (interactive) {
468                         if (((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) ||
469                            ((pass_again = alloc_safe_mem(MAX_PASSSZ)) == NULL)) {
470                                 tc_log(1, "could not allocate safe "
471                                     "passphrase memory\n");
472                                 goto out;
473                         }
474
475                         if ((error = read_passphrase("Passphrase for hidden volume: ",
476                            h_pass, MAX_PASSSZ, 0) ||
477                            (read_passphrase("Repeat passphrase: ", pass_again,
478                            MAX_PASSSZ, 0)))) {
479                                 tc_log(1, "could not read passphrase\n");
480                                 goto out;
481                         }
482
483                         if (strcmp(h_pass, pass_again) != 0) {
484                                 tc_log(1, "Passphrases for hidden volume don't "
485                                     "match\n");
486                                 goto out;
487                         }
488
489                         free_safe_mem(pass_again);
490                         pass_again = NULL;
491                 } else {
492                         /* In batch mode, use provided passphrase */
493                         if ((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
494                                 tc_log(1, "could not allocate safe "
495                                     "passphrase memory");
496                                 goto out;
497                         }
498
499                         if (h_passphrase != NULL)
500                                 strcpy(h_pass, h_passphrase);
501                 }
502
503                 if (n_hkeyfiles > 0) {
504                         /* Apply keyfiles to 'h_pass' */
505                         if ((error = apply_keyfiles((unsigned char *)h_pass,
506                             MAX_PASSSZ, h_keyfiles, n_hkeyfiles))) {
507                                 tc_log(1, "could not apply keyfiles\n");
508                                 goto out;
509                         }
510                 }
511
512                 if (interactive) {
513                         hidden_blocks = 0;
514                 } else {
515                         hidden_blocks = size_hidden_bytes_in/blksz;
516                         if (hidden_blocks == 0) {
517                                 tc_log(1, "hidden_blocks to create volume "
518                                     "cannot be zero!\n");
519                                 goto out;
520                         }
521
522                         if (size_hidden_bytes_in >=
523                             (blocks*blksz) - MIN_VOL_BYTES) {
524                                 tc_log(1, "Hidden volume needs to be "
525                                     "smaller than the outer volume\n");
526                                 goto out;
527                         }
528                 }
529
530                 /* This only happens in interactive mode */
531                 while (hidden_blocks == 0) {
532                         if ((r = _humanize_number(buf, sizeof(buf),
533                             (uint64_t)(blocks * blksz))) < 0) {
534                                 sprintf(buf, "%zu bytes", (blocks * blksz));
535                         }
536
537                         printf("The total volume size of %s is %s (bytes)\n", dev, buf);
538                         memset(buf, 0, sizeof(buf));
539                         printf("Size of hidden volume (e.g. 127M):  ");
540                         fflush(stdout);
541
542                         if ((fgets(buf, sizeof(buf), stdin)) == NULL) {
543                                 tc_log(1, "Could not read from stdin\n");
544                                 goto out;
545                         }
546
547                         /* get rid of trailing newline */
548                         buf[strlen(buf)-1] = '\0';
549                         if ((error = _dehumanize_number(buf,
550                             &tmp)) != 0) {
551                                 tc_log(1, "Could not interpret input: %s\n", buf);
552                                 continue;
553                         }
554
555                         if (tmp >= (blocks*blksz) - MIN_VOL_BYTES) {
556                                 tc_log(1, "Hidden volume needs to be "
557                                     "smaller than the outer volume\n");
558                                 hidden_blocks = 0;
559                                 continue;
560                         }
561
562                         hidden_blocks = (size_t)tmp;
563                         hidden_blocks /= blksz;
564                 }
565         }
566
567         if (interactive) {
568                 /* Show summary and ask for confirmation */
569                 printf("Summary of actions:\n");
570                 printf(" - Completely erase *EVERYTHING* on %s\n", dev);
571                 printf(" - Create %svolume on %s\n", hidden?("outer "):"", dev);
572                 if (hidden) {
573                         printf(" - Create hidden volume of %zu bytes at end of "
574                             "outer volume\n",
575                             hidden_blocks * blksz);
576                 }
577
578                 printf("\n Are you sure you want to proceed? (y/n) ");
579                 fflush(stdout);
580                 if ((fgets(buf, sizeof(buf), stdin)) == NULL) {
581                         tc_log(1, "Could not read from stdin\n");
582                         goto out;
583                 }
584
585                 if ((buf[0] != 'y') && (buf[0] != 'Y')) {
586                         tc_log(1, "User cancelled action(s)\n");
587                         goto out;
588                 }
589         }
590
591         tc_log(0, "Securely erasing the volume...\nThis process may take "
592             "some time depending on the size of the volume\n");
593
594         /* erase volume */
595         if ((error = secure_erase(dev, blocks * blksz, blksz)) != 0) {
596                 tc_log(1, "could not securely erase device %s\n", dev);
597                 goto out;
598         }
599
600         tc_log(0, "Creating volume headers...\nDepending on your system, this "
601             "process may take a few minutes as it uses true random data which "
602             "might take a while to refill\n");
603
604         /* create encrypted headers */
605         ehdr = create_hdr((unsigned char *)pass,
606             (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass),
607             prf_algo, cipher_chain, blksz, blocks, VOL_RSVD_BYTES_START/blksz,
608             blocks - (MIN_VOL_BYTES/blksz), 0, &ehdr_backup);
609         if (ehdr == NULL) {
610                 tc_log(1, "Could not create header\n");
611                 goto out;
612         }
613
614         if (hidden) {
615                 hehdr = create_hdr((unsigned char *)h_pass,
616                     (n_hkeyfiles > 0)?MAX_PASSSZ:strlen(h_pass), h_prf_algo,
617                     h_cipher_chain,
618                     blksz, blocks,
619                     blocks - (VOL_RSVD_BYTES_END/blksz) - hidden_blocks,
620                     hidden_blocks, 1, &hehdr_backup);
621                 if (hehdr == NULL) {
622                         tc_log(1, "Could not create hidden volume header\n");
623                         goto out;
624                 }
625         }
626
627         tc_log(0, "Writing volume headers to disk...\n");
628
629         if ((error = write_to_disk(dev, 0, blksz, ehdr, sizeof(*ehdr))) != 0) {
630                 tc_log(1, "Could not write volume header to device\n");
631                 goto out;
632         }
633
634         /* Write backup header; it's offset is relative to the end */
635         if ((error = write_to_disk(dev, (blocks*blksz - BACKUP_HDR_OFFSET_END),
636             blksz, ehdr_backup, sizeof(*ehdr_backup))) != 0) {
637                 tc_log(1, "Could not write backup volume header to device\n");
638                 goto out;
639         }
640
641         if (hidden) {
642                 if ((error = write_to_disk(dev, HDR_OFFSET_HIDDEN, blksz, hehdr,
643                     sizeof(*hehdr))) != 0) {
644                         tc_log(1, "Could not write hidden volume header to "
645                             "device\n");
646                         goto out;
647                 }
648
649                 /* Write backup hidden header; offset is relative to end */
650                 if ((error = write_to_disk(dev,
651                     (blocks*blksz - BACKUP_HDR_HIDDEN_OFFSET_END), blksz,
652                     hehdr_backup, sizeof(*hehdr_backup))) != 0) {
653                         tc_log(1, "Could not write backup hidden volume "
654                             "header to device\n");
655                         goto out;
656                 }
657         }
658
659         /* Everything went ok */
660         tc_log(0, "All done!\n");
661
662         ret = 0;
663
664 out:
665         if (pass)
666                 free_safe_mem(pass);
667         if (h_pass)
668                 free_safe_mem(h_pass);
669         if (pass_again)
670                 free_safe_mem(pass_again);
671         if (ehdr)
672                 free_safe_mem(ehdr);
673         if (hehdr)
674                 free_safe_mem(hehdr);
675         if (ehdr_backup)
676                 free_safe_mem(ehdr_backup);
677         if (hehdr_backup)
678                 free_safe_mem(hehdr_backup);
679
680         return ret;
681 }
682
683 static
684 struct tcplay_info *
685 info_map_common(const char *dev, int sflag, const char *sys_dev,
686     int protect_hidden, const char *keyfiles[], int nkeyfiles,
687     const char *h_keyfiles[], int n_hkeyfiles, char *passphrase,
688     char *passphrase_hidden, int interactive, int retries, time_t timeout)
689 {
690         struct tchdr_enc *ehdr, *hehdr = NULL;
691         struct tcplay_info *info, *hinfo = NULL;
692         char *pass;
693         char *h_pass;
694         int error, error2 = 0;
695         size_t sz;
696         size_t blocks, blksz;
697
698         if ((error = get_disk_info(dev, &blocks, &blksz)) != 0) {
699                 tc_log(1, "could not get disk information\n");
700                 return NULL;
701         }
702
703         if (retries < 1)
704                 retries = 1;
705
706         info = NULL;
707
708         ehdr = NULL;
709         pass = h_pass = NULL;
710
711         while ((info == NULL) && retries-- > 0)
712         {
713                 pass = h_pass = NULL;
714                 ehdr = hehdr = NULL;
715                 info = hinfo = NULL;
716
717                 if ((pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
718                         tc_log(1, "could not allocate safe passphrase memory\n");
719                         goto out;
720                 }
721
722                 if (interactive) {
723                         if ((error = read_passphrase("Passphrase: ", pass,
724                             MAX_PASSSZ, timeout))) {
725                                 tc_log(1, "could not read passphrase\n");
726                                 /* XXX: handle timeout differently? */
727                                 goto out;
728                         }
729                 } else {
730                         /* In batch mode, use provided passphrase */
731                         if (passphrase != NULL)
732                                 strcpy(pass, passphrase);
733                 }
734
735                 if (nkeyfiles > 0) {
736                         /* Apply keyfiles to 'pass' */
737                         if ((error = apply_keyfiles((unsigned char *)pass, MAX_PASSSZ,
738                             keyfiles, nkeyfiles))) {
739                                 tc_log(1, "could not apply keyfiles");
740                                 goto out;
741                         }
742                 }
743
744                 if (protect_hidden) {
745                         if ((h_pass = alloc_safe_mem(MAX_PASSSZ)) == NULL) {
746                                 tc_log(1, "could not allocate safe passphrase memory\n");
747                                 goto out;
748                         }
749
750                         if (interactive) {
751                                 if ((error = read_passphrase(
752                                     "Passphrase for hidden volume: ", h_pass,
753                                     MAX_PASSSZ, timeout))) {
754                                         tc_log(1, "could not read passphrase\n");
755                                         goto out;
756                                 }
757                         } else {
758                                 /* In batch mode, use provided passphrase */
759                                 if (passphrase_hidden != NULL)
760                                         strcpy(h_pass, passphrase_hidden);
761                         }
762
763                         if (n_hkeyfiles > 0) {
764                                 /* Apply keyfiles to 'pass' */
765                                 if ((error = apply_keyfiles((unsigned char *)h_pass, MAX_PASSSZ,
766                                     h_keyfiles, n_hkeyfiles))) {
767                                         tc_log(1, "could not apply keyfiles");
768                                         goto out;
769                                 }
770                         }
771                 }
772
773                 /* Always read blksz-sized chunks */
774                 sz = blksz;
775
776                 ehdr = (struct tchdr_enc *)read_to_safe_mem((sflag) ? sys_dev : dev,
777                     (sflag) ? HDR_OFFSET_SYS : 0, &sz);
778                 if (ehdr == NULL) {
779                         tc_log(1, "error read hdr_enc: %s", dev);
780                         goto out;
781                 }
782
783                 if (!sflag) {
784                         /* Always read blksz-sized chunks */
785                         sz = blksz;
786
787                         hehdr = (struct tchdr_enc *)read_to_safe_mem(dev,
788                             HDR_OFFSET_HIDDEN, &sz);
789                         if (hehdr == NULL) {
790                                 tc_log(1, "error read hdr_enc: %s", dev);
791                                 goto out;
792                         }
793                 } else {
794                         hehdr = NULL;
795                 }
796
797                 error = process_hdr(dev, (unsigned char *)pass,
798                     (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass),
799                     ehdr, &info);
800
801                 /*
802                  * Try to process hidden header if we have to protect the hidden
803                  * volume, or the decryption/verification of the main header
804                  * failed.
805                  */
806                 if (hehdr && (error || protect_hidden)) {
807                         if (error) {
808                                 error2 = process_hdr(dev, (unsigned char *)pass,
809                                     (nkeyfiles > 0)?MAX_PASSSZ:strlen(pass), hehdr,
810                                     &info);
811                         } else if (protect_hidden) {
812                                 error2 = process_hdr(dev, (unsigned char *)h_pass,
813                                     (n_hkeyfiles > 0)?MAX_PASSSZ:strlen(h_pass), hehdr,
814                                     &hinfo);
815                         }
816                 }
817
818                 /* We need both to protect a hidden volume */
819                 if ((protect_hidden && (error || error2)) ||
820                     (error && error2)) {
821                         tc_log(1, "Incorrect password or not a TrueCrypt volume\n");
822
823                         if (info) {
824                                 if (info->hdr)
825                                         free_safe_mem(info->hdr);
826                                 free_safe_mem(info);
827                                 info = NULL;
828                         }
829                         if (hinfo) {
830                                 if (hinfo->hdr)
831                                         free_safe_mem(hinfo->hdr);
832                                 free_safe_mem(hinfo);
833                                 hinfo = NULL;
834                         }
835
836                         /* Try again (or finish) */
837                         free_safe_mem(pass);
838                         pass = NULL;
839
840                         if (h_pass) {
841                                 free_safe_mem(h_pass);
842                                 h_pass = NULL;
843                         }
844                         if (ehdr) {
845                                 free_safe_mem(ehdr);
846                                 ehdr = NULL;
847                         }
848                         if (hehdr) {
849                                 free_safe_mem(hehdr);
850                                 hehdr = NULL;
851                         }
852                         continue;
853                 }
854
855                 if (protect_hidden) {
856                         if (adjust_info(info, hinfo) != 0) {
857                                 tc_log(1, "Could not protect hidden volume\n");
858                                 if (info) {
859                                         if (info->hdr)
860                                                 free_safe_mem(info->hdr);
861                                         free_safe_mem(info);
862                                 }
863                                 info = NULL;
864
865                                 if (hinfo->hdr)
866                                         free_safe_mem(hinfo->hdr);
867                                 free_safe_mem(hinfo);
868                                 hinfo = NULL;
869                                 goto out;
870                         }
871
872                         if (hinfo->hdr)
873                                 free_safe_mem(hinfo->hdr);
874                         free_safe_mem(hinfo);
875                         hinfo = NULL;
876                 }
877         }
878
879 out:
880         if (hinfo)
881                 free_safe_mem(hinfo);
882         if (pass)
883                 free_safe_mem(pass);
884         if (h_pass)
885                 free_safe_mem(h_pass);
886         if (ehdr)
887                 free_safe_mem(ehdr);
888         if (hehdr)
889                 free_safe_mem(hehdr);
890
891         return info;
892 }
893
894 int
895 info_volume(const char *device, int sflag, const char *sys_dev,
896     int protect_hidden, const char *keyfiles[], int nkeyfiles,
897     const char *h_keyfiles[], int n_hkeyfiles,
898     char *passphrase, char *passphrase_hidden, int interactive, int retries,
899     time_t timeout)
900 {
901         struct tcplay_info *info;
902
903         info = info_map_common(device, sflag, sys_dev, protect_hidden,
904             keyfiles, nkeyfiles, h_keyfiles, n_hkeyfiles,
905             passphrase, passphrase_hidden, interactive, retries, timeout);
906
907         if (info != NULL) {
908                 if (interactive)
909                         print_info(info);
910                 if (info->hdr)
911                         free_safe_mem(info->hdr);
912                 free_safe_mem(info);
913
914                 return 0;
915                 /* NOT REACHED */
916         }
917
918         return -1;
919 }
920
921 int
922 map_volume(const char *map_name, const char *device, int sflag,
923     const char *sys_dev, int protect_hidden, const char *keyfiles[],
924     int nkeyfiles, const char *h_keyfiles[], int n_hkeyfiles,
925     char *passphrase, char *passphrase_hidden, int interactive, int retries,
926     time_t timeout)
927
928 {
929         struct tcplay_info *info;
930         int error;
931
932         info = info_map_common(device, sflag, sys_dev, protect_hidden,
933             keyfiles, nkeyfiles, h_keyfiles, n_hkeyfiles,
934             passphrase, passphrase_hidden, interactive, retries, timeout);
935
936         if (info == NULL)
937                 return -1;
938
939         if ((error = dm_setup(map_name, info)) != 0) {
940                 tc_log(1, "Could not set up mapping %s\n", map_name);
941                 if (info->hdr)
942                         free_safe_mem(info->hdr);
943                 free_safe_mem(info);
944                 return -1;
945         }
946
947         if (interactive)
948                 printf("All ok!\n");
949
950         free_safe_mem(info);
951
952         return 0;
953 }
954
955 static
956 int
957 dm_remove_device(const char *name)
958 {
959         struct dm_task *dmt = NULL;
960         int ret = EINVAL;
961
962         if ((dmt = dm_task_create(DM_DEVICE_REMOVE)) == NULL)
963                 goto out;
964
965         if ((dm_task_set_name(dmt, name)) == 0)
966                 goto out;
967
968         if ((dm_task_run(dmt)) == 0)
969                 goto out;
970
971         ret = 0;
972 out:
973         if (dmt)
974                 dm_task_destroy(dmt);
975
976         return ret;
977 }
978
979 int
980 dm_setup(const char *mapname, struct tcplay_info *info)
981 {
982         struct tc_cipher_chain *cipher_chain;
983         struct dm_task *dmt = NULL;
984         struct dm_info dmi;
985         char *params = NULL;
986         char *uu;
987         char *uu_stack[64];
988         int uu_stack_idx;
989 #if defined(__DragonFly__)
990         uint32_t status;
991 #endif
992         int r, ret = 0;
993         int j;
994         off_t start, offset;
995         char dev[PATH_MAX];
996         char map[PATH_MAX];
997         uint32_t cookie;
998
999         dm_udev_set_sync_support(1);
1000
1001         if ((params = alloc_safe_mem(512)) == NULL) {
1002                 tc_log(1, "could not allocate safe parameters memory");
1003                 return ENOMEM;
1004         }
1005
1006         strcpy(dev, info->dev);
1007         start = info->start;
1008         offset = info->offset;
1009         uu_stack_idx = 0;
1010
1011         /* Get to the end of the chain */
1012         for (cipher_chain = info->cipher_chain; cipher_chain->next != NULL;
1013             cipher_chain = cipher_chain->next)
1014                 ;
1015
1016         for (j= 0; cipher_chain != NULL;
1017             cipher_chain = cipher_chain->prev, j++) {
1018
1019                 cookie = 0;
1020
1021                 /* aes-cbc-essiv:sha256 7997f8af... 0 /dev/ad0s0a 8 */
1022                 /*                         iv off---^  block off--^ */
1023                 snprintf(params, 512, "%s %s %"PRIu64 " %s %"PRIu64,
1024                     cipher_chain->cipher->dm_crypt_str, cipher_chain->dm_key,
1025                     (uint64_t)info->skip, dev, (uint64_t)offset);
1026 #ifdef DEBUG
1027                 printf("Params: %s\n", params);
1028 #endif
1029
1030                 if ((dmt = dm_task_create(DM_DEVICE_CREATE)) == NULL) {
1031                         tc_log(1, "dm_task_create failed\n");
1032                         ret = -1;
1033                         goto out;
1034                 }
1035
1036                 /*
1037                  * If this is the last element in the cipher chain, use the
1038                  * final map name. Otherwise pick a secondary name...
1039                  */
1040                 if (cipher_chain->prev == NULL)
1041                         strcpy(map, mapname);
1042                 else
1043                         sprintf(map, "%s.%d", mapname, j);
1044
1045                 if ((dm_task_set_name(dmt, map)) == 0) {
1046                         tc_log(1, "dm_task_set_name failed\n");
1047                         ret = -1;
1048                         goto out;
1049                 }
1050
1051 #if defined(__linux__)
1052                 uuid_generate(info->uuid);
1053                 if ((uu = malloc(1024)) == NULL) {
1054                         tc_log(1, "uuid_unparse memory failed\n");
1055                         ret = -1;
1056                         goto out;
1057                 }
1058                 uuid_unparse(info->uuid, uu);
1059 #elif defined(__DragonFly__)
1060                 uuid_create(&info->uuid, &status);
1061                 if (status != uuid_s_ok) {
1062                         tc_log(1, "uuid_create failed\n");
1063                         ret = -1;
1064                         goto out;
1065                 }
1066
1067                 uuid_to_string(&info->uuid, &uu, &status);
1068                 if (uu == NULL) {
1069                         tc_log(1, "uuid_to_string failed\n");
1070                         ret = -1;
1071                         goto out;
1072                 }
1073 #endif
1074
1075                 if ((dm_task_set_uuid(dmt, uu)) == 0) {
1076                         free(uu);
1077                         tc_log(1, "dm_task_set_uuid failed\n");
1078                         ret = -1;
1079                         goto out;
1080                 }
1081
1082                 free(uu);
1083
1084                 if ((dm_task_add_target(dmt, start, info->size, "crypt", params)) == 0) {
1085                         tc_log(1, "dm_task_add_target failed\n");
1086                         ret = -1;
1087                         goto out;
1088                 }
1089
1090                 if ((dm_task_set_cookie(dmt, &cookie, 0)) == 0) {
1091                         tc_log(1, "dm_task_set_cookie failed\n");
1092                         ret = -1;
1093                         goto out;
1094                 }
1095
1096                 if ((dm_task_run(dmt)) == 0) {
1097                         dm_udev_wait(cookie);
1098                         tc_log(1, "dm_task_task_run failed\n");
1099                         ret = -1;
1100                         goto out;
1101                 }
1102
1103                 if ((dm_task_get_info(dmt, &dmi)) == 0) {
1104                         dm_udev_wait(cookie);
1105                         tc_log(1, "dm_task_get info failed\n");
1106                         ret = -1;
1107                         goto out;
1108                 }
1109
1110                 dm_udev_wait(cookie);
1111
1112                 asprintf(&uu_stack[uu_stack_idx++], "%s", map);
1113
1114                 offset = 0;
1115                 start = 0;
1116                 sprintf(dev, "/dev/mapper/%s.%d", mapname, j);
1117
1118                 dm_task_destroy(dmt);
1119                 dm_task_update_nodes();
1120         }
1121
1122 out:
1123         /*
1124          * If an error occured, try to unroll changes made before it
1125          * happened.
1126          */
1127         if (ret) {
1128                 j = uu_stack_idx;
1129                 while (j > 0) {
1130 #ifdef DEBUG
1131                         printf("Unrolling dm changes! j = %d (%s)\n", j-1,
1132                             uu_stack[j-1]);
1133 #endif
1134                         if ((r = dm_remove_device(uu_stack[--j])) != 0) {
1135                                 tc_log(1, "Tried to unroll dm changes, "
1136                                     "giving up.\n");
1137                                 break;
1138                         }
1139                 }
1140         }
1141
1142         while (uu_stack_idx > 0)
1143                 free(uu_stack[--uu_stack_idx]);
1144
1145         free_safe_mem(params);
1146
1147         return ret;
1148 }
1149
1150 int
1151 dm_teardown(const char *mapname, const char *device __unused)
1152 {
1153 #if 0
1154         struct dm_task *dmt = NULL;
1155         struct dm_info dmi;
1156 #endif
1157         char map[PATH_MAX];
1158         int i, error;
1159
1160         if ((error = dm_remove_device(mapname)) != 0) {
1161                 tc_log(1, "Could not remove mapping %s\n", mapname);
1162                 return error;
1163         }
1164
1165         /* Try to remove other cascade devices */
1166         for (i = 2; i >= 0; i--) {
1167                 sprintf(map, "%s.%d", mapname, i);
1168                 dm_remove_device(map);
1169         }
1170
1171         return 0;
1172 }
1173
1174 struct tc_crypto_algo *
1175 check_cipher(const char *cipher, int quiet)
1176 {
1177         int i, found = 0;
1178
1179         for (i = 0; tc_crypto_algos[i].name != NULL; i++) {
1180                 if (strcmp(cipher, tc_crypto_algos[i].name) == 0) {
1181                         found = 1;
1182                         break;
1183                 }
1184         }
1185
1186         if (!found && !quiet) {
1187                 fprintf(stderr, "Valid ciphers are: ");
1188                 for (i = 0; tc_crypto_algos[i].name != NULL; i++)
1189                         fprintf(stderr, "%s ", tc_crypto_algos[i].name);
1190                 fprintf(stderr, "\n");
1191                 return NULL;
1192         }
1193
1194         return &tc_crypto_algos[i];
1195 }
1196
1197 struct tc_cipher_chain *
1198 check_cipher_chain(char *cipher_chain, int quiet)
1199 {
1200         struct tc_cipher_chain *cipher = NULL;
1201         int i,k, nciphers = 0, mismatch = 0;
1202         char *ciphers[8];
1203         char *tmp_chain, *tmp_chain_free;
1204         char *token;
1205
1206         if ((tmp_chain = strdup(cipher_chain)) == NULL) {
1207                 tc_log(1, "Could not allocate strdup memory\n");
1208                 return NULL;
1209         }
1210
1211         tmp_chain_free = tmp_chain;
1212
1213         while ((token = strsep(&tmp_chain, ",")) != NULL)
1214                 ciphers[nciphers++] = token;
1215
1216         cipher = NULL;
1217
1218         for (i = 0; valid_cipher_chains[i][0] != NULL; i++) {
1219                 mismatch = 0;
1220
1221                 for (k = 0; (valid_cipher_chains[i][k] != NULL); k++) {
1222                         /*
1223                          * If there are more ciphers in the chain than in the
1224                          * ciphers[] variable this is not the right chain.
1225                          */
1226                         if (k == nciphers) {
1227                                 mismatch = 1;
1228                                 break;
1229                         }
1230
1231                         if (strcmp(ciphers[k], valid_cipher_chains[i][k]) != 0)
1232                                 mismatch = 1;
1233                 }
1234
1235                 /*
1236                  * If all ciphers matched and there are exactly nciphers,
1237                  * then we found the right cipher chain.
1238                  */
1239                 if ((k == nciphers) && !mismatch) {
1240                         cipher = tc_cipher_chains[i];
1241                         break;
1242                 }
1243         }
1244
1245         if (cipher == NULL) {
1246                 tc_log(1, "Invalid cipher: %s\n", cipher_chain);
1247                 if (!quiet) {
1248                         fprintf(stderr, "Valid cipher chains are:\n");
1249                         for (i = 0; valid_cipher_chains[i][0] != NULL; i++) {
1250                                 for (k = 0; valid_cipher_chains[i][k] != NULL;
1251                                     k++) {
1252                                         fprintf(stderr, "%s%c",
1253                                             valid_cipher_chains[i][k],
1254                                             (valid_cipher_chains[i][k+1] != NULL) ?
1255                                             ',' : '\0');
1256                                 }
1257                                 fprintf(stderr, "\n");
1258                         }
1259                 }
1260         }
1261
1262         free(tmp_chain_free);
1263         return cipher;
1264 }
1265
1266 struct pbkdf_prf_algo *
1267 check_prf_algo(char *algo, int quiet)
1268 {
1269         int i, found = 0;
1270
1271         for (i = 0; pbkdf_prf_algos[i].name != NULL; i++) {
1272                 if (strcmp(algo, pbkdf_prf_algos[i].name) == 0) {
1273                         found = 1;
1274                         break;
1275                 }
1276         }
1277
1278         if (!found && !quiet) {
1279                 fprintf(stderr, "Valid PBKDF PRF algorithms are: ");
1280                 for (i = 0; pbkdf_prf_algos[i].name != NULL; i++)
1281                         fprintf(stderr, "%s ", pbkdf_prf_algos[i].name);
1282                 fprintf(stderr, "\n");
1283                 return NULL;
1284         }
1285
1286         return &pbkdf_prf_algos[i];
1287 }
1288
1289 int
1290 tc_play_init(void)
1291 {
1292         int error;
1293
1294         if ((error = tc_build_cipher_chains()) != 0)
1295                 return error;
1296
1297         if ((error = tc_crypto_init()) != 0)
1298                 return error;
1299
1300         return 0;
1301 }