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