-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibddr_crypt.c
1612 lines (1526 loc) · 48.7 KB
/
libddr_crypt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** libddr_crypt.c
*
* plugin for dd_rescue, de/encrypting during copying ...
*
* (c) Kurt Garloff <[email protected]>, 2014
* License: GNU GPLv2 or v3
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include "ddr_plugin.h"
#include "ddr_ctrl.h"
#include "find_nonzero.h"
#include "archdep.h"
#include "aes.h"
#include "hash.h"
#include "pbkdf2.h"
#include "pbkdf_ossl.h"
#include "sha256.h"
#include "md5.h"
#include "secmem.h"
#include "checksum_file.h"
#include "random.h"
#include "aes_c.h"
#include "aes_ossl.h"
#ifdef HAVE_AESNI
#include "aesni.h"
#endif
#ifdef HAVE_AES_ARM64
#include "aes_arm64.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <endian.h>
#include <signal.h>
#ifdef HAVE_SYS_XATTR_H
#include <sys/xattr.h>
#define HAVE_XATTR 1
#elif defined(HAVE_ATTR_XATTR_H)
#include <attr/xattr.h>
#define HAVE_XATTR 1
#endif
#if __WORDSIZE == 64
#define LL "l"
#define ATOL atol
#elif __WORDSIZE == 32
#define LL "ll"
#define ATOL atoll
#else
#error __WORDSIZE unknown
#endif
#if (defined(__x86_64__) || defined(__i386__)) && !defined(NO_SSE42) && !defined(NO_AVX2) && !defined(NO_RDRAND)
# define MAY_AESNI 1
//char have_aesni;
#endif
#define FPLOG_(seq, lvl, fmt, args...) \
plug_log(ddr_plug.logger, seq, stderr, lvl, fmt, ##args)
#define FPLOG(lvl, fmt, args...) \
FPLOG_(state->seq, lvl, fmt, ##args)
/* fwd decl */
extern ddr_plugin_t ddr_plug;
typedef struct _crypt_state {
ciph_desc_t *alg, *engine;
char enc, debug, kgen, igen, sgen, keyf, ivf, saltf;
char kset, iset, pset, sset;
char finfirst, rev, bench, skiphole;
clock_t cpu;
int seq, pad;
int inbuf, pbkdf2r;
sec_fields *sec;
/*const*/ opt_t *opts;
char *pfnm, *sfnm;
size_t saltlen;
loff_t lastpos;
loff_t processed;
#if 1 //def HAVE_XATTR
char* salt_xattr_name;
char* key_xattr_name;
char* iv_xattr_name;
char sxattr, sxfallback;
char kxattr, kxfallback;
char ixattr, ixfallback;
#endif
char weakrnd, opbkdf, outkeyiv, ctrbug198;
char opbkdf11, nosalthdr, ilnchg, islast;
unsigned char *zerobuf;
unsigned int zerosize;
loff_t hole;
} crypt_state;
/* aes modules rely on avail of global crypto symbol to point to sec_fields ... */
sec_fields *crypto;
const char *crypt_help = "The crypt plugin for dd_rescue de/encrypts data copied on the fly.\n"
" It only supports aligned blocks (with CTR) and no holes (sparse writing).\n"
" Parameters: [alg[o[rithm]]=]ALG:enc[rypt]:dec[rypt]:engine=STR:pad=STR\n"
"\t:keyhex=HEX:keyfd=[x]INT[@INT@INT]:keyfile=NAME[@INT@INT]:keygen:keysfile\n"
"\t:ivhex=HEX:ivfd=[x]INT[@INT@INT]:ivfile=NAME[@INT@INT]:ivgen:ivsfile\n"
#ifdef HAVE_XATTR
"\t:keyxattr[=xattr_name]:kxfallback:ivxattr[=xattr_name]:ixfallback\n"
#endif
"\t:pass=STR:passfd=[x]INT[@INT@INT]:passfile=NAME[@INT@INT]\n"
"\t:salt=STR:salthex=HEX:saltfd=[x]INT[@INT@INT]:saltfile=NAME[@INT@INT]\n"
"\t:saltlen=INT:saltgen:saltsfile"
#ifdef HAVE_XATTR
":saltxattr[=xattr_name]:sxfallback"
#endif
"\n\t:pbkdf2[=INT]:opbkdf[11]:debug:bench[mark]:skiphole:weakrnd:outkeyiv\n"
"\t:nosalthdr:ctrbug198\n"
" Use algorithm=help to get a list of supported crypt algorithms\n";
#ifndef MIN
# define MIN(a,b) ((a)<(b)? (a): (b))
#endif
#ifndef MAX
# define MAX(a,b) ((a)>(b)? (a): (b))
#endif
int parse_hex(unsigned char*, const char*, uint maxlen);
int parse_hex_u32(unsigned int*, const char*, uint maxlen);
int read_fd(unsigned char*, const char*, uint maxlen, const char*);
int read_file(unsigned char*, const char*, uint maxlen);
char* mystrncpy(unsigned char*, const char*, uint maxlen);
int stripcrlf(char* str, uint maxlen);
void whiteout(char* str, char quiet);
int set_flag(char* flg, const char* msg)
{
if (*flg) {
FPLOG_(-1, FATAL, "%s already set\n", msg);
return -1;
}
*flg = 1;
return 0;
}
int set_alg(crypt_state* state, const char* algnm)
{
ciph_desc_t *alg = findalg(state->engine, algnm, 0);
if (state->alg) {
if (alg)
FPLOG(FATAL, "alg already set to, can't override with %s\n",
state->alg->name, algnm);
else
FPLOG(FATAL, "Don't understand option (alg?) %s\n", algnm);
return -1;
}
if (!strcasecmp(algnm, "help")) {
FPLOG(INFO, "Crypto algorithms:", NULL);
ciph_desc_t *alg;
for (alg = state->engine; alg->name != NULL; ++alg)
FPLOG(NOHDR, " %s", alg->name);
FPLOG(NOHDR, "\n", NULL);
return -1;
} else {
if (!alg) {
FPLOG(FATAL, "Unknown parameter/algorithm %s\n", algnm);
return -1;
}
state->alg = alg;
}
return 0;
}
#define BLKSZ (state->alg? state->alg->blocksize: 16UL)
int crypt_plug_init(void **stat, char* param, int seq, const opt_t *opt)
{
int err = 0;
crypt_state *state = (crypt_state*)malloc(sizeof(crypt_state));
*stat = (void*)state;
memset(state, 0, sizeof(crypt_state));
state->seq = seq;
state->opts = (opt_t*)opt;
state->enc = -1;
state->sec = secmem_init();
crypto = state->sec;
assert(state->sec);
state->pad = PAD_ALWAYS;
state->saltlen = -1;
#if defined(CC_FLAGS_AES) && (defined(__x86_64__) || defined(__i386__))
if (have_aesni) {
#ifndef NO_AVX2
if (have_avx2) {
state->engine = VAESNI_Methods;
if (opt->verbose)
FPLOG(INFO, "Default to use AVX2 AESNI crypto extensions\n");
} else {
#else
do {
#endif
state->engine = SAESNI_Methods;
if (opt->verbose)
FPLOG(INFO, "Default to use Std AESNI crypto extensions\n");
}
#ifdef NO_AVX2
while(0);
#endif
} else {
#elif defined(HAVE_AES_ARM64)
if (have_arm8crypto) {
state->engine = AES_ARM8_Methods;
if (opt->verbose)
FPLOG(INFO, "Default to use ARMv8 crypto extensions\n");
} else {
#endif
if (opt->verbose)
FPLOG(INFO, "Default to use C crypto implementation\n");
state->engine = AES_C_Methods;
#if defined(HAVE_AES_ARM64) || (defined(CC_FLAGS_AES) && (defined(__x86_64__) || defined(__i386__)))
}
#endif
while (param) {
char* next = strchr(param, ':');
if (next)
*next++ = 0;
if (!*param) {
param = next;
continue;
}
if (!strcasecmp(param, "help")) {
FPLOG(INFO, "%s", crypt_help);
return -1;
} else if (!strcasecmp(param, "debug"))
state->debug = 1;
else if (!strcmp(param, "encrypt") || !strcmp(param, "enc"))
state->enc = 1;
else if (!strcmp(param, "decrypt") || !strcmp(param, "dec"))
state->enc = 0;
else if (!memcmp(param, "engine=", 7)) {
if (!strcasecmp(param+7, "aes_c"))
state->engine = AES_C_Methods;
#ifdef HAVE_AES_ARM64
else if (!strcasecmp(param+7, "aesarm64"))
state->engine = AES_ARM8_Methods;
#endif
#ifdef HAVE_AESNI
#ifndef NO_AVX2
else if (!strcasecmp(param+7, "aesni") && have_avx2)
state->engine = VAESNI_Methods;
else if (!strcasecmp(param+7, "vaesni"))
state->engine = VAESNI_Methods;
#endif
else if (!strcasecmp(param+7, "saesni"))
state->engine = SAESNI_Methods;
else if (!strcasecmp(param+7, "aesni"))
state->engine = SAESNI_Methods;
#endif
#ifdef HAVE_LIBCRYPTO
else if (!strcasecmp(param+7, "openssl"))
state->engine = AES_OSSL_Methods;
#endif
else {
FPLOG(FATAL, "Engine %s unknown, specify aesni/aesarm64/aes_c/openssl\n",
param+7);
--err;
param = next;
continue;
}
}
else if (!memcmp(param, "algorithm=", 10))
err += set_alg(state, param+10);
else if (!memcmp(param, "algo=", 5))
err += set_alg(state, param+5);
else if (!memcmp(param, "alg=", 4))
err += set_alg(state, param+4);
else if (!memcmp(param, "pad=", 4)) {
if (!strcasecmp(param+4, "zero"))
state->pad = PAD_ZERO;
else if (!strcasecmp(param+4, "always"))
state->pad = PAD_ALWAYS;
else if (!strcasecmp(param+4, "asneeded"))
state->pad = PAD_ASNEEDED;
else {
FPLOG(FATAL, "Illegal padding %s: Specify zero/always/asneeded!\n",
param+4);
--err;
param = next;
continue;
}
}
else if (!memcmp(param, "keyhex=", 7)) {
//err += parse_hex_u32((unsigned int*)state->sec->userkey1, param+7, state->alg->keylen/(8*sizeof(int)));
err += parse_hex(state->sec->userkey1, param+7, state->alg->keylen/8);
whiteout(param+7, opt->quiet);
err += set_flag(&state->kset, "key");
} else if (!memcmp(param, "keyfd=", 6)) {
err += read_fd(state->sec->userkey1, param+6, 32, "key");
err += set_flag(&state->kset, "key");
} else if (!memcmp(param, "keyfile=", 8)) {
err += read_file(state->sec->userkey1, param+8, state->alg->keylen/8);
err += set_flag(&state->kset, "key");
} else if (!strcmp(param, "keygen"))
state->kgen = 1;
else if (!strcmp(param, "keysfile"))
state->keyf = 1;
else if (!memcmp(param, "ivhex=", 6)) {
//err += parse_hex_u32((unsigned int*)state->sec->nonce1, param+6, BLKSZ/sizeof(int));
err += parse_hex(state->sec->nonce1, param+6, BLKSZ);
whiteout(param+6, opt->quiet);
err += set_flag(&state->iset, "IV");
} else if (!memcmp(param, "ivfd=", 5)) {
err += read_fd(state->sec->nonce1, param+5, BLKSZ, "iv");
err += set_flag(&state->iset, "IV");
} else if (!memcmp(param, "ivfile=", 7)) {
err += read_file(state->sec->nonce1, param+7, BLKSZ);
err += set_flag(&state->iset, "IV");
} else if (!strcmp(param, "ivgen"))
state->igen = 1;
else if (!strcmp(param, "ivsfile"))
state->ivf = 1;
else if (!memcmp(param, "pass=", 5)) {
mystrncpy(state->sec->passphr, param+5, 128);
whiteout(param+5, opt->quiet);
err += set_flag(&state->pset, "password");
#if 0
} else if (!memcmp(param, "passhex=", 8)) {
/* FIXME: This will error out on shorter passphrases! */
err += parse_hex(state->sec->passphr, param+8, 128);
err += set_flag(&state->pset, "password");
#endif
} else if (!memcmp(param, "passfd=", 7)) {
err += read_fd(state->sec->passphr, param+7, 128, "passphrase");
stripcrlf((char*)state->sec->passphr, 128);
err += set_flag(&state->pset, "password");
} else if (!memcmp(param, "passfile=", 9)) {
if (!state->pset) {
err += read_file(state->sec->passphr, param+9, 128);
stripcrlf((char*)state->sec->passphr, 128);
err += set_flag(&state->pset, "password");
} else /* Later: save if pset */
state->pfnm = param+9;
} else if (!memcmp(param, "salt=", 5)) {
//mystrncpy(state->sec->salt, param+5, 64);
gensalt(state->sec->salt, 8, param+5, NULL, 0);
whiteout(param+5, opt->quiet);
err += set_flag(&state->sset, "salt");
} else if (!memcmp(param, "salthex=", 8)) {
err += parse_hex(state->sec->salt, param+8, 8);
whiteout(param+8, opt->quiet);
err += set_flag(&state->sset, "salt");
} else if (!memcmp(param, "saltfd=", 7)) {
err += read_fd(state->sec->salt, param+7, 8, "salt");
err += set_flag(&state->sset, "salt");
} else if (!memcmp(param, "saltfile=", 9)) {
if (!state->sset && !state->sgen) {
err += read_file(state->sec->salt, param+9, 8);
err += set_flag(&state->sset, "salt");
} else /* sset is set, so save later */
state->sfnm = param+9;
} else if (!strcmp(param, "saltsfile"))
state->saltf = 1;
else if (!memcmp(param, "saltlen=", 8))
state->saltlen = ATOL(param+8);
else if (!strcmp(param, "saltgen"))
state->sgen = 1;
#ifdef HAVE_XATTR
else if (!strcmp(param, "saltxattr"))
err += set_flag(&state->sxattr, "saltxattr");
else if (!memcmp(param, "saltxattr=", 10)) {
state->salt_xattr_name = strdup(param+10);
err += set_flag(&state->sxattr, "saltxattr");
} else if (!strcmp(param, "sxfallback") || !strcmp(param, "sxfallb"))
err += set_flag(&state->sxfallback, "sxfallback");
else if (!strcmp(param, "keyxattr"))
err += set_flag(&state->kxattr, "keyxattr");
else if (!memcmp(param, "keyxattr=", 9)) {
state->key_xattr_name = strdup(param+9);
err += set_flag(&state->kxattr, "keyxattr");
} else if (!strcmp(param, "kxfallback") || !strcmp(param, "kxfallb"))
err += set_flag(&state->kxfallback, "kxfallback");
else if (!strcmp(param, "ivxattr"))
err += set_flag(&state->ixattr, "ivxattr");
else if (!memcmp(param, "ivxattr=", 8)) {
state->iv_xattr_name = strdup(param+8);
err += set_flag(&state->ixattr, "ivxattr");
} else if (!strcmp(param, "ixfallback") || !strcmp(param, "ixfallb"))
err += set_flag(&state->ixfallback, "ixfallback");
#endif
else if (!memcmp(param, "bench", 5))
state->bench = 1;
else if (!memcmp(param, "pbkdf2=", 7))
state->pbkdf2r = atol(param+7);
else if (!strcmp(param, "pbkdf2"))
state->pbkdf2r = 17000;
else if (!strcmp(param, "opbkdf"))
state->opbkdf = 1;
else if (!strcmp(param, "opbkdf11")) {
state->opbkdf = 1; state->opbkdf11 = 1;
} else if (!strcmp(param, "skiphole"))
state->skiphole = 1;
else if (!strcmp(param, "nosalthdr"))
state->nosalthdr = 1;
else if (!strcmp(param, "weakrnd"))
state->weakrnd = 1;
else if (!strcmp(param, "outkeyiv"))
state->outkeyiv = 1;
else if (!strcmp(param, "ctrbug198"))
state->ctrbug198 = 1;
/* Hmmm, ok, let's support algname without alg= */
else {
err += set_alg(state, param);
}
param = next;
}
/* Now process params ... */
/* 0th: encryption or decryption? */
if (state->enc == (char)-1) {
FPLOG(FATAL, "Need to specify enc[rypt] or dec[rypt]\n", NULL);
return -1;
}
/* 1st: Set engine: Default: aesni/aes_c: Done */
/* 2nd: Set alg: Already done if set explicitly */
if (!err && !state->alg) {
state->alg = findalg(state->engine, "AES192-CTR", 0);
FPLOG(INFO, "Using default algorithm AES192-CTR\n", NULL);
}
if (!state->alg)
return -1;
/* Actually, we can support seeks/reverse copies with CTR and ECB */
ddr_plug.needs_align = state->alg->blocksize;
ddr_plug.supports_seek = state->alg->stream->seek_blk;
/* 3rd: Padding: Already done */
/* 4th: pass: done */
/* 5th: salt (later: if not given: derive from outnm) */
/* 6th: key (later: defaults to pbkdf2(pass, salt) */
if (state->kgen && !state->enc) {
FPLOG(FATAL, "Decrypting with a generated key does not make sense\n", NULL);
return -1;
}
if (!state->pset && !state->kset && !state->keyf && !state->kgen && !state->kxattr) {
FPLOG(FATAL, "Need to set key or password\n", NULL);
--err;
}
if (state->kset && state->kgen) {
FPLOG(FATAL, "Can't set and generate a key\n", NULL);
--err;
}
state->finfirst = state->rev = opt->reverse;
/* 7th: iv (later: defaults to generation from salt) */
return err;
}
int crypt_plug_release(void **stat)
{
if (!stat || !*stat)
return -1;
crypt_state *state = (crypt_state*)*stat;
if (state->sec)
secmem_release(state->sec);
else
return -2;
#ifdef HAVE_XATTR
if (state->iv_xattr_name)
free(state->iv_xattr_name);
if (state->key_xattr_name)
free(state->key_xattr_name);
if (state->salt_xattr_name)
free(state->salt_xattr_name);
#endif
if (state->zerobuf)
free(state->zerobuf);
free(*stat);
return 0;
}
int hexchar(const char v)
{
if (isdigit(v))
return v - '0';
if (v >= 'a' && v <= 'f')
return v - 'a' + 10;
if (v >= 'A' && v <= 'F')
return v - 'A' + 10;
return -1;
}
int hexbyte(const char s[2])
{
int i = hexchar(s[0]);
if (i < 0)
return i;
int j = hexchar(s[1]);
if (j < 0)
return j;
return (i << 4) | j;
}
int parse_hex(unsigned char* res, const char* str, uint maxlen)
{
if (str[0] == '0' && str[1] == 'x')
str += 2;
uint i;
for (i = 0; i < maxlen; ++i) {
int v = hexbyte(str+i*2);
if (v < 0)
break;
res[i] = v;
}
if (i < maxlen) {
memset(res+i, 0, maxlen-i);
FPLOG_(-1, FATAL, "Too short key/IV (%i/%i) bytes\n", i, maxlen);
return -1;
}
return 0;
}
int parse_hex_u32(unsigned int* res, const char* str, uint maxlen)
{
if (str[0] == '0' && str[1] == 'x')
str += 2;
uint i;
for (i = 0; i < maxlen; ++i) {
int v3 = hexbyte(str+i*8);
int v2 = hexbyte(str+i*8+2);
int v1 = hexbyte(str+i*8+4);
int v0 = hexbyte(str+i*8+6);
if (v3 < 0 || v2 < 0 || v1 < 0 || v0 < 0)
break;
res[i] = v3 << 24 | v2 << 16 | v1 << 8 | v0;
}
if (i < maxlen) {
memset(res+i, 0, 4*(maxlen-i));
FPLOG_(-1, FATAL, "Too short key/IV (%i/%i) u32s\n", i, maxlen);
return -1;
}
return 0;
}
char* hexout(char* buf, const unsigned char* val, unsigned int ln)
{
int i;
for (i = 0; i < ln; ++i)
sprintf(buf+2*i, "%02x", val[i]);
return buf;
}
char* hexout_u32(char* buf, const unsigned int* val, unsigned int ln)
{
int i;
for (i = 0; i < ln; ++i)
sprintf(buf+8*i, "%08x", val[i]);
return buf;
}
void get_offs_len(const char* str, off_t *off, size_t *len)
{
const char* ptr = strrchr(str, '@');
const char* pt2 = ptr? strrchr(ptr, '@'): NULL;
*off = 0;
*len = 0;
if (!pt2 && !ptr)
return;
if (pt2) {
*off = atol(ptr+1);
*len = atol(pt2+1);
return;
}
*len = atol(ptr+1);
}
int read_fd(unsigned char* res, const char* param, uint maxlen, const char* what)
{
char ibuf[2*maxlen+3];
int hex = 0;
if (*param == 'x') {
++param;
++hex;
}
int fd = atol(param);
int ln = -1;
if (fd == 0 && isatty(fd)) {
FPLOG_(-1, INPUT, "Enter %s: ", what);
if (hex) {
ln = hidden_input(fd, ibuf, 2*maxlen+2, 1);
ibuf[ln] = 0;
ln = parse_hex(res, ibuf, maxlen);
} else {
ln = hidden_input(fd, (char*)res, maxlen, 1);
}
} else {
off_t off = 0;
size_t sz = 0;
get_offs_len(param, &off, &sz);
if (hex) {
ln = pread(fd, ibuf, MIN(2*maxlen+2, (sz? sz: 4096)), off);
if (ln == -1) {
if (errno == ESPIPE && off == 0)
ln = read(fd, ibuf, MIN(2*maxlen+2, (sz? sz: 4096)));
if (ln < 0) {
FPLOG_(-1, FATAL, "can not read secret from fd %i!\n", fd);
return 1;
}
}
ibuf[ln] = 0;
ln = parse_hex(res, ibuf, maxlen);
} else {
ln = pread(fd, res, MIN(maxlen, (sz? sz: 4096)), off);
if (ln == -1) {
if (errno == ESPIPE && off == 0)
ln = read(fd, res, MIN(2*maxlen+2, (sz? sz: 4096)));
if (ln < 0) {
FPLOG_(-1, FATAL, "can not read secret from fd %i!\n", fd);
return 1;
}
}
if (ln < (int)maxlen)
memset(res+ln, 0, maxlen-ln);
}
}
if (ln <= 0)
FPLOG_(-1, FATAL, "%s empty!\n", what);
return ln<=0? 1: 0;
}
int read_file(unsigned char* res, const char* param, uint maxlen)
{
off_t off = 0;
size_t sz = 0;
get_offs_len(param, &off, &sz);
int fd = open(param, O_RDONLY);
/* TODO: Handle a filename of "-" as stdin */
if (fd < 0) {
FPLOG_(-1, FATAL, "Can't open %s for reading: %s\n",
param, strerror(errno));
return -1;
}
int ln = pread(fd, res, MIN(maxlen, (sz? sz: 4096)), off);
if (ln < (int)maxlen)
memset(res+ln, 0, maxlen-ln);
return ln>0? 0: -1;
}
int write_file(const unsigned char *data, const char* param, uint maxlen, int mode)
{
off_t off = 0;
size_t sz = 0;
get_offs_len(param, &off, &sz);
if (!sz)
sz = maxlen;
int fd = open(param, O_RDWR|O_CREAT, mode);
/* TODO: Handle a filename of "-" as stdout */
if (fd < 0) {
FPLOG_(-1, FATAL, "Can't open %s for writing: %s\n",
param, strerror(errno));
return -1;
}
off_t o = lseek(fd, off, SEEK_SET);
assert(o == off);
int ln = write(fd, data, sz);
//assert(ln == sz);
return ln==sz? 0: -1;
}
char* mystrncpy(unsigned char* res, const char* param, uint maxlen)
{
size_t ln = strlen(param);
memcpy(res, param, MIN(ln+1, maxlen));
if (ln+1 < maxlen)
memset(res+ln+1, 0, maxlen-ln-1);
return (char*)res;
}
int stripcrlf(char* str, uint maxlen)
{
/* Note: We may read beyond str -- but we have zeros in secmem, so it's harmless */
size_t ln = strlen(str);
if (ln >= maxlen)
return 0;
if (ln+1 < maxlen)
memset(str+ln+1, 0, maxlen-ln-1);
size_t oln = ln;
/* This removes a trailing \n (Unix), \r (Mac) or \r\n (DOS). */
if (str[ln-1] == '\n')
str[--ln] = 0;
if (str[ln-1] == '\r')
str[--ln] = 0;
return (oln == ln? 0: 1);
}
void whiteout(char* str, char quiet)
{
#ifndef NO_WRITE_ARGV
int ln = strlen(str);
assert(ln <= 512 && ln >= 0);
memset(str, 0, ln);
if (ln >= 1)
str[0] = 'X';
#endif
if (!quiet)
FPLOG_(-1, WARN, "Don't specify sensitive data on the command line!\n", NULL);
}
const char* mybasenm(const char* nm)
{
const char* ptr = strrchr(nm, '/'); // FIXME: Unix
if (ptr)
return ptr+1;
else
return nm;
}
/* Constructs name for KEYS and IVS files (in allocated mem) */
char *keyfnm(const char* base, const char *encnm)
{
char* ptr = strrchr(encnm, '/'); // FIXME: Unix
if (!ptr)
return strdup(base);
else {
char* kfnm = malloc(ptr-encnm + 2 + strlen(base));
assert(kfnm);
memcpy(kfnm, encnm, ptr-encnm+1);
*(kfnm+(ptr-encnm+1)) = 0;
strcat(kfnm, base);
return kfnm;
}
}
char* chartohex(crypt_state *state, const unsigned char* key, const int bytes)
{
assert(bytes < 72);
hexout(state->sec->charbuf1, key, bytes);
return state->sec->charbuf1;
}
char* chartohex_u32(crypt_state *state, const unsigned int* key, const int words)
{
assert(words < 18);
hexout_u32(state->sec->charbuf1, key, words);
return state->sec->charbuf1;
}
int write_keyfile(crypt_state *state, const char* base, const char* name, const unsigned char* key, const int bytes, int acc, char confnm, char isu32)
{
char *fnm;
if (confnm)
fnm = keyfnm(base, name);
else
fnm = strdup(base);
int err = isu32?
upd_chks(fnm, name, chartohex_u32(state, (unsigned int*)key, bytes/sizeof(int)), acc) :
upd_chks(fnm, name, chartohex(state, key, bytes), acc);
free(fnm);
if (err)
FPLOG(FATAL, "Could not write key/IV/pass/salt file\n", NULL);
return err;
}
#ifdef HAVE_XATTR
int get_xattr(crypt_state *state, const char* atrnm,
unsigned char* data, int dlen,
char fb, char* fbf, char* flag)
{
const char* name = state->opts->iname;
int err = 0;
if (state->enc)
name = state->opts->oname;
if (state->debug)
FPLOG(DEBUG, "Try to read xattr %s from %s file %s\n",
atrnm, (state->enc? "output": "input"), name);
/* Longest is 128byte hex for SHA512 (8x64byte numbers -> 8x16 digits) */
ssize_t itln = getxattr(name, atrnm, state->sec->charbuf1, 128);
if (itln <= 0) {
if (!fb)
FPLOG(WARN, "Could not read xattr %s of %s\n", atrnm, name);
else {
if (state->debug)
FPLOG(DEBUG, "Fall back to file\n");
if (fbf)
*fbf = 1;
}
return -ENOENT;
} else if (itln != 2*dlen) {
FPLOG(WARN, "Wrong length of xattr %s (expected %i hex chars, got %i) of %s\n", atrnm, 2*dlen, itln, name);
if (fb && fbf)
*fbf = 1;
return -ENOENT;
} else {
err += parse_hex(data, state->sec->charbuf1, dlen);
err += set_flag(flag, atrnm);
}
return err;
}
int set_xattr(crypt_state* state, const char* atrnm,
unsigned char *data, int dlen,
char fb, char *fbf)
{
const char* name = state->opts->oname;
if (!state->enc) {
FPLOG(WARN, "Not setting xattr %s for %s when not encrypting!\n",
atrnm, name);
return -1;
}
/* FIXME: Use same logic as in hash plugin */
//if (state->ochg && !state->ichg) {
// name = state->opts->iname;
//} else if (state->ochg) {
// FPLOG(WARN, "Can't write xattr in the middle of plugin chain (%s)\n",
// state->fname);
// return -ENOENT;
//}
if (state->debug)
FPLOG(INFO, "Try to write xattr %s to output file %s\n", atrnm, name);
if (setxattr(name, atrnm, chartohex(state, data, dlen), 2*dlen, 0)) {
if (!fb)
FPLOG(FATAL, "Failed writing xattr %s for %s: %s\n",
atrnm, name, strerror(errno));
else {
if (state->debug)
FPLOG(DEBUG, "Fallback to file\n");
if (fbf)
*fbf = 1;
}
return -1;
}
return 0;
}
/* TODO: Salt: Shouldn't we store and retrieve the kdf as well?
* user.pbkdf=pbkdf2=NR or user.pbkdf=opbkdf
*/
int get_salt_xattr(crypt_state* state)
{
int r = get_xattr(state, state->salt_xattr_name,
state->sec->salt, 8,
state->sxfallback, &state->saltf, &state->sset);
if (!r) {
const char* name = state->enc? state->opts->oname: state->opts->iname;
ssize_t itln = getxattr(name, "user.pbkdf", state->sec->charbuf1, 128);
if (itln <= 0)
return r;
int rnd = 0;
if (sscanf(state->sec->charbuf1, "pbkdf2=%i", &rnd) == 1) {
if (rnd != state->pbkdf2r && state->opts->verbose)
FPLOG(INFO, "Setting pbkdf2 KDF with %i rounds\n", rnd);
state->pbkdf2r = rnd; state->opbkdf = 0;
} else if (sscanf(state->sec->charbuf1, "opbkdf11") == 0) {
if (!state->opbkdf && state->opts->verbose)
FPLOG(INFO, "Setting opbkdf11\n");
state->opbkdf = 1; state->opbkdf11 = 1; state->pbkdf2r = 0;
} else if (sscanf(state->sec->charbuf1, "opbkdf") == 0) {
if (!state->opbkdf && state->opts->verbose)
FPLOG(INFO, "Setting opbkdf\n");
state->opbkdf = 1; state->pbkdf2r = 0;
} else
FPLOG(WARN, "Unknown pbkdf value %s\n", state->sec->charbuf1);
}
return r;
}
int set_salt_xattr(crypt_state* state)
{
int r = set_xattr(state, state->salt_xattr_name,
state->sec->salt, 8, state->sxfallback, &state->saltf);
if (!r && state->enc) {
const char* name = state->opts->oname;
char buf[32];
if (state->pbkdf2r)
snprintf(buf, 32, "pbkdf2=%i", state->pbkdf2r);
else if (state->opbkdf11)
sprintf(buf, "opbkdf11");
else if (state->opbkdf)
sprintf(buf, "opbkdf");
else
abort();
if (setxattr(name, "user.pbkdf", buf, strlen(buf)+1, 0) && !state->opts->quiet)
FPLOG(WARN, "Huh? Stored salt but could not store pbkdf to xattr\n");
}
return r;
}
static inline int get_key_xattr(crypt_state* state)
{
return get_xattr(state, state->key_xattr_name,
state->sec->userkey1, state->alg->keylen/8,
state->kxfallback, &state->keyf, &state->kset);
}
static inline int set_key_xattr(crypt_state *state)
{
int r = set_xattr(state, state->key_xattr_name,
state->sec->userkey1, state->alg->keylen/8,
state->kxfallback, &state->keyf);
if (!r && !state->opts->quiet)
FPLOG(WARN, "Key stored in xattr of %s is not well protected\n",
state->opts->oname);
return r;
}
static inline int get_iv_xattr(crypt_state* state)
{
return get_xattr(state, state->iv_xattr_name,
state->sec->nonce1, BLKSZ,
state->ixfallback, &state->ivf, &state->iset);
}
static inline int set_iv_xattr(crypt_state *state)
{
return set_xattr(state, state->iv_xattr_name,
state->sec->nonce1, BLKSZ,
state->ixfallback, &state->ivf);
}
#endif
int crypt_open(const opt_t *opt, int ilnchg, int olnchg, int ichg, int ochg,
unsigned int totslack_pre, unsigned int totslack_post,
const fstate_t *fst, void **stat, int islast)
{
int err = 0;
char ivsnm[32], keynm[32], saltnm[32];
clock_t t1 = 0;
crypt_state *state = (crypt_state*)*stat;
//state->opts = (opt_t*)opt;
state->zerosize = MAX(65536, opt->softbs);
state->ilnchg = ilnchg;
state->islast = islast;
sprintf(ivsnm, "IVS.%s", state->alg->name);
sprintf(keynm, "KEYS.%s", state->alg->name);
sprintf(saltnm, "SALT.%s", state->alg->name);
#ifdef HAVE_XATTR
if (state->sxattr && !state->salt_xattr_name) {
state->salt_xattr_name = malloc(32);
snprintf(state->salt_xattr_name, 32, "user.salt.%s", state->alg->name);
}
if (state->kxattr && !state->key_xattr_name) {
state->key_xattr_name = malloc(32);
snprintf(state->key_xattr_name, 32, "user.key.%s", state->alg->name);
}
if (state->ixattr && !state->iv_xattr_name) {
state->iv_xattr_name = malloc(32);
snprintf(state->iv_xattr_name, 32, "user.iv.%s", state->alg->name);
}
#endif
if (state->bench)
t1 = clock();
/* Are we en- or decrypting? */
const char* encnm = state->enc? opt->oname: opt->iname;
size_t encln = state->enc? opt->init_opos + (opt->reverse? 0: fst->estxfer): fst->fin_ipos + (opt->reverse? fst->estxfer: 0);
if (state->alg->stream->granul > 1 && state->enc && (state->pad == PAD_ALWAYS || (state->pad == PAD_ASNEEDED && (encln&(BLKSZ-1)))))
encln += BLKSZ-(encln&(BLKSZ-1));
else
ddr_plug.changes_output_len = 0;
/* If we need to generate a salt ... */
if (state->saltlen != (size_t)-1)
encln = state->saltlen;
/* Password */
if (state->pset && state->pfnm) {
/*
if (write_keyfile(state, state->pfnm, encnm, state->sec->passphr, strlen((const char*)state->sec->passphr), 0600, 0, 0))
return -1;
*/
if (write_file(state->sec->passphr, state->pfnm, strlen((const char*)state->sec->passphr), 0600))
return -1;
}
char needsalt = state->pset && !((state->iset||state->igen) && (state->kset||state->kgen));
/* 5th: Salt possibilities:
* (.) We may not need a salt as user opted to specify/read/generate key+IV ...
* (a) It's been set already via salt=, saltfd=, salthex=, saltfile= (sset is set)
* (b) We use openSSL compat and find a valid Salted__ header
* (c) We can read it from saltsfile (SALT.$ALG) or from xattr
* (d) It needs to be generated via prng (sgen)
* (e) Nothing: Generate from file name and length
*/
if (needsalt) {