e8514391b8036b8168c5f85d7ef32e8383c59542
[tfcrypt.git] / tfcrypt.c
1 /*
2  * tfcrypt -- high security Threefish encryption tool.
3  *
4  * tfcrypt is copyrighted:
5  * Copyright (C) 2012-2019 Andrey Rys. All rights reserved.
6  *
7  * tfcrypt is licensed to you under the terms of std. MIT/X11 license:
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining
10  * a copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 #include "tfcrypt.h"
30
31 static tfc_byte svctr[TF_BLOCK_SIZE];
32 static tfc_fsize rwd, do_read_loops, loopcnt;
33
34 static void open_log(const char *logfile)
35 {
36         int fd;
37
38         if (!strcmp(logfile, "-")) return;
39
40         fd = open(logfile, O_WRONLY | O_CREAT | O_LARGEFILE | O_TRUNC, 0666);
41         if (fd == -1) xerror(NO, NO, YES, "%s", logfile);
42         xclose(2);
43         if (dup2(fd, 2) == -1) xexit(2);
44         xclose(fd);
45         do_statline_dynamic = NO;
46 }
47
48 static int getps_filter(struct getpasswd_state *getps, char chr, size_t pos)
49 {
50         if (chr == '\x03') {
51                 getps->retn = ((size_t)-2);
52                 return 6;
53         }
54         return 1;
55 }
56
57 static int getps_hex_filter(struct getpasswd_state *getps, char chr, size_t pos)
58 {
59         if (chr == '\x03') {
60                 getps->retn = ((size_t)-2);
61                 return 6;
62         }
63         if (chr >= '0' && chr <= '9') return 1;
64         if (chr >= 'a' && chr <= 'f') return 1;
65         if (chr >= 'A' && chr <= 'F') return 1;
66         if (chr == '\x7f' || chr == '\x08'
67         || chr == '\x15' || chr == '\x17') return 1;
68         return 0;
69 }
70
71 static inline int isctrlchr(int c)
72 {
73         if (c == 9) return 0;
74         if (c >= 0 && c <= 31) return 1;
75         if (c == 127) return 1;
76         return 0;
77 }
78
79 static int getps_plain_filter(struct getpasswd_state *getps, char chr, size_t pos)
80 {
81         int x;
82
83         x = getps_filter(getps, chr, pos);
84         if (x != 1) return x;
85
86         if (pos < getps->pwlen && !isctrlchr(chr))
87                 write(getps->efd, &chr, sizeof(char));
88         return 1;
89 }
90
91 static int getps_plain_hex_filter(struct getpasswd_state *getps, char chr, size_t pos)
92 {
93         int x;
94
95         x = getps_hex_filter(getps, chr, pos);
96         if (x != 1) return x;
97
98         if (pos < getps->pwlen && !isctrlchr(chr))
99                 write(getps->efd, &chr, sizeof(char));
100         return 1;
101 }
102
103 static void make_hint(void *hint, size_t szhint, const void *data, size_t szdata)
104 {
105         char t[TF_FROM_BITS(TF_MAX_BITS)];
106
107         skein(t, TF_MAX_BITS, NULL, data, szdata);
108         xor_shrink(hint, szhint, t, sizeof(t));
109         memset(t, 0, sizeof(t));
110 }
111
112 static void raw_say_hint(void *hint, size_t szhint, const void *data, size_t szdata, const char *prompt)
113 {
114         make_hint(hint, szhint, data, szdata);
115         if (prompt) tfc_nfsay(stderr, "%s: ", prompt);
116         mehexdump(hint, szhint, szhint, 1);
117         memset(hint, 0, szhint);
118 }
119
120 static void say_hint(const void *data, size_t szdata, const char *prompt)
121 {
122         char t[TF_SIZE_UNIT];
123         raw_say_hint(t, TF_SIZE_UNIT, data, szdata, prompt);
124         /* t[] is erased (automatically) */
125 }
126
127 int main(int argc, char **argv)
128 {
129         int c;
130         double td;
131         char *s, *d, *t, *stoi;
132         size_t x, n;
133
134         progpid = getpid();
135         progname = basename(argv[0]);
136
137         if (!isatty(2)) do_statline_dynamic = NO;
138
139         s = (char *)srcblk;
140         d = getenv("HOME");
141         if (!d) d = "";
142         n = PATH_MAX > sizeof(srcblk) ? sizeof(srcblk) : PATH_MAX;
143         if (xstrlcpy(s, d, n) >= n) goto _baddfname;
144         if (xstrlcat(s, "/.tfcrypt.defs", n) >= n) goto _baddfname;
145         read_defaults(s, YES);
146 _baddfname:
147         memset(s, 0, n);
148
149         if (!strcmp(progname, "iotool")) {
150                 do_edcrypt = TFC_DO_PLAIN;
151                 password = YES;
152                 ctr_mode = TFC_MODE_PLAIN;
153         }
154
155         opterr = 0;
156         while ((c = getopt(argc, argv, "L:s:aU:C:r:K:t:Pkzxc:l:qedn:vV:pwE:o:O:S:AmuM:R:Z:WHD:")) != -1) {
157                 switch (c) {
158                         case 'L':
159                                 read_defaults(optarg, NO);
160                                 break;
161                         case 's':
162                                 saltf = optarg;
163                                 break;
164                         case 'r':
165                                 randsource = optarg;
166                                 break;
167                         case 'c':
168                                 if (!strcasecmp(optarg, "show"))
169                                         counter_opt = TFC_CTR_SHOW;
170                                 else if (!strcasecmp(optarg, "head"))
171                                         counter_opt = TFC_CTR_HEAD;
172                                 else if (!strcasecmp(optarg, "rand"))
173                                         counter_opt = TFC_CTR_RAND;
174                                 else if (!strcasecmp(optarg, "zero"))
175                                         counter_opt = TFC_CTR_ZERO;
176                                 else if (strchr(optarg, ':')) {
177                                         char *ss, chr;
178
179                                         counter_opt = TFC_CTR_SSET;
180                                         n = sizeof(ctr);
181
182                                         s = d = optarg; t = NULL;
183                                         while ((s = strtok_r(d, ",", &t))) {
184                                                 if (d) d = NULL;
185
186                                                 if (n == 0) break;
187                                                 ss = strchr(s, ':');
188                                                 if (!ss) continue;
189                                                 *ss = 0; ss++;
190                                                 chr = (char)strtoul(s, &stoi, 16);
191                                                 if (!str_empty(stoi)) continue;
192                                                 x = (size_t)strtoul(ss, &stoi, 10);
193                                                 if (!str_empty(stoi)) continue;
194                                                 if (x > n) x = n;
195                                                 memset(ctr+(sizeof(ctr)-n), (int)chr, x);
196                                                 n -= x;
197                                         }
198                                 }
199                                 else counter_file = sksum_hashlist_file = optarg;
200                                 break;
201                         case 'C':
202                                 if (!strcasecmp(optarg, "ctr"))
203                                         ctr_mode = TFC_MODE_CTR;
204                                 else if (!strcasecmp(optarg, "stream"))
205                                         ctr_mode = TFC_MODE_STREAM;
206                                 else if (!strcasecmp(optarg, "cbc"))
207                                         ctr_mode = TFC_MODE_CBC;
208                                 else if (!strcasecmp(optarg, "ecb"))
209                                         ctr_mode = TFC_MODE_ECB;
210                                 else if (!strcasecmp(optarg, "xts"))
211                                         ctr_mode = TFC_MODE_XTS;
212                                 else if (!strcasecmp(optarg, "ocb"))
213                                         ctr_mode = TFC_MODE_OCB;
214                                 else xerror(NO, YES, YES, "%s: invalid mode of operation", optarg);
215                                 break;
216                         case 'P':
217                                 do_edcrypt = TFC_DO_PLAIN;
218                                 password = YES;
219                                 ctr_mode = TFC_MODE_PLAIN;
220                                 break;
221                         case 'e':
222                                 if (do_edcrypt != TFC_DO_PLAIN) do_edcrypt = TFC_DO_ENCRYPT;
223                                 break;
224                         case 'd':
225                                 if (do_edcrypt != TFC_DO_PLAIN) do_edcrypt = TFC_DO_DECRYPT;
226                                 break;
227                         case 'D':
228                                 macbits = strtoul(optarg, &stoi, 10);
229                                 if (macbits == 0 || !str_empty(stoi) || macbits < 8
230                                 || macbits > TF_MAX_BITS || macbits % 8)
231                                         xerror(NO, YES, YES, "%s: invalid MAC bits setting", optarg);
232                                 break;
233                         case 'n':
234                                 nr_turns = sksum_turns = strtoul(optarg, &stoi, 10);
235                                 if (!str_empty(stoi)) xerror(NO, YES, YES, "%s: invalid number of turns", optarg);
236                                 break;
237                         case 'U':
238                                 if (!strcasecmp(optarg, "key"))
239                                         mackey_opt = TFC_MACKEY_RAWKEY;
240                                 else if (!strcasecmp(optarg, "pwd"))
241                                         mackey_opt = TFC_MACKEY_PASSWORD;
242                                 else {
243                                         mackey_opt = TFC_MACKEY_FILE;
244                                         mackeyf = optarg;
245                                 }
246                                 break;
247                         case 'p':
248                                 password = YES;
249                                 break;
250                         case 'k':
251                                 rawkey = TFC_RAWKEY_KEYFILE;
252                                 break;
253                         case 'z':
254                                 rawkey = TFC_RAWKEY_ASKSTR;
255                                 break;
256                         case 'x':
257                                 rawkey = TFC_RAWKEY_ASKHEX;
258                                 break;
259                         case 'K':
260                                 verbose = YES;
261                                 genkeyf = optarg;
262                                 break;
263                         case 't':
264                                 tweakf = optarg;
265                                 do_full_key = NO;
266                                 break;
267                         case 'l':
268                                 if (maxlen != NOFSIZE) break;
269
270                                 maxlen = tfc_humanfsize(optarg, &stoi);
271                                 if (!str_empty(stoi)) {
272                                         maxlen = tfc_fnamesize(optarg, YES);
273                                         maxlen = tfc_modifysize(maxlen, strchr(optarg, ':'));
274                                         if (maxlen == NOFSIZE) xerror(NO, YES, YES,
275                                         "%s: invalid count value", optarg);
276                                 }
277                                 else maxlen = tfc_modifysize(maxlen, strchr(optarg, ':'));
278                                 if (counter_opt == TFC_CTR_HEAD)
279                                         maxlen += TF_BLOCK_SIZE;
280                                 break;
281                         case 'w':
282                                 overwrite_source = YES;
283                                 break;
284                         case 'E':
285                                 if (!strcmp(optarg, "xall")) {
286                                         catch_all_errors = YES;
287                                         break;
288                                 }
289                                 if (!strcmp(optarg, "xseek")) {
290                                         ignore_seek_errors = YES;
291                                         break;
292                                 }
293                                 if (!strcmp(optarg, "exit"))
294                                         error_action = TFC_ERRACT_EXIT;
295                                 else if (!strncmp(optarg, "cont", 4))
296                                         error_action = TFC_ERRACT_CONT;
297                                 else if (!strcmp(optarg, "sync"))
298                                         error_action = TFC_ERRACT_SYNC;
299                                 else if (!strcmp(optarg, "lsync"))
300                                         error_action = TFC_ERRACT_LSYNC;
301                                 else xerror(NO, YES, YES, "invalid error action %s specified", optarg);
302                                 break;
303                         case 'o':
304                                 open_log(optarg);
305                                 break;
306                         case 'O':
307                                 s = d = optarg; t = NULL;
308                                 while ((s = strtok_r(d, ",", &t))) {
309                                         if (d) d = NULL;
310                                         if (!strcmp(s, "sync"))
311                                                 write_flags |= O_SYNC;
312                                         else if (!strcmp(s, "trunc"))
313                                                 write_flags |= O_TRUNC;
314                                         else if (!strcmp(s, "append"))
315                                                 write_flags |= O_APPEND;
316                                         else if (!strcmp(s, "fsync"))
317                                                 do_fsync = YES;
318                                         else if (!strcmp(s, "pad"))
319                                                 do_pad = YES;
320                                         else if (!strcmp(s, "xtime"))
321                                                 do_preserve_time = YES;
322                                         else if (!strcmp(s, "gibsize"))
323                                                 do_stats_in_gibs = YES;
324                                         else if (!strcmp(s, "plainstats"))
325                                                 do_statline_dynamic = NO;
326                                         else if (!strcmp(s, "statless"))
327                                                 do_less_stats = YES;
328                                         else if (!strcmp(s, "norepeat"))
329                                                 no_repeat = YES;
330                                         else if (!strncmp(s, "prompt", 6) && *(s+6) == '=')
331                                                 pw_prompt = s+7;
332                                         else if (!strncmp(s, "macprompt", 9) && *(s+9) == '=')
333                                                 mac_pw_prompt = s+10;
334                                         else if (!strcmp(s, "shorthex"))
335                                                 do_full_hexdump = NO;
336                                         else if (!strcmp(s, "fullkey"))
337                                                 do_full_key = YES;
338                                         else if (!strcmp(s, "showsecrets"))
339                                                 show_secrets = YES;
340                                         else if (!strcmp(s, "finished"))
341                                                 show_when_done = YES;
342                                         else if (!strcmp(s, "pid"))
343                                                 show_pid = YES;
344                                         else if (!strncmp(s, "readloops", 9) && *(s+9) == '=') {
345                                                 do_read_loops = tfc_humanfsize(s+10, &stoi);
346                                                 if (!str_empty(stoi)) do_read_loops = NOSIZE;
347                                         }
348                                         else if (!strncmp(s, "logfile", 7) && *(s+7) == '=')
349                                                 open_log(s+8);
350                                         else if (!strncmp(s, "iobs", 4) && *(s+4) == '=') {
351                                                 s += 5;
352                                                 blksize = (size_t)tfc_humanfsize(s, &stoi);
353                                                 if (!str_empty(stoi)) {
354                                                         blksize = (size_t)tfc_fnamesize(s, YES);
355                                                         blksize = (size_t)tfc_modifysize((tfc_fsize)blksize, strchr(s, ':'));
356                                                         if (blksize == NOSIZE) xerror(NO, YES, YES,
357                                                         "%s: invalid block size value", s);
358                                                 }
359                                                 else blksize = (size_t)tfc_modifysize((tfc_fsize)blksize, strchr(s, ':'));
360                                                 if (blksize < TF_BLOCK_SIZE) xerror(NO, YES, YES,
361                                                         "%s: block size is lesser than TF_BLOCK_SIZE (%u bytes)", s, TFC_U(TF_BLOCK_SIZE));
362                                                 if (blksize > TFC_BLKSIZE) xerror(NO, YES, YES,
363                                                         "%s: block size exceeds %u bytes",
364                                                         s, TFC_U(TFC_BLKSIZE));
365                                         }
366                                         else if (!strncmp(s, "xtsblocks", 9) && *(s+9) == '=') {
367                                                 s += 10;
368                                                 xtsblocks = (size_t)tfc_humanfsize(s, &stoi);
369                                                 if (!str_empty(stoi)) {
370                                                         xtsblocks = (size_t)tfc_fnamesize(s, YES);
371                                                         xtsblocks = (size_t)tfc_modifysize((tfc_fsize)xtsblocks, strchr(s, ':'));
372                                                         if (xtsblocks == NOSIZE) xerror(NO, YES, YES,
373                                                         "%s: invalid blocks per xts block value", s);
374                                                 }
375                                                 else xtsblocks = (size_t)tfc_modifysize((tfc_fsize)xtsblocks, strchr(s, ':'));
376                                                 if (TFC_BLKSIZE % xtsblocks) xerror(NO, YES, YES,
377                                                         "%s: nr of blocks per xts block is not round to %u bytes",
378                                                         s, TFC_U(TFC_BLKSIZE));
379                                                 if ((xtsblocks * TF_BLOCK_SIZE) > TFC_BLKSIZE) xerror(NO, YES, YES,
380                                                         "%s: nr of blocks per xts block exceeds %u bytes",
381                                                         s, TFC_U(TFC_BLKSIZE));
382                                         }
383                                         else if (!strncmp(s, "iseek", 5) && *(s+5) == '=') {
384                                                 s += 6;
385                                                 iseek = tfc_humanfsize(s, &stoi);
386                                                 if (!str_empty(stoi)) {
387                                                         iseek = tfc_fnamesize(s, YES);
388                                                         iseek = tfc_modifysize(iseek, strchr(s, ':'));
389                                                         if (iseek == NOFSIZE) xerror(NO, YES, YES,
390                                                         "%s: invalid iseek value", s);
391                                                 }
392                                                 else iseek = tfc_modifysize(iseek, strchr(s, ':'));
393                                                 if (ctr_mode != TFC_MODE_PLAIN && iseek % TF_BLOCK_SIZE)
394                                                         xerror(NO, YES, YES,
395                                                                 "%s: not round to TF block size "
396                                                                 "of %u bytes",
397                                                                 s, TFC_U(TF_BLOCK_SIZE));
398                                                 iseek_blocks = iseek / TF_BLOCK_SIZE;
399                                         }
400                                         else if (!strncmp(s, "ixseek", 6) && *(s+6) == '=') {
401                                                 s += 7;
402                                                 iseek = tfc_humanfsize(s, &stoi);
403                                                 if (!str_empty(stoi)) {
404                                                         iseek = tfc_fnamesize(s, YES);
405                                                         iseek = tfc_modifysize(iseek, strchr(s, ':'));
406                                                         if (iseek == NOFSIZE) xerror(NO, YES, YES,
407                                                                 "%s: invalid ixseek value", s);
408                                                 }
409                                                 else iseek = tfc_modifysize(iseek, strchr(s, ':'));
410                                         }
411                                         else if (!strncmp(s, "ictr", 4) && *(s+4) == '=') {
412                                                 s += 5;
413                                                 iseek_blocks = tfc_humanfsize(s, &stoi);
414                                                 if (!str_empty(stoi)) {
415                                                         iseek_blocks = tfc_fnamesize(s, YES);
416                                                         if (iseek_blocks == NOFSIZE)
417                                                                 xerror(NO, YES, YES,
418                                                                 "%s: invalid ictr value", s);
419                                                         iseek_blocks /= TF_BLOCK_SIZE;
420                                                         iseek_blocks = tfc_modifysize(iseek_blocks, strchr(s, ':'));
421                                                 }
422                                                 else iseek_blocks = tfc_modifysize(iseek_blocks, strchr(s, ':'));
423                                         }
424                                         else if (!strncmp(s, "ixctr", 5) && *(s+5) == '=') {
425                                                 s += 6;
426                                                 iseek_blocks = tfc_humanfsize(s, &stoi);
427                                                 if (!str_empty(stoi)) {
428                                                         iseek_blocks = tfc_fnamesize(s, YES);
429                                                         iseek_blocks = tfc_modifysize(iseek_blocks, strchr(s, ':'));
430                                                         if (iseek_blocks == NOFSIZE)
431                                                                 xerror(NO, YES, YES,
432                                                                 "%s: invalid ixctr value", s);
433                                                 }
434                                                 else iseek_blocks = tfc_modifysize(iseek_blocks, strchr(s, ':'));
435                                                 if (iseek_blocks % TF_BLOCK_SIZE)
436                                                         xerror(NO, YES, YES,
437                                                         "%s: not round to TF block size "
438                                                         "of %u bytes", s, TFC_U(TF_BLOCK_SIZE));
439                                                 iseek_blocks /= TF_BLOCK_SIZE;
440                                         }
441                                         else if (!strncmp(s, "oseek", 5) && *(s+5) == '=') {
442                                                 s += 6;
443                                                 oseek = tfc_humanfsize(s, &stoi);
444                                                 if (!str_empty(stoi)) {
445                                                         oseek = tfc_fnamesize(s, YES);
446                                                         oseek = tfc_modifysize(oseek, strchr(s, ':'));
447                                                         if (oseek == NOFSIZE) xerror(NO, YES, YES,
448                                                         "%s: invalid oseek value", s);
449                                                 }
450                                                 else oseek = tfc_modifysize(oseek, strchr(s, ':'));
451                                         }
452                                         else if (!strncmp(s, "count", 5) && *(s+5) == '=') {
453                                                 s += 6;
454                                                 maxlen = tfc_humanfsize(s, &stoi);
455                                                 if (!str_empty(stoi)) {
456                                                         maxlen = tfc_fnamesize(s, YES);
457                                                         maxlen = tfc_modifysize(maxlen, strchr(s, ':'));
458                                                         if (maxlen == NOFSIZE) xerror(NO, YES, YES,
459                                                         "%s: invalid count value", s);
460                                                 }
461                                                 else maxlen = tfc_modifysize(maxlen, strchr(s, ':'));
462                                                 if (counter_opt == TFC_CTR_HEAD)
463                                                         maxlen += TF_BLOCK_SIZE;
464                                         }
465                                         else if (!strncmp(s, "ftrunc", 6) && *(s+6) == '=') {
466                                                 s += 7;
467                                                 if (!strcmp(s, "tail")) {
468                                                         do_ftrunc = TFC_FTRUNC_TAIL;
469                                                         ftrunc_dfd = NOFSIZE;
470                                                 }
471                                                 else {
472                                                         do_ftrunc = TFC_DO_FTRUNC;
473                                                         ftrunc_dfd = tfc_humanfsize(s, &stoi);
474                                                         if (!str_empty(stoi)) {
475                                                                 ftrunc_dfd = tfc_fnamesize(s, YES);
476                                                                 ftrunc_dfd = tfc_modifysize(ftrunc_dfd, strchr(s, ':'));
477                                                                 if (ftrunc_dfd == NOFSIZE) xerror(NO, YES, YES,
478                                                                 "%s: invalid ftrunc value", s);
479                                                         }
480                                                         else ftrunc_dfd = tfc_modifysize(ftrunc_dfd, strchr(s, ':'));
481                                                 }
482                                         }
483                                         else if (!strncmp(s, "xkey", 4) && *(s+4) == '=') {
484                                                 s += 5;
485                                                 maxkeylen = tfc_humanfsize(s, &stoi);
486                                                 if (!str_empty(stoi)) {
487                                                         maxkeylen = tfc_fnamesize(s, YES);
488                                                         maxkeylen = tfc_modifysize(maxkeylen, strchr(s, ':'));
489                                                         if (maxkeylen == NOSIZE)
490                                                                 xerror(NO, YES, YES,
491                                                                 "%s: invalid key length value", s);
492                                                 }
493                                                 else maxkeylen = tfc_modifysize(maxkeylen, strchr(s, ':'));
494                                         }
495                                         else if (!strncmp(s, "okey", 4) && *(s+4) == '=') {
496                                                 s += 5;
497                                                 keyoffset = tfc_humanfsize(s, &stoi);
498                                                 if (!str_empty(stoi)) {
499                                                         keyoffset = tfc_fnamesize(s, YES);
500                                                         keyoffset = tfc_modifysize(keyoffset, strchr(s, ':'));
501                                                         if (keyoffset == NOFSIZE)
502                                                                 xerror(NO, YES, YES,
503                                                                 "%s: invalid key offset value", s);
504                                                 }
505                                                 else keyoffset = tfc_modifysize(keyoffset, strchr(s, ':'));
506                                         }
507                                         else if (!strncmp(s, "xctr", 4) && *(s+4) == '=') {
508                                                 s += 5;
509                                                 ctrsz = tfc_humanfsize(s, &stoi);
510                                                 if (!str_empty(stoi)) {
511                                                         ctrsz = (size_t)tfc_fnamesize(s, YES);
512                                                         ctrsz = (size_t)tfc_modifysize((tfc_fsize)ctrsz, strchr(s, ':'));
513                                                         if (ctrsz == NOSIZE)
514                                                                 xerror(NO, YES, YES,
515                                                                 "%s: invalid counter length value", s);
516                                                 }
517                                                 else ctrsz = (size_t)tfc_modifysize((tfc_fsize)ctrsz, strchr(s, ':'));
518                                                 if (ctrsz > TF_BLOCK_SIZE)
519                                                         xerror(NO, YES, YES, "%s: counter size cannot exceed TF block size", s);
520                                         }
521                                         else xerror(NO, YES, YES, "invalid option %s", s);
522                                 }
523                                 break;
524                         case 'S':
525                                 do_mac = TFC_MAC_SIGN;
526                                 if (strcasecmp(optarg, "mac") != 0)
527                                         do_mac_file = optarg;
528                                 break;
529                         case 'M':
530                                 do_mac = TFC_MAC_VRFY;
531                                 if (!strcasecmp(optarg, "drop"))
532                                         do_mac = TFC_MAC_DROP;
533                                 else if (strcasecmp(optarg, "mac") != 0)
534                                         do_mac_file = optarg;
535                                 break;
536                         case 'm':
537                         case 'u':
538                                 if (do_mac != TFC_MAC_VRFY)
539                                         xerror(NO, YES, YES, "signature source was not specified");
540                                 do_mac = TFC_MAC_JUST_VRFY;
541                                 if (c == 'u') do_mac = TFC_MAC_JUST_VRFY2;
542                                 break;
543                         case 'R':
544                         case 'Z':
545                                 if (maxlen != NOFSIZE) {
546                                         if (c == 'Z') genzero_nr_bytes = maxlen;
547                                         else genrandom_nr_bytes = maxlen;
548                                 }
549                                 else {
550                                         tfc_fsize t;
551                                         if (!strcasecmp(optarg, "cbs"))
552                                                 t = TF_BLOCK_SIZE;
553                                         else if (!strcasecmp(optarg, "ks"))
554                                                 t = TF_FROM_BITS(TFC_KEY_BITS);
555                                         else if (!strcasecmp(optarg, "xks"))
556                                                 t = TF_FROM_BITS(TFC_KEY_BITS) * 2;
557                                         else if (!strcasecmp(optarg, "iobs"))
558                                                 t = blksize;
559                                         else {
560                                                 t = tfc_humanfsize(optarg, &stoi);
561                                                 if (!str_empty(stoi)) {
562                                                         t = tfc_fnamesize(optarg, NO);
563                                                         t = tfc_modifysize(t, strchr(optarg, ':'));
564                                                 }
565                                                 else t = tfc_modifysize(t, strchr(optarg, ':'));
566                                         }
567                                         if (c == 'Z') genzero_nr_bytes = maxlen = t;
568                                         else genrandom_nr_bytes = maxlen = t;
569                                 }
570                                 break;
571                         case 'a':
572                                 do_preserve_time = YES;
573                                 break;
574                         case 'A':
575                                 do_outfmt = TFC_OUTFMT_B64;
576                                 break;
577                         case 'W':
578                                 do_outfmt = TFC_OUTFMT_RAW;
579                                 break;
580                         case 'H':
581                                 do_outfmt = TFC_OUTFMT_HEX;
582                                 break;
583                         case 'q':
584                                 quiet = YES;
585                                 xexit_no_nl = YES;
586                                 verbose = NO;
587                                 do_full_hexdump = NO;
588                                 status_timer = 0;
589                                 break;
590                         case 'v':
591                                 verbose = YES;
592                                 break;
593                         case 'V':
594                                 td = strtod(optarg, &stoi);
595                                 status_timer = TFC_DTOUSECS(td);
596                                 if (status_timer <= TFC_DTOUSECS(0) || !str_empty(stoi)) status_timer = 0;
597                                 break;
598                         default:
599                                 usage();
600                                 break;
601                 }
602         }
603
604         if (!strcmp(progname, "tfbench")) {
605                 if (!*(argv+optind)) usage();
606
607                 td = strtod(*(argv+optind), &stoi);
608                 if (td <= TFC_DTOUSECS(0) || !str_empty(stoi))
609                         xerror(NO, YES, YES,
610                         "%s: invalid benchmark time in seconds", *(argv+optind));
611                 bench_timer = TFC_DTOUSECS(td);
612                 do_benchmark(bench_timer, td);
613         }
614         if (genrandom_nr_bytes) {
615                 ctr_mode = TFC_MODE_STREAM;
616                 do_edcrypt = TFC_DO_ENCRYPT;
617                 gen_write_bytes(*(argv+optind), oseek, genrandom_nr_bytes);
618         }
619         if (genzero_nr_bytes) {
620                 ctr_mode = TFC_MODE_PLAIN;
621                 do_edcrypt = TFC_DO_PLAIN;
622                 gen_write_bytes(*(argv+optind), oseek, genzero_nr_bytes);
623         }
624
625         if (rawkey && password)
626                 xerror(NO, YES, YES, "Cannot use rawkey and hashing password!");
627         if (do_edcrypt == TFC_DO_ENCRYPT && do_mac >= TFC_MAC_VRFY)
628                 xerror(NO, YES, YES, "Cannot encrypt and verify signature!");
629         if (do_edcrypt == TFC_DO_DECRYPT && do_mac == TFC_MAC_SIGN)
630                 xerror(NO, YES, YES, "Cannot decrypt and calculate signature!");
631         if (do_edcrypt == TFC_DO_DECRYPT && counter_opt == TFC_CTR_RAND)
632                 xerror(NO, YES, YES, "Cannot decrypt and embed a generated CTR into file!");
633         if (do_edcrypt == TFC_DO_ENCRYPT && counter_opt == TFC_CTR_HEAD)
634                 xerror(NO, YES, YES, "Cannot encrypt and read CTR from source!");
635         if (overwrite_source && counter_opt == TFC_CTR_RAND)
636                 xerror(NO, YES, YES, "Cannot embed a CTR into file when overwriting it!");
637         if (ctr_mode == TFC_MODE_PLAIN
638         && (do_edcrypt || do_mac || rawkey
639         || mackey_opt || counter_opt || counter_file))
640                 xerror(NO, YES, YES, "Encryption facility is disabled when in plain IO mode.");
641
642         errno = 0;
643         do_stop = NO;
644
645         if (saltf) {
646                 int saltfd;
647
648                 memset(tfc_salt, 0, TFC_MAX_SALT);
649                 tfc_saltsz = 0;
650                 if (!strcasecmp(saltf, "disable")) goto _nosalt;
651
652                 if (!strcmp(saltf, "-")) saltfd = 0;
653                 else saltfd = open(saltf, O_RDONLY | O_LARGEFILE);
654                 if (saltfd == -1) xerror(NO, NO, YES, "%s", saltf);
655                 lio = xread(saltfd, tfc_salt, TFC_MAX_SALT - TF_FROM_BITS(TFC_KEY_BITS));
656                 if (lio == NOSIZE) xerror(NO, NO, YES, "%s", saltf);
657                 tfc_saltsz = lio;
658                 xclose(saltfd);
659         }
660
661 _nosalt:
662         if (mackey_opt == TFC_MACKEY_FILE && mackeyf) {
663                 int mkfd = -1;
664                 tfc_yesno do_stop;
665
666                 if (!strcmp(mackeyf, "-")) mkfd = 0;
667                 else mkfd = open(mackeyf, O_RDONLY | O_LARGEFILE);
668                 if (mkfd == -1) xerror(NO, NO, YES, "%s", mackeyf);
669
670                 skein_init(&sk, TFC_KEY_BITS);
671
672                 do_stop = NO;
673                 while (1) {
674                         if (do_stop) break;
675                         pblk = tmpdata;
676                         ldone = 0;
677                         lrem = lblock = sizeof(tmpdata);
678                         if (error_action == TFC_ERRACT_SYNC) rdpos = tfc_fdgetpos(mkfd);
679 _mkragain:              lio = xread(mkfd, pblk, lrem);
680                         if (lio == 0 && do_stop == NO) do_stop = YES;
681                         if (lio != NOSIZE) ldone += lio;
682                         else {
683                                 if (errno != EIO && catch_all_errors != YES)
684                                         xerror(NO, NO, NO, "%s", mackeyf);
685                                 switch (error_action) {
686                                         case TFC_ERRACT_CONT: xerror(YES, NO, NO, "%s", mackeyf); goto _mkragain; break;
687                                         case TFC_ERRACT_SYNC:
688                                         case TFC_ERRACT_LSYNC:
689                                                 xerror(YES, NO, NO, "%s", mackeyf);
690                                                 lio = ldone = lrem = lblock;
691                                                 memset(tmpdata, 0, lio);
692                                                 if (rdpos == NOFSIZE) lseek(mkfd, lio, SEEK_CUR);
693                                                 else lseek(mkfd, rdpos + lio, SEEK_SET);
694                                                 break;
695                                         default: xerror(NO, NO, NO, "%s", mackeyf); break;
696                                 }
697                         }
698                         if (lio && lio < lrem) {
699                                 pblk += lio;
700                                 lrem -= lio;
701                                 goto _mkragain;
702                         }
703
704                         skein_update(&sk, tmpdata, ldone);
705                 }
706
707                 skein_final(mackey, &sk);
708
709                 xclose(mkfd);
710         }
711         else if (mackey_opt == TFC_MACKEY_PASSWORD) {
712                 memset(&getps, 0, sizeof(struct getpasswd_state));
713                 getps.fd = getps.efd = -1;
714                 getps.passwd = pwdask;
715                 getps.pwlen = sizeof(pwdask)-1;
716                 getps.echo = mac_pw_prompt ? mac_pw_prompt : "Enter MAC password: ";
717                 getps.charfilter = (show_secrets == YES) ? getps_plain_filter : getps_filter;
718                 getps.maskchar = (show_secrets == YES) ? 0 : 'x';
719                 getps.flags = GETP_WAITFILL;
720                 n = xgetpasswd(&getps);
721                 if (n == NOSIZE) xerror(NO, NO, YES, "getting MAC password");
722                 if (n == ((size_t)-2)) xexit(1);
723                 if (verbose) say_hint(pwdask, n, "MAC password hint");
724                 skein(mackey, TF_MAX_BITS, NULL, pwdask, n);
725         }
726
727         
728         if ((strlen(progname) <= 9)
729         && ((!strcmp(progname, "sksum"))
730         || ((!memcmp(progname, "sk", 2))
731         && (!memcmp(progname+3, "sum", 3)
732         || !memcmp(progname+4, "sum", 3)
733         || !memcmp(progname+5, "sum", 3)
734         || !memcmp(progname+6, "sum", 3)))))
735                 do_sksum(progname, argv+optind);
736         if (!strcmp(progname, "tfbase64")) do_edbase64(argv+optind);
737
738         idx = optind;
739
740         if (argv[idx]) {
741                 if (password || rawkey > TFC_RAWKEY_KEYFILE) goto _nokeyfd;
742                 if (!strcmp(argv[idx], "-")) kfd = 0;
743                 else kfd = open(argv[idx], O_RDONLY | O_LARGEFILE);
744                 if (kfd == -1) xerror(NO, NO, YES, "%s", argv[idx]);
745
746                 lio = strnlen(argv[idx], PATH_MAX);
747                 memset(argv[idx], '*', lio);
748
749                 idx++;
750         }
751         else password = YES;
752
753         errno = 0;
754         if (do_full_key == NO && tweakf) {
755                 int twfd;
756
757                 if (!strcmp(tweakf, "-")) twfd = 0;
758                 else twfd = open(tweakf, O_RDONLY | O_LARGEFILE);
759                 if (twfd == -1) xerror(NO, NO, YES, "%s", tweakf);
760                 lio = ldone = xread(twfd, tweak, TF_TWEAK_SIZE);
761                 if (lio == NOSIZE) xerror(NO, NO, YES, "%s", tweakf);
762                 if (ldone < TF_TWEAK_SIZE)
763                         xerror(NO, NO, YES, "%s: %zu bytes tweak required", tweakf, TF_TWEAK_SIZE);
764                 xclose(twfd);
765         }
766
767 _nokeyfd:
768         errno = 0;
769         if (argv[idx]) {
770                 if (!strcmp(argv[idx], "-") && kfd) sfd = 0;
771                 else {
772                         sfd = open(argv[idx], O_RDONLY | O_LARGEFILE);
773                         if (do_preserve_time) if (fstat(sfd, &s_stat) == -1)
774                                 xerror(YES, NO, YES, "stat(%s)", argv[idx]);
775                 }
776                 if (sfd == -1) xerror(NO, NO, YES, "%s", argv[idx]);
777
778                 if ((do_mac >= TFC_MAC_VRFY || do_mac <= TFC_MAC_DROP) && !do_mac_file) {
779                         maxlen = tfc_fdsize(sfd);
780                         if (maxlen == NOFSIZE)
781                                 xerror(NO, YES, YES,
782                                 "Cannot verify embedded MAC with non-seekable source!");
783                         maxlen -= TF_FROM_BITS(macbits);
784                 }
785                 srcfname = argv[idx];
786                 idx++;
787         }
788
789         if (!do_mac_file && (do_mac >= TFC_MAC_VRFY && sfd == 0))
790                 xerror(NO, YES, YES, "Cannot verify embedded MAC with non-seekable source!");
791
792         if (ctrsz == NOSIZE) ctrsz = TF_BLOCK_SIZE;
793         if (ctrsz > TF_BLOCK_SIZE) ctrsz = TF_BLOCK_SIZE;
794
795         if (ctr_mode == TFC_MODE_ECB) goto _ctrskip1;
796         errno = 0;
797         if (counter_file) {
798                 int ctrfd;
799
800                 if (!strcmp(counter_file, "-")) ctrfd = 0;
801                 else ctrfd = open(counter_file, O_RDONLY | O_LARGEFILE);
802                 if (ctrfd == -1) xerror(NO, NO, YES, "%s", counter_file);
803                 lio = xread(ctrfd, ctr, ctrsz);
804                 if (lio == NOSIZE) xerror(NO, NO, YES, "%s", counter_file);
805                 if (lio < ctrsz) xerror(NO, YES, YES, "counter file is too small (%zu)!", lio);
806                 xclose(ctrfd);
807         }
808         else if (counter_opt == TFC_CTR_HEAD) {
809                 pblk = ctr;
810                 ldone = 0;
811                 lrem = lblock = ctrsz;
812                 if (error_action == TFC_ERRACT_SYNC) rdpos = tfc_fdgetpos(sfd);
813 _ctrragain:     lio = xread(sfd, pblk, lrem);
814                 if (lio != NOSIZE) ldone += lio;
815                 else {
816                         if (errno != EIO && catch_all_errors != YES)
817                                 xerror(NO, NO, NO, "%s", srcfname);
818                         switch (error_action) {
819                                 case TFC_ERRACT_CONT: xerror(YES, NO, NO, "%s", srcfname); goto _ctrragain; break;
820                                 case TFC_ERRACT_SYNC:
821                                 case TFC_ERRACT_LSYNC:
822                                         xerror(YES, NO, NO, "%s", srcfname);
823                                         lio = ldone = lrem = lblock;
824                                         memset(ctr, 0, lio);
825                                         if (rdpos == NOFSIZE) lseek(sfd, lio, SEEK_CUR);
826                                         else lseek(sfd, rdpos + lio, SEEK_SET);
827                                         break;
828                                 default: xerror(NO, NO, NO, "%s", srcfname); break;
829                         }
830                 }
831                 if (lio && lio < lrem) {
832                         pblk += lio;
833                         lrem -= lio;
834                         goto _ctrragain;
835                 }
836                 total_processed_src += ldone;
837         }
838
839 _ctrskip1:
840         if (iseek) {
841                 if (counter_opt == TFC_CTR_HEAD && ctr_mode != TFC_MODE_ECB)
842                         iseek += ctrsz;
843                 if (lseek(sfd, iseek, SEEK_SET) == -1)
844                         xerror(ignore_seek_errors, NO, NO, "%s: seek failed", srcfname);
845         }
846
847         if (ctr_mode == TFC_MODE_PLAIN) goto _plain;
848
849         if (verbose) tfc_esay("%s: hashing password", tfc_format_pid(progname));
850
851         if (rawkey == TFC_RAWKEY_KEYFILE) {
852                 tfc_yesno xtskeyset = NO;
853
854                 pblk = key;
855 _xts2key:       ldone = 0;
856                 lrem = lblock = TF_FROM_BITS(TFC_KEY_BITS);
857                 if (error_action == TFC_ERRACT_SYNC) rdpos = tfc_fdgetpos(kfd);
858 _keyragain:     lio = xread(kfd, pblk, lrem);
859                 if (lio != NOSIZE) ldone += lio;
860                 else {
861                         if (errno != EIO && catch_all_errors != YES)
862                                 xerror(NO, NO, NO, "reading key");
863                         switch (error_action) {
864                                 case TFC_ERRACT_CONT: xerror(YES, NO, NO, "reading key"); goto _keyragain; break;
865                                 case TFC_ERRACT_SYNC:
866                                 case TFC_ERRACT_LSYNC:
867                                         xerror(YES, NO, NO, "reading key");
868                                         lio = ldone = lrem = lblock;
869                                         memset(key, 0, lio);
870                                         if (rdpos == NOFSIZE) lseek(kfd, lio, SEEK_CUR);
871                                         else lseek(kfd, rdpos + lio, SEEK_SET);
872                                         break;
873                                 default: xerror(NO, NO, NO, "reading key"); break;
874                         }
875                 }
876                 if (lio && lio < lrem) {
877                         pblk += lio;
878                         lrem -= lio;
879                         goto _keyragain;
880                 }
881                 if (ldone < lblock) xerror(NO, YES, YES, "rawkey too small! (%zu)", ldone);
882
883                 if (ctr_mode == TFC_MODE_XTS) {
884                         if (xtskeyset == NO) {
885                                 pblk = xtskey;
886                                 xtskeyset = YES;
887                                 goto _xts2key;
888                         }
889                 }
890         }
891         else if (rawkey == TFC_RAWKEY_ASKSTR) {
892                 tfc_yesno xtskeyset = NO;
893
894                 pblk = key; n = sizeof(key);
895 _xts2keyaskstr: memset(&getps, 0, sizeof(struct getpasswd_state));
896                 getps.fd = getps.efd = -1;
897                 getps.passwd = (char *)pblk;
898                 getps.pwlen = n;
899                 getps.echo = pw_prompt ? pw_prompt : "Enter rawkey (str): ";
900                 getps.charfilter = (show_secrets == YES) ? getps_plain_filter : getps_filter;
901                 getps.maskchar = (show_secrets == YES) ? 0 : 'x';
902                 getps.flags = GETP_WAITFILL;
903                 n = xgetpasswd(&getps);
904                 if (n == NOSIZE) xerror(NO, NO, YES, "getting string rawkey");
905                 if (n == ((size_t)-2)) xexit(1);
906                 if (verbose) say_hint(pblk, n, "Raw string key hint");
907                 if (ctr_mode == TFC_MODE_XTS) {
908                         if (xtskeyset == NO) {
909                                 pblk = xtskey; n = sizeof(xtskey);
910                                 xtskeyset = YES;
911                                 goto _xts2keyaskstr;
912                         }
913                 }
914         }
915         else if (rawkey == TFC_RAWKEY_ASKHEX) {
916                 tfc_yesno xtskeyset = NO;
917
918                 pblk = key;
919 _rawkey_hex_again:
920                 memset(&getps, 0, sizeof(struct getpasswd_state));
921                 getps.fd = getps.efd = -1;
922                 getps.passwd = pwdask;
923                 getps.pwlen = (TF_FROM_BITS(TFC_KEY_BITS)*2);
924                 getps.echo = pw_prompt ? pw_prompt : "Enter rawkey (hex): ";
925                 getps.charfilter = (show_secrets == YES) ? getps_plain_hex_filter : getps_hex_filter;
926                 getps.maskchar = (show_secrets == YES) ? 0 : 'x';
927                 getps.flags = GETP_WAITFILL;
928                 n = xgetpasswd(&getps);
929                 if (n == NOSIZE) xerror(NO, NO, YES, "getting hex rawkey");
930                 if (n == ((size_t)-2)) xexit(1);
931                 if (n % 2) {
932                         tfc_esay("Please input even number of hex digits!");
933                         goto _rawkey_hex_again;
934                 }
935                 hex2bin(pblk, pwdask);
936                 memset(pwdask, 0, sizeof(pwdask));
937                 if (verbose) say_hint(pblk, n/2, "Raw hex key hint");
938                 if (ctr_mode == TFC_MODE_XTS) {
939                         if (xtskeyset == NO) {
940                                 pblk = xtskey;
941                                 xtskeyset = YES;
942                                 goto _rawkey_hex_again;
943                         }
944                 }
945         }
946         else if (password) {
947 _pwdagain:      memset(&getps, 0, sizeof(struct getpasswd_state));
948                 getps.fd = getps.efd = -1;
949                 getps.passwd = pwdask;
950                 getps.pwlen = sizeof(pwdask)-1;
951                 getps.echo = pw_prompt ? pw_prompt : "Enter password: ";
952                 getps.charfilter = (show_secrets == YES) ? getps_plain_filter : getps_filter;
953                 getps.maskchar = (show_secrets == YES) ? 0 : 'x';
954                 getps.flags = GETP_WAITFILL;
955                 n = xgetpasswd(&getps);
956                 if (n == NOSIZE) xerror(NO, NO, YES, "getting password");
957                 if (n == ((size_t)-2)) xexit(1);
958                 if (do_edcrypt == TFC_DO_ENCRYPT && no_repeat == NO) {
959                         getps.fd = getps.efd = -1;
960                         getps.passwd = pwdagain;
961                         getps.pwlen = sizeof(pwdagain)-1;
962                         getps.echo = "Enter it again: ";
963                         getps.flags = GETP_WAITFILL;
964                         n = xgetpasswd(&getps);
965                         if (n == NOSIZE) xerror(NO, NO, YES, "getting password again");
966                         if (n == ((size_t)-2)) xexit(1);
967                         if (strncmp(pwdask, pwdagain, sizeof(pwdagain)-1) != 0) {
968                                 tfc_esay("Passwords are different, try again");
969                                 goto _pwdagain;
970                         }
971                 }
972                 if (verbose) say_hint(pwdask, n, "Password hint");
973                 skein(key, TFC_KEY_BITS, mackey_opt ? mackey : NULL, pwdask, n);
974                 memset(pwdask, 0, sizeof(pwdask));
975                 memset(pwdagain, 0, sizeof(pwdagain));
976         }
977         else {
978                 if (skeinfd(key, TFC_KEY_BITS, mackey_opt ? mackey : NULL, kfd, keyoffset, maxkeylen) != YES)
979                         xerror(NO, NO, YES, "hashing key");
980         }
981
982         if (rawkey == NO) {
983                 if (tfc_saltsz > 0) {
984                         memcpy(tfc_salt+tfc_saltsz, key, TF_FROM_BITS(TFC_KEY_BITS));
985                         skein(key, TFC_KEY_BITS, mackey_opt ? mackey : NULL, tfc_salt, tfc_saltsz+TF_FROM_BITS(TFC_KEY_BITS));
986                 }
987                 if (nr_turns > 1) for (x = 0; x < nr_turns; x++)
988                         skein(key, TFC_KEY_BITS, mackey_opt ? mackey : NULL, key, TF_FROM_BITS(TFC_KEY_BITS));
989                 memset(tfc_salt, 0, TFC_MAX_SALT);
990         }
991
992         if (ctr_mode == TFC_MODE_XTS && rawkey == NO) {
993                 skein(xtskey, TF_NR_KEY_BITS, mackey_opt ? mackey : NULL, key, TF_FROM_BITS(TFC_KEY_BITS));
994         }
995
996         if (genkeyf) {
997                 int krfd;
998                 tfc_yesno xtskeyset = NO;
999
1000                 pblk = key;
1001                 if (!strcmp(genkeyf, "-")) krfd = 1;
1002                 else krfd = open(genkeyf, O_WRONLY | O_CREAT | O_LARGEFILE | write_flags, 0666);
1003                 if (krfd == -1) xerror(NO, NO, YES, "%s", genkeyf);
1004 _xts2genkey:    if (xwrite(krfd, pblk, TF_FROM_BITS(TFC_KEY_BITS)) == NOSIZE) xerror(NO, NO, YES, "%s", genkeyf);
1005                 if (do_fsync && fsync(krfd) == -1) xerror(NO, NO, YES, "%s", genkeyf);
1006                 if (verbose && xtskeyset == NO) {
1007                         tfc_esay("%s: password hashing done", tfc_format_pid(progname));
1008                         tfc_esay("%s: rawkey written to %s.", tfc_format_pid(progname), genkeyf);
1009                         tfc_esay("%s: Have a nice day!", tfc_format_pid(progname));
1010                 }
1011
1012                 if (ctr_mode == TFC_MODE_XTS) {
1013                         if (xtskeyset == NO) {
1014                                 pblk = xtskey;
1015                                 xtskeyset = YES;
1016                                 goto _xts2genkey;
1017                         }
1018                 }
1019
1020                 fchmod(krfd, 0600);
1021                 xclose(krfd);
1022                 xexit(0);
1023         }
1024
1025         if (do_mac != NO) {
1026                 if (mackey_opt == TFC_MACKEY_RAWKEY) skein(mackey, TF_MAX_BITS, key, key, TF_FROM_BITS(TFC_KEY_BITS));
1027                 if (ctr_mode < TFC_MODE_OCB) {
1028                         if (verbose) tfc_esay("%s: doing MAC calculation, processing speed "
1029                                 "will be slower.", tfc_format_pid(progname));
1030                         if (mackey_opt) skein_init_key(&sk, mackey, macbits);
1031                         else skein_init(&sk, macbits);
1032                 }
1033         }
1034
1035         if (!counter_file && counter_opt <= TFC_CTR_SHOW && ctr_mode != TFC_MODE_ECB) {
1036                 skein(ctr, TF_TO_BITS(ctrsz), mackey_opt ? mackey : NULL, key, TF_FROM_BITS(TFC_KEY_BITS));
1037         }
1038
1039         tf_convkey(key);
1040         if (ctr_mode == TFC_MODE_XTS) tf_convkey(xtskey);
1041         if (do_full_key == NO) {
1042                 if (!tweakf) skein(tweak, TF_NR_TWEAK_BITS, NULL, key, TF_FROM_BITS(TFC_KEY_BITS));
1043                 tf_tweak_set(key, tweak);
1044         }
1045         if (ctr_mode == TFC_MODE_ECB) goto _ctrskip2;
1046
1047         if (counter_opt == TFC_CTR_ZERO) memset(ctr, 0, ctrsz);
1048
1049         tfc_data_to_words64(&iseek_blocks, sizeof(iseek_blocks));
1050         tf_ctr_set(ctr, &iseek_blocks, sizeof(iseek_blocks));
1051         if (do_mac == TFC_MAC_JUST_VRFY2) memcpy(svctr, ctr, TF_BLOCK_SIZE);
1052
1053         if (counter_opt == TFC_CTR_SHOW) {
1054                 switch (do_outfmt) {
1055                         case TFC_OUTFMT_B64: tfc_printbase64(stderr, ctr, ctrsz, YES); break;
1056                         case TFC_OUTFMT_RAW: xwrite(2, ctr, ctrsz); break;
1057                         case TFC_OUTFMT_HEX: mehexdump(ctr, ctrsz, ctrsz, YES); break;
1058                 }
1059         }
1060         else if (counter_opt == TFC_CTR_RAND) tfc_getrandom(ctr, ctrsz);
1061
1062 _ctrskip2:
1063         if (kfd != -1) {
1064                 xclose(kfd);
1065                 kfd = -1;
1066         }
1067         if (verbose) tfc_esay("%s: password hashing done", tfc_format_pid(progname));
1068
1069         if (overwrite_source && srcfname) argv[idx] = srcfname;
1070
1071 _plain:
1072         if (argv[idx]) {
1073                 if (!strcmp(argv[idx], "-")) dfd = 1;
1074                 else dfd = open(argv[idx], O_RDWR | O_LARGEFILE | write_flags, 0666);
1075                 if (dfd == -1) {
1076                         dfd = open(argv[idx], O_WRONLY | O_CREAT | O_LARGEFILE | write_flags, 0666);
1077                         if (dfd == -1) xerror(NO, NO, YES, "%s", argv[idx]);
1078                 }
1079                 dstfname = argv[idx];
1080                 idx++;
1081         }
1082
1083         if (oseek) {
1084                 if (lseek(dfd, oseek, SEEK_SET) == -1)
1085                         xerror(ignore_seek_errors, NO, NO, "%s: seek failed", dstfname);
1086         }
1087
1088         for (x = 1; x < NSIG; x++) signal(x, SIG_IGN);
1089         memset(&sigact, 0, sizeof(sigact));
1090         sigact.sa_flags = SA_RESTART;
1091         sigact.sa_handler = print_crypt_status;
1092         sigaction(SIGUSR1, &sigact, NULL);
1093         sigaction(SIGALRM, &sigact, NULL);
1094         if (status_timer) setup_next_alarm(status_timer > 1000000 ? 1000000 : status_timer);
1095         sigact.sa_handler = change_status_width;
1096         sigaction(SIGQUIT, &sigact, NULL);
1097         sigact.sa_handler = change_status_timer;
1098         sigaction(SIGUSR2, &sigact, NULL);
1099         if (quiet == NO) {
1100                 sigact.sa_handler = print_crypt_status;
1101                 sigaction(SIGINT, &sigact, NULL);
1102                 sigaction(SIGTERM, &sigact, NULL);
1103                 sigaction(SIGTSTP, &sigact, NULL);
1104         }
1105         else {
1106                 sigact.sa_handler = exit_sigterm;
1107                 sigaction(SIGINT, &sigact, NULL);
1108                 sigaction(SIGTERM, &sigact, NULL);
1109                 sigact.sa_handler = handle_sigtstp;
1110                 sigaction(SIGTSTP, &sigact, NULL);
1111         }
1112         memset(&sigact, 0, sizeof(struct sigaction));
1113
1114         tfc_getcurtime(&delta_time);
1115
1116         errno = 0;
1117         if (counter_opt == TFC_CTR_RAND && ctr_mode != TFC_MODE_ECB) {
1118                 pblk = ctr;
1119                 lio = lrem = ctrsz;
1120                 ldone = 0;
1121 _ctrwagain:     lio = xwrite(dfd, pblk, lrem);
1122                 if (lio != NOSIZE) ldone += lio;
1123                 else xerror(NO, NO, NO, "%s", dstfname);
1124                 if (do_fsync && fsync(dfd) == -1) xerror(NO, NO, NO, "%s", dstfname);
1125                 if (lio < lrem) {
1126                         pblk += lio;
1127                         lrem -= lio;
1128                         goto _ctrwagain;
1129                 }
1130                 total_written_dst += ldone;
1131                 total_processed_dst += ldone;
1132                 delta_processed += ldone;
1133         }
1134
1135         if (ctr_mode == TFC_MODE_STREAM) tfe_init_iv(&tfe, key, ctr);
1136
1137         if (do_mac == TFC_MAC_JUST_VRFY2) {
1138                 rwd = tfc_fdgetpos(sfd);
1139                 if (rwd == NOFSIZE) {
1140                         tfc_esay("%s: WARNING: input is not seekable, disabling MAC testing mode", tfc_format_pid(progname));
1141                         do_mac = TFC_MAC_VRFY;
1142                 }
1143                 goto _nodecrypt_again_vrfy2;
1144
1145 _decrypt_again_vrfy2:
1146                 if (lseek(sfd, (off_t)rwd, SEEK_SET) == ((off_t)-1)) {
1147                         xerror(ignore_seek_errors, NO, YES, "MAC testing seek failed");
1148                 }
1149                 total_processed_src = rwd;
1150                 memcpy(ctr, svctr, TF_BLOCK_SIZE);
1151                 memset(svctr, 0, TF_BLOCK_SIZE);
1152         }
1153
1154 _nodecrypt_again_vrfy2:
1155         loopcnt = 1;
1156         errno = 0;
1157         do_stop = NO;
1158         while (1) {
1159                 if (do_stop) break;
1160                 pblk = srcblk;
1161                 ldone = 0;
1162                 lrem = lblock = blk_len_adj(maxlen, total_processed_src, blksize);
1163                 if (error_action == TFC_ERRACT_SYNC) rdpos = tfc_fdgetpos(sfd);
1164 _ragain:        lio = xread(sfd, pblk, lrem);
1165                 if (lio == 0) {
1166                         if ((do_read_loops != 0 && sfd != 0) && (loopcnt < do_read_loops)) {
1167                                 lseek(sfd, 0L, SEEK_SET);
1168                                 loopcnt++;
1169                                 goto _ragain;
1170                         }
1171
1172                         do_stop = YES;
1173                 }
1174                 if (lio != NOSIZE) ldone += lio;
1175                 else {
1176                         if (errno != EIO && catch_all_errors != YES)
1177                                 xerror(NO, NO, NO, "%s", srcfname);
1178                         switch (error_action) {
1179                                 case TFC_ERRACT_CONT: xerror(YES, NO, NO, "%s", srcfname); goto _ragain; break;
1180                                 case TFC_ERRACT_SYNC:
1181                                 case TFC_ERRACT_LSYNC:
1182                                         xerror(YES, NO, NO, "%s", srcfname);
1183                                         lio = ldone = lrem = lblock;
1184                                         memset(srcblk, 0, lio);
1185                                         if (rdpos == NOFSIZE) lseek(sfd, lio, SEEK_CUR);
1186                                         else lseek(sfd, rdpos + lio, SEEK_SET);
1187                                         break;
1188                                 default: xerror(NO, NO, NO, "%s", srcfname); break;
1189                         }
1190                 }
1191                 if (lio && lio < lrem) {
1192                         pblk += lio;
1193                         lrem -= lio;
1194                         goto _ragain;
1195                 }
1196                 total_processed_src += ldone;
1197
1198                 if (do_pad && (ldone % TF_BLOCK_SIZE)) {
1199                         size_t orig = ldone;
1200                         ldone += (TF_BLOCK_SIZE - (ldone % TF_BLOCK_SIZE));
1201                         if (ldone > blksize) ldone = blksize;
1202                         memset(srcblk+orig, 0, sizeof(srcblk)-orig);
1203                 }
1204
1205                 if (do_mac == TFC_MAC_SIGN && ctr_mode < TFC_MODE_OCB)
1206                         skein_update(&sk, srcblk, ldone);
1207
1208                 if (ctr_mode == TFC_MODE_CTR) tf_ctr_crypt(key, ctr, dstblk, srcblk, ldone);
1209                 else if (ctr_mode == TFC_MODE_STREAM) tf_stream_crypt(&tfe, dstblk, srcblk, ldone);
1210                 else if (ctr_mode == TFC_MODE_XTS && do_edcrypt == TFC_DO_ENCRYPT)
1211                         tf_xts_encrypt(key, xtskey, ctr, dstblk, srcblk, ldone, xtsblocks);
1212                 else if (ctr_mode == TFC_MODE_XTS && do_edcrypt == TFC_DO_DECRYPT)
1213                         tf_xts_decrypt(key, xtskey, ctr, dstblk, srcblk, ldone, xtsblocks);
1214                 else if (ctr_mode == TFC_MODE_ECB && do_edcrypt == TFC_DO_ENCRYPT)
1215                         tf_ecb_encrypt(key, dstblk, srcblk, ldone);
1216                 else if (ctr_mode == TFC_MODE_ECB && do_edcrypt == TFC_DO_DECRYPT)
1217                         tf_ecb_decrypt(key, dstblk, srcblk, ldone);
1218                 else if (ctr_mode == TFC_MODE_CBC && do_edcrypt == TFC_DO_ENCRYPT)
1219                         tf_cbc_encrypt(key, ctr, dstblk, srcblk, ldone);
1220                 else if (ctr_mode == TFC_MODE_CBC && do_edcrypt == TFC_DO_DECRYPT)
1221                         tf_cbc_decrypt(key, ctr, dstblk, srcblk, ldone);
1222
1223                 else if (ctr_mode == TFC_MODE_OCB && do_edcrypt == TFC_DO_ENCRYPT)
1224                         tf_ocb_encrypt(key, ctr, dstblk, do_mac == TFC_MAC_SIGN ? macresult : NULL, srcblk, ldone, xtsblocks);
1225                 else if (ctr_mode == TFC_MODE_OCB && do_edcrypt == TFC_DO_DECRYPT)
1226                         tf_ocb_decrypt(key, ctr, dstblk, do_mac >= TFC_MAC_VRFY ? macresult : NULL, srcblk, ldone, xtsblocks);
1227
1228                 else if (ctr_mode == TFC_MODE_PLAIN)
1229                         memcpy(dstblk, srcblk, ldone);
1230
1231                 if (do_mac >= TFC_MAC_VRFY && ctr_mode < TFC_MODE_OCB)
1232                         skein_update(&sk, dstblk, ldone);
1233                 if (do_mac >= TFC_MAC_JUST_VRFY) goto _nowrite;
1234
1235                 pblk = dstblk;
1236                 lrem = ldone;
1237                 ldone = 0;
1238 _wagain:        lio = xwrite(dfd, pblk, lrem);
1239                 if (lio != NOSIZE) ldone += lio;
1240                 else xerror(NO, NO, NO, "%s", dstfname);
1241                 if (do_fsync && fsync(dfd) == -1) xerror(NO, NO, NO, "%s", dstfname);
1242                 if (lio < lrem) {
1243                         pblk += lio;
1244                         lrem -= lio;
1245                         goto _wagain;
1246                 }
1247                 total_written_dst += ldone;
1248 _nowrite:       total_processed_dst += ldone;
1249                 delta_processed += ldone;
1250
1251                 if (maxlen != NOFSIZE && total_processed_src >= maxlen) {
1252                         do_stop = YES;
1253                         break;
1254                 }
1255         }
1256
1257         if (verbose && status_timer && do_statline_dynamic == YES && statline_was_shown == YES) tfc_esay("\n");
1258
1259         errno = 0;
1260         if (do_mac >= TFC_MAC_VRFY) {
1261                 if (!do_mac_file) {
1262                         pblk = macvrfy;
1263                         ldone = 0;
1264                         lrem = lblock = TF_FROM_BITS(macbits);
1265                         if (error_action == TFC_ERRACT_SYNC) rdpos = tfc_fdgetpos(sfd);
1266 _macragain:             lio = xread(sfd, pblk, lrem);
1267                         if (lio != NOSIZE) ldone += lio;
1268                         else {
1269                                 if (errno != EIO && catch_all_errors != YES)
1270                                         xerror(NO, NO, NO, "%s", srcfname);
1271                                 switch (error_action) {
1272                                         case TFC_ERRACT_CONT: xerror(YES, NO, NO, "%s", srcfname); goto _macragain; break;
1273                                         case TFC_ERRACT_SYNC:
1274                                         case TFC_ERRACT_LSYNC:
1275                                                 xerror(YES, NO, NO, "%s", srcfname);
1276                                                 lio = ldone = lrem = lblock;
1277                                                 memset(macvrfy, 0, lio);
1278                                                 if (rdpos == NOFSIZE) lseek(sfd, lio, SEEK_CUR);
1279                                                 else lseek(sfd, rdpos + lio, SEEK_SET);
1280                                                 break;
1281                                         default: xerror(NO, NO, NO, "%s", srcfname); break;
1282                                 }
1283                         }
1284                         if (lio && lio < lrem) {
1285                                 pblk += lio;
1286                                 lrem -= lio;
1287                                 goto _macragain;
1288                         }
1289                         total_processed_src += ldone;
1290                 }
1291                 else {
1292                         int mfd;
1293
1294                         if (!strcmp(do_mac_file, "-")) mfd = 0;
1295                         else mfd = open(do_mac_file, O_RDONLY | O_LARGEFILE);
1296                         if (mfd == -1) xerror(YES, NO, NO, "%s", do_mac_file);
1297                         lio = ldone = xread(mfd, tmpdata, sizeof(tmpdata));
1298                         if (lio == NOSIZE) xerror(NO, NO, YES, "%s", do_mac_file);
1299                         if (!memcmp(tmpdata, TFC_ASCII_TFC_MAC_FOURCC, TFC_ASCII_TFC_MAC_FOURCC_LEN)) {
1300                                 memmove(tmpdata, tmpdata+TFC_ASCII_TFC_MAC_FOURCC_LEN,
1301                                         sizeof(tmpdata)-TFC_ASCII_TFC_MAC_FOURCC_LEN);
1302                                 lio = TF_FROM_BITS(macbits);
1303                                 base64_decode((char *)macvrfy, lio, (char *)tmpdata, sizeof(tmpdata));
1304                         }
1305                         else memcpy(macvrfy, tmpdata, TF_FROM_BITS(macbits));
1306                         xclose(mfd);
1307                 }
1308
1309                 if (ldone < TF_FROM_BITS(macbits)) {
1310                         if (quiet == NO) tfc_esay("%s: short signature (%zu), "
1311                                 "not verifying", tfc_format_pid(progname), ldone);
1312                         exitcode = 1;
1313                         goto _shortmac;
1314                 }
1315
1316                 if (ctr_mode < TFC_MODE_OCB) skein_final(macresult, &sk);
1317                 else skein(macresult, macbits, mackey, macresult, TF_FROM_BITS(macbits));
1318
1319                 if (ctr_mode == TFC_MODE_CTR) tf_ctr_crypt(key, ctr, tmpdata, macvrfy, TF_FROM_BITS(macbits));
1320                 else if (ctr_mode == TFC_MODE_STREAM) tf_stream_crypt(&tfe, tmpdata, macvrfy, TF_FROM_BITS(macbits));
1321                 else if (ctr_mode == TFC_MODE_XTS) tf_xts_decrypt(key, xtskey, ctr, tmpdata, macvrfy, TF_FROM_BITS(macbits), xtsblocks);
1322                 else if (ctr_mode == TFC_MODE_ECB) tf_ecb_decrypt(key, tmpdata, macvrfy, TF_FROM_BITS(macbits));
1323                 else if (ctr_mode == TFC_MODE_CBC) tf_cbc_decrypt(key, ctr, tmpdata, macvrfy, TF_FROM_BITS(macbits));
1324                 else if (ctr_mode == TFC_MODE_OCB) tf_ocb_decrypt(key, ctr, tmpdata, NULL, macvrfy, TF_FROM_BITS(macbits), xtsblocks);
1325
1326                 if (!memcmp(tmpdata, macresult, TF_FROM_BITS(macbits))) {
1327                         if (quiet == NO) {
1328                                 tfc_esay("%s: signature is good", tfc_format_pid(progname));
1329                                 if (verbose) {
1330                                         if (do_outfmt == TFC_OUTFMT_B64) tfc_printbase64(stderr, macresult, TF_FROM_BITS(macbits), YES);
1331                                         else mehexdump(macresult, TF_FROM_BITS(macbits), TF_FROM_BITS(macbits), YES);
1332                                 }
1333                         }
1334                         if (do_mac == TFC_MAC_JUST_VRFY2) {
1335                                 if (verbose) tfc_esay("%s: -u: MAC signature is valid, proceeding with decrypting it again", tfc_format_pid(progname));
1336                                 maxlen = total_processed_src - SKEIN_DIGEST_SIZE;
1337                                 do_mac = TFC_MAC_DROP2;
1338                                 goto _decrypt_again_vrfy2;
1339                         }
1340                 }
1341                 else {
1342                         if (quiet == NO) {
1343                                 tfc_esay("%s: signature is BAD: "
1344                                 "wrong password, key, mode, or file is not signed", tfc_format_pid(progname));
1345                                 if (do_mac == TFC_MAC_JUST_VRFY2) tfc_esay("%s: -u: MAC signature is invalid, not decrypting it again", tfc_format_pid(progname));
1346                         }
1347                         exitcode = 1;
1348                 }
1349
1350 _shortmac:      memset(macvrfy, 0, sizeof(macvrfy));
1351                 memset(macresult, 0, sizeof(macresult));
1352                 memset(tmpdata, 0, sizeof(tmpdata));
1353         }
1354         else if (do_mac == TFC_MAC_SIGN) {
1355                 if (ctr_mode < TFC_MODE_OCB) skein_final(macresult, &sk);
1356                 else skein(macresult, macbits, mackey, macresult, TF_FROM_BITS(macbits));
1357
1358                 if (ctr_mode == TFC_MODE_CTR) tf_ctr_crypt(key, ctr, tmpdata, macresult, TF_FROM_BITS(macbits));
1359                 else if (ctr_mode == TFC_MODE_STREAM) tf_stream_crypt(&tfe, tmpdata, macresult, TF_FROM_BITS(macbits));
1360                 else if (ctr_mode == TFC_MODE_XTS) tf_xts_encrypt(key, xtskey, ctr, tmpdata, macresult, TF_FROM_BITS(macbits), xtsblocks);
1361                 else if (ctr_mode == TFC_MODE_ECB) tf_ecb_encrypt(key, tmpdata, macresult, TF_FROM_BITS(macbits));
1362                 else if (ctr_mode == TFC_MODE_CBC) tf_cbc_encrypt(key, ctr, tmpdata, macresult, TF_FROM_BITS(macbits));
1363                 else if (ctr_mode == TFC_MODE_OCB) tf_ocb_encrypt(key, ctr, tmpdata, NULL, macresult, TF_FROM_BITS(macbits), xtsblocks);
1364                 memset(macresult, 0, sizeof(macresult));
1365
1366                 if (!do_mac_file) {
1367                         pblk = tmpdata;
1368                         lio = lrem = TF_FROM_BITS(macbits);
1369                         ldone = 0;
1370 _macwagain:             lio = xwrite(dfd, pblk, lrem);
1371                         if (lio != NOSIZE) ldone += lio;
1372                         else xerror(NO, NO, NO, "%s", dstfname);
1373                         if (do_fsync && fsync(dfd) == -1) xerror(NO, NO, NO, "%s", dstfname);
1374                         if (lio < lrem) {
1375                                 pblk += lio;
1376                                 lrem -= lio;
1377                                 goto _macwagain;
1378                         }
1379                         total_written_dst += ldone;
1380                         total_processed_dst += ldone;
1381                         delta_processed += ldone;
1382                 }
1383                 else {
1384                         int mfd;
1385
1386                         if (!strcmp(do_mac_file, "-")) mfd = 1;
1387                         else mfd = open(do_mac_file, O_WRONLY | O_CREAT | O_LARGEFILE | write_flags, 0666);
1388                         if (mfd == -1) xerror(YES, NO, NO, "%s", do_mac_file);
1389                         if (do_outfmt == TFC_OUTFMT_B64) {
1390                                 memcpy(macvrfy, tmpdata, TF_FROM_BITS(macbits));
1391                                 memset(tmpdata, 0, TFC_TMPSIZE);
1392                                 memcpy(tmpdata, TFC_ASCII_TFC_MAC_FOURCC, TFC_ASCII_TFC_MAC_FOURCC_LEN);
1393                                 base64_encode((char *)tmpdata+TFC_ASCII_TFC_MAC_FOURCC_LEN, (char *)macvrfy, TF_FROM_BITS(macbits));
1394                                 lrem = strnlen((char *)tmpdata, sizeof(tmpdata));
1395                                 if (lrem) {
1396                                         tmpdata[lrem] = '\n';
1397                                         lrem++;
1398                                 }
1399                                 lio = xwrite(mfd, tmpdata, lrem);
1400                         }
1401                         else lio = xwrite(mfd, tmpdata, TF_FROM_BITS(macbits));
1402                         if (lio == NOSIZE) xerror(NO, NO, YES, "%s", do_mac_file);
1403                         if (do_fsync && fsync(mfd) == -1) xerror(NO, NO, YES, "%s", do_mac_file);
1404                         xclose(mfd);
1405                 }
1406
1407                 memset(macvrfy, 0, sizeof(macvrfy));
1408                 memset(macresult, 0, sizeof(macresult));
1409                 memset(tmpdata, 0, sizeof(tmpdata));
1410         }
1411         else if (do_mac == TFC_MAC_DROP2) total_processed_src += SKEIN_DIGEST_SIZE;
1412
1413         if (verbose || status_timer || (do_stop == YES && quiet == NO)) print_crypt_status(0);
1414
1415         xexit(exitcode);
1416         return -1;
1417 }