6f994ef7daacc28d9bc675d6058386b2b478de44
[tfcrypt.git] / tfc_error.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 tfc_yesno xexit_no_nl;
32
33 void xerror(tfc_yesno noexit, tfc_yesno noerrno, tfc_yesno nostats, const char *fmt, ...)
34 {
35         va_list ap;
36         char *s;
37
38         if (quiet) goto _do_sil_exit;
39
40         va_start(ap, fmt);
41
42         if (statline_was_shown == YES && do_statline_dynamic == YES) tfc_esay("\n");
43
44         tfc_nfsay(stderr, "%s: ", tfc_format_pid(progname));
45         tfc_vfsay(stderr, NO, fmt, ap);
46         if (errno && noerrno == NO) {
47                 s = strerror(errno);
48                 tfc_esay(": %s", s);
49         }
50         else tfc_esay("\n");
51
52         va_end(ap);
53
54         if (nostats == NO) {
55                 print_crypt_status(-1);
56                 tfc_esay("\n");
57         }
58
59         xexit_no_nl = YES;
60
61 _do_sil_exit:
62         if (noexit == YES) {
63                 errno = 0;
64                 return;
65         }
66
67         xexit(2);
68 }
69
70 void xexit(int status)
71 {
72         if (status > 1) goto _do_clean_and_exit;
73
74         if (do_ftrunc > TFC_NO_FTRUNC) {
75                 if (do_ftrunc == TFC_FTRUNC_TAIL) ftrunc_dfd = total_processed_dst;
76                 if (ftruncate(dfd, (off_t)ftrunc_dfd) == -1) xerror(YES, NO, YES, "ftruncate(%d)", dfd);
77         }
78         if (do_preserve_time) fcopy_matime(dfd, &s_stat);
79
80 _do_clean_and_exit:
81         xclose(sfd);
82         xclose(dfd);
83
84         memset(srcblk, 0, sizeof(srcblk));
85         memset(dstblk, 0, sizeof(dstblk));
86
87         memset(key, 0, sizeof(key));
88         memset(ctr, 0, sizeof(ctr));
89         memset(mackey, 0, sizeof(mackey));
90         memset(xtskey, 0, sizeof(xtskey));
91         memset(tweak, 0, sizeof(tweak));
92         memset(&sk, 0, sizeof(struct skein));
93         memset(&tfe, 0, sizeof(struct tfe_stream));
94
95         tfc_finirandom();
96
97         memset(macvrfy, 0, sizeof(macvrfy));
98         memset(macresult, 0, sizeof(macresult));
99
100         memset(tmpdata, 0, sizeof(tmpdata));
101         memset(&getps, 0, sizeof(struct getpasswd_state));
102         memset(pwdask, 0, sizeof(pwdask));
103         memset(pwdagain, 0, sizeof(pwdagain));
104
105         if (xexit_no_nl == NO) tfc_esay("\n");
106         exit(status);
107 }
108
109 void usage(void)
110 {
111         tfc_yesno is_embedded_prog = NO;
112
113         xexit_no_nl = YES;
114
115         if (optopt == 'V') {
116                 tfc_say("tfcrypt toolkit, version %s.", _TFCRYPT_VERSION);
117                 if (ctr_mode != TFC_MODE_PLAIN) {
118                         char shash[64];
119
120                         hash_defaults(shash, sizeof(shash));
121                         tfc_say("Defaults hash: %s", shash);
122                         memset(shash, 0, sizeof(shash));
123                 }
124                 xexit(0);
125         }
126
127         if (!strcmp(progname, "iotool")) {
128                 is_embedded_prog = YES;
129                 tfc_say("usage: %s [-E how] [-l length] [-O opts] [-aqvw] [-V secs] [source] [output]", progname);
130                 tfc_say("\n");
131                 tfc_say("%s: do dd-like input/output, writing source to output whole or partially.", progname);
132                 tfc_say("  -E how: how to behave on I/O errors (both src or dst):");
133                 tfc_say("    exit: print error if not quiet, then exit,");
134                 tfc_say("    cont: print error if not quiet, then continue,");
135                 tfc_say("      no action to pad missing data is attempted.");
136                 tfc_say("      may be dangerous when working with block devices.");
137                 tfc_say("    sync: print error if not quiet, then continue,");
138                 tfc_say("      pad missing data block with zeroes.");
139                 tfc_say("    lsync: same as sync, but does not use SEEK_SET logic,");
140                 tfc_say("      lsync uses only relative seek operations, and does not prequery");
141                 tfc_say("      the current file position for exact offsets, which maybe unsafe.");
142                 tfc_say("      For this reason, it is HIGHLY recommended to use sync instead!");
143                 tfc_say("      Note that both sync and lsync work only with read errors!");
144                 tfc_say("  default error action is exit with printing status if not quiet.");
145                 tfc_say("  -E xall: turn on error actions above for all errors, not just EIO errors.");
146                 tfc_say("  -E xseek: ignore positioning and other seek related errors.");
147                 tfc_say("    Multiple -E specifiers may be given in separate options.");
148                 tfc_say("  -a: shortcut of -O xtime.");
149                 tfc_say("  -l length: read only these first bytes of source.");
150                 tfc_say("  -O opts: set options (comma separated list):");
151                 tfc_say("    ro: open all files only for reading, even those intended for writing,");
152                 tfc_say("    sync: request a synchronous I/O for a output,");
153                 tfc_say("    fsync: on each write() call a corresponding fsync(fd),");
154                 tfc_say("    trunc: open(O_WRONLY) will truncate output file to zero size.");
155                 tfc_say("    append: open(O_APPEND) will append data to output file.");
156                 tfc_say("    pad: pad incomplete (l.t. %u bytes) block with zeroes.", TFC_U(TF_BLOCK_SIZE));
157                 tfc_say("    xtime: copy timestamps from source to destination files.");
158                 tfc_say("    gibsize: use SI units of size: 1k = 1000. Applies only to size prefixes.");
159                 tfc_say("    Computers convention is to use 1024, whereas SI/hdd measure in 1000.");
160                 tfc_say("    plainstats: force status line to be plain: no fancy dynamic stuff.");
161                 tfc_say("    Dynamic line works well only on VT100 compatible ttys, and");
162                 tfc_say("    when the whole status line width is smaller than tty width.");
163                 tfc_say("    statless: emit less information in status line (only processed data).");
164                 tfc_say("    iobs=val: set IO block size value. Must not exceed %u bytes.", TFC_U(TFC_BLKSIZE));
165                 tfc_say("    nobuf: disable IO buffering, write as soon as data received (only for stream ciphers!)");
166                 tfc_say("    iseek=val: seek source file/device by these val bytes.");
167                 tfc_say("    oseek=val: seek destination file/device by these val bytes.");
168                 tfc_say("    ioseek=val: seek both source and destination.");
169                 tfc_say("    ioseek is equal to iseek and oseek.");
170                 tfc_say("    count=val: process only these val bytes, both input and output.");
171                 tfc_say("    ftrunc=val: truncate output file to these val bytes before closing it.");
172                 tfc_say("    ftrunc=tail: truncate output's tail, leaving only processed data.");
173                 tfc_say("  -w: overwrite source file. If not file, ignored.");
174                 tfc_say("  -q: always be quiet, never tell anything (except when signaled).");
175                 tfc_say("  -v: print number of read and written encrypted bytes, and explain stages.");
176                 tfc_say("  -V seconds: activate timer that will repeatedly print statistics to stderr.");
177                 tfc_say("\n");
178         }
179         else if ((strlen(progname) <= 9)
180         && ((!strcmp(progname, "sksum"))
181         || ((!memcmp(progname, "sk", 2))
182         && (!memcmp(progname+3, "sum", 3)
183         || !memcmp(progname+4, "sum", 3)
184         || !memcmp(progname+5, "sum", 3)
185         || !memcmp(progname+6, "sum", 3))))) {
186                 is_embedded_prog = YES;
187                 tfc_say("usage: %s [-AW] [-D BITS] [-n TURNS] [-l length] [-c <file>] [-U <file>] [source] ...", progname);
188                 tfc_say("\n");
189                 tfc_say("%s: calculate and print Skein hashsum of stream.", progname);
190                 tfc_say("  -D BITS: specify bits as it was skBITSsum.");
191                 tfc_say("  -n TURNS: number of turns to perform in Skein function.");
192                 tfc_say("    sksum defaults to just one in all modes.");
193                 tfc_say("  -A: format checksum in base64 rather than in binary hex.");
194                 tfc_say("  -W: output raw binary checksum and remove filename(s) from output.");
195                 tfc_say("  -H: output small hexdump (hex string and ASCII printable characters).");
196                 tfc_say("  -l length: read only these first bytes of source.");
197                 tfc_say("  -c <file>: read hashes list from file and check them.");
198                 tfc_say("  -U <file>: read Skein MAC key from file.");
199                 tfc_say("multiple sources can be given in cmdline, and if one of");
200                 tfc_say("them is specified as \"-\", then reads are performed from stdin.");
201                 tfc_say("\n");
202         }
203         else if (!strcmp(progname, "base64")) {
204                 is_embedded_prog = YES;
205                 tfc_say("usage: %s [-ed] [source] [output]", progname);
206                 tfc_say("\n");
207                 tfc_say("tfcrypt embedded base64 encoder/decoder.");
208                 tfc_say("  -e: encode stream into base64.");
209                 tfc_say("  -d: decode base64 stream.");
210                 tfc_say("no error checking is performed.");
211                 tfc_say("\n");
212         }
213         else if (!strcmp(progname, "tfbench")) {
214                 is_embedded_prog = YES;
215                 tfc_say("usage: %s seconds", progname);
216                 tfc_say("do an in-memory random data benchmark of Threefish.");
217                 tfc_say("\n");
218         }
219
220         if (is_embedded_prog) {
221                 tfc_say("This program is physical part of tfcrypt toolkit.");
222                 tfc_say("(see it's version with %s -V)", progname);
223                 tfc_say("Please note that other tfcrypt options are either ignored there,");
224                 tfc_say("or result of using them is undefined and it's not a bug.");
225
226                 xexit(1);
227         }
228
229         tfc_say("usage: %s [opts] [--] [key] [source] [output]", progname);
230         tfc_say("\n");
231         tfc_say("tfcrypt toolkit: encrypt streams with Threefish in CTR mode,");
232         tfc_say("calculate and check Skein hashsums, generate CSPRNG quality random data,");
233         tfc_say("convert encrypted data into ASCII format to ease transmission.");
234         tfc_say("\n");
235         tfc_say("  -e, -d: encrypt, decrypt (it maybe required).");
236         tfc_say("  -L <file>: load tfcrypt defaults from file.");
237         tfc_say("    defaults is text file which defines salt, nr_turns and default mode.");
238         tfc_say("  -s <file>: load tfcrypt salt from file.");
239         tfc_say("  -s disable: disable key salting at all.");
240         tfc_say("  -p: instead of using key, ask for password.");
241         tfc_say("  -k: use raw (%u byte) key instead of deriving it from arbitrary data.", TFC_U(TF_KEY_SIZE));
242         tfc_say("  -z: ask for key in plain C string form through password asker.");
243         tfc_say("  -x: ask for key in hex string form through password asker.");
244         tfc_say("  -K <file>: generate key from keyfile or password and write it to file.");
245         tfc_say("  -t <file>: use (raw) tweak from file.");
246         tfc_say("  -w: overwrite source file. If not file, ignored.");
247         tfc_say("  -n TURNS: number of turns to perform in Skein function.");
248         tfc_say("    Default is always defined when building tfcrypt.");
249         tfc_say("  -C mode: mode of operation: CTR, STREAM, XTS, ECB, CBC.");
250         tfc_say("    Default encryption mode can be changed when building tfcrypt.");
251         tfc_say("  -c opt: initial CTR value initialisation mode:");
252         tfc_say("    show: do default action, then dump CTR value to stderr,");
253         tfc_say("    head: when decrypting, read CTR from beginning of stream,");
254         tfc_say("    rand: generate random CTR and write it to beginning of stream,");
255         tfc_say("    zero: assume zero CTR is used, do not read from and write it to stream,");
256         tfc_say("    hexc:nr[,hexc:nr,...]: construct counter from given pattern.");
257         tfc_say("      Example: \"ff:124,08:2,80:2\" will fill counter first with 124 0xff bytes,");
258         tfc_say("      then with 2 0x08 bytes, then 2 0x80 bytes. To fill with zeroes, it is");
259         tfc_say("      simple to specify just a \"0:128\" as a pattern. Note that bytes that");
260         tfc_say("      exceed CTR space will be just dropped, and any unused bytes are set to zeroes.");
261         tfc_say("    <file>: read CTR from given file (both when encrypting/decrypting).");
262         tfc_say("      default is to derive CTR from user provided password or keyfile with");
263         tfc_say("      a single Skein function turn over derived, %u byte raw key", TFC_U(TF_KEY_SIZE));
264         tfc_say("  -q: always be quiet, never tell anything (except when signaled).");
265         tfc_say("  -v: print number of read and written encrypted bytes, and explain stages.");
266         tfc_say("  -V seconds: activate timer that will repeatedly print statistics to stderr.");
267         tfc_say("  -a: shortcut of -O xtime.");
268         tfc_say("  -l length: read only these first bytes of source.");
269         tfc_say("  -r <file>: specify random source instead of /dev/urandom.");
270         tfc_say("  -R nr_bytes: generate nr_bytes of random bytes suitable for use as key data.");
271         tfc_say("    -R also supports these aliases specified instead of nr_bytes:");
272         tfc_say("    cbs: output fixed maximum crypt block size (%u bytes),", TFC_U(TF_BLOCK_SIZE));
273         tfc_say("    ks: output fixed maximum crypt key size (%u bytes)", TFC_U(TF_KEY_SIZE));
274         tfc_say("    xks: output fixed maximum crypt XTS key size (%u bytes)", TFC_U(TF_KEY_SIZE*2));
275         tfc_say("    iobs: output %s builtin block size TFC_BLKSIZE (%u bytes),", progname, TFC_U(TFC_BLKSIZE));
276         tfc_say("    if nr_bytes is not a valid number or alias, this string will be");
277         tfc_say("    used to attempt to open it as file, and examine it's size.");
278         tfc_say("    Then this examined size will be set as nr_bytes to output.");
279         tfc_say("  -Z nr_bytes: like -R, but emit zero stream instead of random.");
280         tfc_say("  -D MACBITS: specify bit width of a MAC signature.");
281         tfc_say("  -U key/pwd/<file>: read Skein MAC key from file.");
282         tfc_say("    key: use primary encryption rawkey as a MAC key.");
283         tfc_say("    pwd: ask for password string that will be used as MAC key.");
284         tfc_say("  -S MAC: append MAC signature to end of file:");
285         tfc_say("    MAC: embed MAC signature into file itself at the end,");
286         tfc_say("    <file>: write a detached MAC signature into separate <file>,");
287         tfc_say("    -: write a detached MAC signature to stdout.");
288         tfc_say("    useful only with variable length files! For block devices,");
289         tfc_say("    specify a separate file name to save signature to: -S file.");
290         tfc_say("  -A: format raw binary data, like MAC signature or Skein hash, in base64.");
291         tfc_say("  -W: output pure binary data, and disable any strings addition in Skein.");
292         tfc_say("  -H: output small hexdump (hex string and ASCII printable characters).");
293         tfc_say("  -M MAC: verify attached MAC signature when decrypting a file:");
294         tfc_say("    MAC: embed MAC signature into file itself at the end,");
295         tfc_say("    <file>: write a detached MAC signature into separate <file>,");
296         tfc_say("    -: read a detached MAC signature from stdin,");
297         tfc_say("    drop: do not verify attached MAC, if any, and drop it from output.");
298         tfc_say("  -m: just verify MAC provided with -M. Do not write output file.");
299         tfc_say("  -u: almost same as -m, but turns on MAC pre-test mode, when verified");
300         tfc_say("    signature enables writing output file. It is useful when decrypting small texts.");
301         tfc_say("    The source must be a seekable file, otherwise this mode will be disabled.");
302         tfc_say("    In this mode, decryption is done twice and verification done once.");
303         tfc_say("    Both -m and -u options must be specified after -M.");
304         tfc_say("  -E how: how to behave on I/O errors (both src or dst):");
305         tfc_say("    exit: print error if not quiet, then exit,");
306         tfc_say("    cont: print error if not quiet, then continue,");
307         tfc_say("      no action to pad missing data is attempted.");
308         tfc_say("      may be dangerous when working with block devices.");
309         tfc_say("    sync: print error if not quiet, then continue,");
310         tfc_say("      pad missing data block with zeroes.");
311         tfc_say("    lsync: same as sync, but does not use SEEK_SET logic,");
312         tfc_say("      lsync uses only relative seek operations, and does not prequery");
313         tfc_say("      the current file position for exact offsets, which maybe unsafe.");
314         tfc_say("      For this reason, it is HIGHLY recommended to use sync instead!");
315         tfc_say("      Note that both sync and lsync work only with read errors!");
316         tfc_say("  default error action is exit with printing status if not quiet.");
317         tfc_say("  -E xall: turn on error actions above for all errors, not just EIO errors.");
318         tfc_say("  -E xseek: ignore positioning and other seek related errors.");
319         tfc_say("    Multiple -E specifiers may be given in separate options.");
320         tfc_say("  -o logfile: redirect all messages to logfile instead of stderr.");
321         tfc_say("  -O opts: set options (comma separated list):");
322         tfc_say("    ro: open all files only for reading, even those intended for writing,");
323         tfc_say("    sync: request a synchronous I/O for a output,");
324         tfc_say("    fsync: on each write() call a corresponding fsync(fd),");
325         tfc_say("    trunc: open(O_WRONLY) will truncate output file to zero size.");
326         tfc_say("    append: open(O_APPEND) will append data to output file.");
327         tfc_say("    pad: pad incomplete (l.t. %u bytes) block with zeroes.", TFC_U(TF_BLOCK_SIZE));
328         tfc_say("    xtime: copy timestamps from source to destination files.");
329         tfc_say("    gibsize: use SI units of size: 1k = 1000. Applies only to size prefixes.");
330         tfc_say("    Computers convention is to use 1024, whereas SI/hdd measure in 1000.");
331         tfc_say("    plainstats: force status line to be plain: no fancy dynamic stuff.");
332         tfc_say("    Dynamic line works well only on VT100 compatible ttys, and");
333         tfc_say("    when the whole status line width is smaller than tty width.");
334         tfc_say("    statless: emit less information in status line (only processed data).");
335         tfc_say("    norepeat: do not ask for any possible password confirmations.");
336         tfc_say("    showsecrets: show passwords in plaintext instead of masking them.");
337         tfc_say("    finished: add \"finished\" word before status line when work is finished.");
338         tfc_say("    pid: show %s's process id near it's name in error messages, logs etc.", progname);
339         tfc_say("    readloops=val: when seekable source ends, reading continues from it's beginning again.");
340         tfc_say("    prompt=str: set main password prompts to this string.");
341         tfc_say("    macprompt=str: set MAC password prompts to this string.");
342         tfc_say("    shorthex: with -H, do not print printable characters, dump only hex string.");
343         tfc_say("    logfile: (same as -o) redirect all messages to logfile instead of stderr.");
344         tfc_say("    iobs=val: set IO block size value. Must not exceed %u bytes.", TFC_U(TFC_BLKSIZE));
345         tfc_say("    nobuf: disable IO buffering, write as soon as data received (only for stream ciphers!)");
346         tfc_say("    xtsblocks=val: use these nr of TF blocks per XTS block. Default is %u.", TFC_U(TFC_XTSBLOCKS));
347         tfc_say("    iseek=val: seek source file/device by these val bytes.");
348         tfc_say("    Initial counter is adjusted automatically.");
349         tfc_say("    ixseek=val: rawseek source file/device by these val bytes.");
350         tfc_say("    Do not adjust initial counter automatically.");
351         tfc_say("    ictr=val: Increment initial counter by this val blocks.");
352         tfc_say("    The size of each block is %u bytes.", TFC_U(TF_BLOCK_SIZE));
353         tfc_say("    ictr option is valid only for CTR and CTR like modes.");
354         tfc_say("    ixctr=val: Increment initial counter by this val bytes.");
355         tfc_say("    Internally this number is translated into number of %u byte blocks.", TFC_U(TF_BLOCK_SIZE));
356         tfc_say("    oseek=val: seek destination file/device by these val bytes.");
357         tfc_say("    ioseek=val: seek both source and destination.");
358         tfc_say("    ioseek is equal to iseek and oseek.");
359         tfc_say("    count=val: process only these val bytes, both input and output.");
360         tfc_say("    ftrunc=val: truncate output file to these val bytes before closing it.");
361         tfc_say("    ftrunc=tail: truncate output's tail, leaving only processed data.");
362         tfc_say("    xkey=val: take only val bytes from user keyfile.");
363         tfc_say("    okey=val: seek the key before reading it (usually a device).");
364         tfc_say("    xctr=val: specify size in bytes of initial counter prepended or read.");
365         tfc_say("    fullkey: occupy tweak space by key space, extending key size by 256 bits.");
366         tfc_say("  -P: plain IO mode: disable encryption/decryption code at all.");
367         tfc_say("\n");
368         tfc_say("Default is to ask for password, then encrypt stdin into stdout.");
369         tfc_say("Some cmdline parameters may be mutually exclusive, or they can");
370         tfc_say("generate errors or behave abnormally. Please understand that some");
371         tfc_say("dumb mode error checking may be not performed well, and please read");
372         tfc_say("the README included within package and this help text carefully.");
373         tfc_say("\n");
374
375         xexit(1);
376 }