-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtomb
executable file
·2446 lines (2068 loc) · 68.2 KB
/
tomb
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
#!/bin/zsh
#
# Tomb, the Crypto Undertaker
#
# A commandline tool to easily operate encryption of secret data
#
# Homepage on: [tomb.dyne.org](http://tomb.dyne.org)
# {{{ License
# Copyright (C) 2007-2013 Dyne.org Foundation
#
# Tomb is designed, written and maintained by Denis Roio <jaromil@dyne.org>
#
# With contributions by Anathema, Boyska and Hellekin O. Wolf.
#
# Testing and reviews are contributed by Dreamer, Shining,
# Mancausoft, Asbesto Molesto and Nignux.
#
# Tomb's artwork is contributed by Jordi aka Mon Mort.
#This source code is free software; you can redistribute it
#and/or modify it under the terms of the GNU Public License
#as published by the Free Software Foundation; either
#version 3 of the License, or (at your option) any later
#version.
#
#This source code is distributed in the hope that it will be
#useful, but WITHOUT ANY WARRANTY; without even the implied
#warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#PURPOSE. Please refer to the GNU Public License for more
#details.
#
#You should have received a copy of the GNU Public License
#along with this source code; if not, write to: Free
#Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
#02139, USA.
# }}} - License
# {{{ Global variables
VERSION=1.4
DATE="Jun/2013"
TOMBEXEC=$0
typeset -a OLDARGS
for arg in ${argv}; do OLDARGS+=($arg); done
DD="dd"
WIPE="rm -f"
MKFS="mkfs.ext3 -q -F -j -L"
KDF=1
STEGHIDE=1
MKTEMP=1
RESIZER=1
SWISH=1
QRENCODE=1
MOUNTOPTS="rw,noatime,nodev"
typeset -A global_opts
typeset -A opts
typeset -h username
typeset -h tombkeydir # global used if key comes from stdin
tombkeydir=""
typeset -h _uid
typeset -h _gid
typeset -h _tty
# Set a sensible PATH
# PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
# }}}
# {{{ Safety functions
_have_shm() {
# Check availability of 1MB of SHM
xxx "_have_shm 0 We need only 1 MB of RAM"
[[ -k /dev/shm ]] || return 1
local -i SHM RAM
SHM=$(df -k -B 4K -a -t tmpfs /dev/shm | awk '/\/dev\/shm/ { print $4; }')
(( $? )) && return 1
xxx "_have_shm 1 SHM $SHM KB are available"
RAM=$(awk '/MemFree/ { print $2 }' /proc/meminfo)
xxx "_have_shm 2 RAM $RAM KB are free"
(( $RAM >= 1024 )) && return 0
xxx "_have_shm 3 RAM $RAM KB left only :("
# Now we have more RAM than affected to SHM, so we can expect some for our little needs.
# Does that work when SHM is disabled from kernel config?
return 1
}
# Create temporary directories with caution
safe_dir() {
# Try and create our temporary directory in RAM
# Note that there's no warranty the underlying FS won't swap
# every 5 seconds (e.g., ext3)
local -i tries
while (( $tries < 3 )) ; do
tries+=1
if _have_shm; then
xxx "safe_dir creating $1 dir in RAM"
if (( $MKTEMP )); then
mktemp -d /dev/shm/tomb.$1.$$.XXXXXXX
else
dir="/dev/shm/tomb.$1.$$.$RANDOM$RANDOM"
mkdir -m 0700 -p "$dir"
print "$dir"
fi
return 0
else
_warning "WARNING: we cannot ensure we're running in RAM."
xxx "Wait a bit before retrying... (attempt $tries)"
sync && sleep 0.5
fi
done
_warning "WARNING: no RAM available for me to run safely."
return 1
}
# Provide a random filename in shared memory
safe_filename() {
_have_shm || die "No access to shared memory on this system, sorry."
(( $MKTEMP )) && \
mktemp -u /dev/shm/tomb.$1.$$.XXXXXXX || \
print "/dev/shm/tomb.$1.$$.$RANDOM$RANDOM"
}
# Check if swap is activated
check_swap() {
# Return 0 if NO swap is used, 1 if swap is used
# Return 2 if swap(s) is(are) used, but ALL encrypted
local swaps=$(awk '/partition/ { print $1 }' /proc/swaps 2>/dev/null)
[[ -z "$swaps" ]] && return 0 # No swap partition is active
no "An active swap partition is detected, this poses security risks."
no "You can deactivate all swap partitions using the command:"
no " swapoff -a"
no "But if you want to proceed like this, use the -f (force) flag."
die "Operation aborted."
}
# Ask user for a password
ask_password() {
# we use pinentry now
# comes from gpg project and is much more secure
# it also conveniently uses the right toolkit
# pinentry has no custom icon setting
# so we need to temporary modify the gtk theme
if [ -r /usr/local/share/themes/tomb/gtk-2.0-key/gtkrc ]; then
GTK2_RC=/usr/local/share/themes/tomb/gtk-2.0-key/gtkrc
elif [ -r /usr/share/themes/tomb/gtk-2.0-key/gtkrc ]; then
GTK2_RC=/usr/share/themes/tomb/gtk-2.0-key/gtkrc
fi
title="Insert tomb password"
if [ $2 ]; then title="$2"; fi
output=`cat <<EOF | GTK2_RC_FILES=${GTK2_RC} pinentry 2>/dev/null | tail -n +7
OPTION ttyname=$TTY
OPTION lc-ctype=$LANG
SETTITLE $title
SETDESC $1
SETPROMPT Password:
GETPIN
EOF`
if [[ `tail -n1 <<<$output` =~ ERR ]]; then
return 1
fi
head -n1 <<<$output | awk '/^D / { sub(/^D /, ""); print }'
return 0
}
# Drop privileges
exec_as_user() {
if ! [ $SUDO_USER ]; then
exec $@[@]
return $?
fi
xxx "exec_as_user '$SUDO_USER': ${(f)@}"
sudo -u $SUDO_USER "${@[@]}"
return $?
}
#Escalate privileges
check_priv() {
# save original user
username=$USER
if [ $UID != 0 ]; then
xxx "Using sudo for root execution of '${TOMBEXEC} ${(f)OLDARGS}'"
# check if sudo has a timestamp active
sudok=false
if ! option_is_set --sudo-pwd; then
if [ $? != 0 ]; then # if not then ask a password
cat <<EOF | pinentry 2>/dev/null | awk '/^D / { sub(/^D /, ""); print }' | sudo -S -v
OPTION ttyname=$TTY
OPTION lc-ctype=$LANG
SETTITLE Super user privileges required
SETDESC Sudo execution of Tomb ${OLDARGS[@]}
SETPROMPT Insert your USER password:
GETPIN
EOF
fi
else
_verbose "Escalating privileges using sudo-pwd"
sudo -S -v <<<`option_value --sudo-pwd`
fi
sudo "${TOMBEXEC}" -U ${UID} -G ${GID} -T ${TTY} "${(@)OLDARGS}"
exit $?
fi # are we root already
# check if we have support for loop mounting
losetup -f > /dev/null
{ test "$?" = "0" } || {
no "Loop mount of volumes is not supported on this machine, this error"
no "often occurs on VPS and kernels that don't provide the loop module."
no "It is impossible to use Tomb on this machine at this conditions."
die "Operation aborted."
}
# make sure necessary kernel modules are loaded
modprobe dm_mod 2>/dev/null
modprobe dm_crypt 2>/dev/null
return 0
}
# check if a filename is a valid tomb
is_valid_tomb() {
xxx "is_valid_tomb $1"
# argument check
{ test "$1" = "" } && {
_warning "Tomb file is missing from arguments"; return 1 }
# file checks
{ test -r "$1" } || {
_warning "Tomb file not found: $1"; return 1 }
{ test -f "$1" } || {
_warning "Tomb file is not a regular file: $1"; return 1 }
# check file type (if its a Luks fs)
file "$1" | grep -i 'luks encrypted file' >/dev/null
{ test $? = 0 } || {
_warning "File is not a valid tomb: $1"; return 1 }
# check if its already open
tombfile=`basename $1`
tombname=${tombfile%%\.*}
mount -l | grep "${tombfile}.*\[$tombname\]$" > /dev/null
{ test $? = 0 } && {
_warning "Tomb is currently in use: $tombname"; return 1 }
_message "Valid tomb file found: $1"
return 0
}
# }}}
# {{{ Commandline interaction
usage() {
cat <<EOF
Syntax: tomb [options] command [arguments]
Commands:
// Creation:
dig create a new empty TOMB file of --size in MB
forge create a new KEY file and set its password
lock installs a lock on a TOMB to use it with KEY
// Operations on tombs:
open open an existing TOMB
index update the search indexes of tombs
search looks for filenames matching text patterns
list list of open TOMBs and information on them
close close a specific TOMB (or 'all')
slam slam a TOMB killing all programs using it
EOF
if [ "$RESIZER" = 1 ]; then
cat <<EOF
resize resize a TOMB to a new --size (can only grow)
EOF
fi
cat <<EOF
// Operations on keys:
passwd change the password of a KEY
setkey change the KEY locking a TOMB (needs old one)
EOF
{ test "$QRENCODE" = "1" } && {
cat <<EOF
engrave makes a QR code of a KEY to be saved on paper
EOF
}
if [ "$STEGHIDE" = 1 ]; then
cat <<EOF
bury hide a KEY inside a JPEG image
exhume extract a KEY from a JPEG image
EOF
fi
cat <<EOF
Options:
-s size of the tomb file when creating/resizing one (in MB)
-k path to the key to be used ('-k -' to read from stdin)
-n don't process the hooks found in tomb
-o mount options used to open (default: rw,noatime,nodev)
-f force operation (i.e. even if swap is active)
EOF
{ test "$KDF" = 1 } && {
cat <<EOF
--kdf generate passwords armored against dictionary attacks
EOF
}
cat <<EOF
-h print this help
-v print version, license and list of available ciphers
-q run quietly without printing informations
-D print debugging information at runtime
For more informations on Tomb read the manual: man tomb
Please report bugs on <http://github.com/dyne/tomb/issues>.
EOF
}
# Check an option
option_is_set() {
# First argument, the commandline flag (i.e. "-s").
# Second (optional) argument: if "out", command will print it out 'set'/'unset'
# (useful for if conditions).
# Return 0 if is set, 1 otherwise
[[ -n ${(k)opts[$1]} ]];
r=$?
if [[ $2 == out ]]; then
if [[ $r == 0 ]]; then
echo 'set'
else
echo 'unset'
fi
fi
return $r;
}
# Get an option value
option_value() {
# First argument, the commandline flag (i.e. "-s").
<<< ${opts[$1]}
}
# Messaging function with pretty coloring
function _msg() {
local command="print -P"
local progname="$fg[magenta]${TOMBEXEC##*/}$reset_color"
local message="$fg_bold[normal]$fg_no_bold[normal]${2}$reset_color"
local -i returncode
case "$1" in
inline)
command+=" -n"; pchars=" > "; pcolor="yellow"
;;
message)
pchars=" . "; pcolor="white"; message="$fg_no_bold[$pcolor]${2}$reset_color"
;;
verbose)
pchars="[D]"; pcolor="blue"
;;
success)
pchars="(*)"; pcolor="green"; message="$fg_no_bold[$pcolor]${2}$reset_color"
;;
warning)
pchars="[W]"; pcolor="yellow"; message="$fg_no_bold[$pcolor]${2}$reset_color"
;;
failure)
pchars="[E]"; pcolor="red"; message="$fg_no_bold[$pcolor]${2}$reset_color"
returncode=1
;;
*)
pchars="[F]"; pcolor="red"
message="Developer oops! Usage: _msg MESSAGE_TYPE \"MESSAGE_CONTENT\""
returncode=127
;;
esac
${=command} "${progname} $fg_bold[$pcolor]$pchars$reset_color ${message}$color[reset_color]" >&2
return $returncode
}
function _message say() {
local notice="message"
[[ "$1" = "-n" ]] && shift && notice="inline"
option_is_set -q || _msg "$notice" "$1"
return 0
}
alias act="_message -n"
function _verbose xxx() {
option_is_set -D && _msg verbose "$1"
return 0
}
function _success yes() {
option_is_set -q || _msg success "$1"
return 0
}
function _warning no() {
option_is_set -q || _msg warning "$1"
return 1
}
function _failure die() {
typeset -i exitcode=${2:-1}
option_is_set -q || _msg failure "$1"
exit $exitcode
}
# Print out progress to inform GUI caller applications (--batch mode)
progress() {
# $1 is "what is progressing"
# $2 is "percentage"
# $3 is (eventually blank) status
# Example: if creating a tomb, it could be sth like
# progress create 0 filling with random data
# progress create 40 generating key
# progress keygen 0 please move the mouse
# progress keygen 30 please move the mouse
# progress keygen 60 please move the mouse
# progress keygen 100 key generated
# progress create 80 please enter password
# progress create 90 formatting the tomb
# progress create 100 tomb created successfully
if ! option_is_set --batch; then
return
fi
print "[m][P][$1][$2][$3]" >&2
}
# Check what's installed
check_bin() {
# check for required programs
for req in cryptsetup pinentry sudo gpg; do
command -v $req >/dev/null || die "Cannot find $req. It's a requirement to use Tomb, please install it." 1
done
export PATH=/sbin:/usr/sbin:$PATH
# which dd command to use
command -v dcfldd > /dev/null
{ test $? = 0 } && { DD="dcfldd statusinterval=1" }
# which wipe command to use
command -v wipe > /dev/null && WIPE="wipe -f -s" || WIPE="rm -f"
# check for filesystem creation progs
command -v mkfs.ext4 > /dev/null && \
MKFS="mkfs.ext4 -q -F -j -L" || \
MKFS="mkfs.ext3 -q -F -j -L"
# check for mktemp
command -v mktemp > /dev/null || MKTEMP=0
# check for steghide
command -v steghide > /dev/null || STEGHIDE=0
# check for resize
command -v e2fsck resize2fs > /dev/null || RESIZER=0
# check for KDF auxiliary tools
command -v tomb-kdb-pbkdf2 > /dev/null || KDF=0
# check for Swish-E file content indexer
command -v swish-e > /dev/null || SWISH=0
# check for QREncode for paper backups of keys
command -v qrencode > /dev/null || QRENCODE=0
}
# }}} - Commandline interaction
# {{{ Utils functions
# fromhuman accept arguments such as "5", "12MiB", "20KB"
fromhuman() {
zmodload zsh/pcre
if [[ -z $1 ]]; then
return 1
fi
if [[ $1 -pcre-match '^\d+$' ]]; then
echo $1
return 0
fi
human="${1:u}" # to uppercase
if ! [[ $human =~ '^[0-9]+[KMG]I?B$' ]]; then
return 1
fi
numeric=$(egrep -o '^[0-9]+' <<<$human)
modunit=$(egrep -o '[A-Z]*$' <<<$human)
typeset -A modunit_mult
modunit_mult=(KB 0.001 KIB 0.001024 MB 1 MIB 1 GB 1000 GIB 1024)
integer megabytes
megabytes=$(($numeric * ${modunit_mult[$modunit]}))
echo $megabytes
}
# }}} - Utils functions
# {{{ Key operations
# This function retrieves a tomb key specified on commandline or one
# laying nearby the tomb if found, or from stdin if the option was
# selected. It also runs validity checks on the file. Callers should
# always use drop_key() when done with all key operations.
# On success returns 0 and prints out the full path to the key
load_key() {
# take the name of a tomb file as argument
# this is used for guessing if the key is nearby
{ test "$1" = "" } || {
tombdir=`dirname $1`
tombfile=`basename $1`
tombname=${tombfile%%\.*}
}
if option_is_set -k ; then
if [[ "`option_value -k`" == "-" ]]; then
xxx "load_key reading from stdin"
# take key from stdin
tombkeydir=`safe_dir load_key`
xxx "tempdir is $tombkeydir"
cat > ${tombkeydir}/stdin.tmp
tombdir=${tombkeydir}
tombfile=stdin.tmp
tombname="stdin"
elif [[ "`option_value -k`" != "" ]]; then
# take key from a file
tombkey=`option_value -k`
tombdir=`dirname $tombkey`
tombfile=`basename $tombkey`
fi
fi
tombkey=${tombdir}/${tombfile}
xxx "load_key: `ls -lh ${tombkey}`"
if [ -r "${tombkey}" ]; then
_message "We'll use this key: ${tombkey}"
else
return 1
fi
# this does a check on the file header
if ! is_valid_key ${tombkey}; then
_warning "The key seems invalid, the application/pgp header is missing"
return 1
fi
print "$tombkey"
return 0
}
# This function asks the user for the password to use the key it tests
# it against the return code of gpg on success returns 0 and prints
# the password (be careful about where you save it!)
ask_key_password() {
tombkey="$1"
local keyname=`basename $tombkey`
_message "a password is required to use key ${keyname}"
local passok=0
local tombpass=""
if option_is_set --tomb-pwd; then
tombpass=`option_value --tomb-pwd`
xxx "ask_key_password takes tombpass from CLI argument: $tombpass"
get_lukskey "$tombpass" ${tombkey} >/dev/null
if [ $? = 0 ]; then
passok=1; _message "Password OK."; fi
else
for c in 1 2 3; do
if [ $c = 1 ]; then
tombpass=`exec_as_user ${TOMBEXEC} askpass "Insert password to use key: $keyname"`
else
tombpass=`exec_as_user ${TOMBEXEC} askpass "Insert password to use key: $keyname (retry $c)"`
fi
if [[ $? != 0 ]]; then
_warning "User aborted password dialog"
return 1
fi
get_lukskey "$tombpass" ${tombkey} >/dev/null
if [ $? = 0 ]; then
passok=1; _message "Password OK."
break;
fi
done
fi
{ test "$passok" = "1" } || { return 1 }
print "$tombpass"
unset $tombpass
return 0
}
# change tomb key password
change_passwd() {
_message "Commanded to change password for tomb key $1"
if ! option_is_set -f && ! option_is_set --ignore-swap; then check_swap; fi
local keyfile="$1" # $1 is the tomb key path
# check the keyfile
if ! [ -r $keyfile ]; then
_warning "key not found: $keyfile"
return 1
fi
if ! is_valid_key $keyfile ; then
_warning "file doesn't seems to be a tomb key: $keyfile"
_warning "operation aborted."
return 1
fi
local tmpnewkey lukskey c tombpass tombpasstmp
tmpnewkey=`safe_filename passnew`
lukskey=`safe_filename passold`
_success "Changing password for $keyfile"
tombpass=`ask_key_password $keyfile`
{ test $? = 0 } || {
die "No valid password supplied" }
get_lukskey "${tombpass}" ${keyfile} > ${lukskey};
drop_key
{
local algo
{ option_is_set -o } && { algopt="`option_value -o`" }
gen_key $lukskey $algopt > ${tmpnewkey}
if ! is_valid_key $tmpnewkey; then
die "Error: the newly generated keyfile does not seem valid"
else
# copy the new key as the original keyfile name
cp "${tmpnewkey}" "${keyfile}"
_success "Your passphrase was successfully updated."
fi
} always {
_verbose "cleanup: $tmpnewkey $lukskey"
# wipe all temp file
${=WIPE} "${tmpnewkey}"
${=WIPE} "${lukskey}"
}
return $?
}
# To be called after load_key()
drop_key() {
{ test "$tombkeydir" = "" } && { return 0 }
{ test -r ${tombkeydir}/stdin.tmp } && {
${=WIPE} ${tombkeydir}/stdin.tmp; rmdir ${tombkeydir} }
}
#$1 is the keyfile we are checking
is_valid_key() {
xxx "is_valid_key $1"
# argument check
{ test "$1" = "" } && {
_warning "Key file is missing from arguments"; return 1 }
# file checks
{ test -r "$1" } || {
_warning "Key file not found: $1"; return 1 }
{ test -f "$1" } || {
_warning "Key file is not a regular file: $1"; return 1 }
# this header validity check is a virtuosism by Hellekin
[[ `file =(awk '/^-+BEGIN/,0' $1)` =~ PGP ]] && {
_message "Valid key file found: $1"; return 0 }
# if no BEGIN header found then we try to recover it
[[ `file $1 -bi` =~ text/plain ]] && {
_warning "Key data found with missing headers, attempting recovery"
local tmp_keyfix=`safe_filename keyfix`
touch $tmp_keyfix
# make sure KDF header comes first
local header=`grep '^_KDF_' $1`
print "$header" >> $tmp_keyfix
cat $1 | awk '
BEGIN {
print "-----BEGIN PGP MESSAGE-----"
print
}
/^_KDF_/ { next }
{ print $0 }
END {
print "-----END PGP MESSAGE-----"
}' >> ${tmp_keyfix}
mv $tmp_keyfix $1
chown ${_uid}:${_gid} ${1}
chmod 0600 ${1}
return 0
}
_warning "Invalid key format: $1"
return 1
}
# Gets a key file and a password, prints out the decoded contents to
# be used directly by Luks as a cryptographic key
get_lukskey() {
# $1 is the password, $2 is the keyfile
local tombpass=$1
local keyfile=$2
firstline=`head -n1 $keyfile`
xxx "get_lukskey XXX $keyfile"
if [[ $firstline =~ '^_KDF_' ]]; then
_verbose "KDF: `cut -d_ -f 3 <<<$firstline`"
case `cut -d_ -f 3 <<<$firstline` in
pbkdf2sha1)
pbkdf2_param=`cut -d_ -f 4- <<<$firstline | tr '_' ' '`
tombpass=$(tomb-kdb-pbkdf2 ${=pbkdf2_param} 2> /dev/null <<<$tombpass)
;;
*)
_failure "No suitable program for KDF `cut -f 3 <<<$firstline`"
unset tombpass
return 1
;;
esac
fi
# fix for gpg 1.4.11 where the --status-* options don't work ;^/
gpgver=`gpg --version | awk '/^gpg/ {print $3}'`
if [ "$gpgver" = "1.4.11" ]; then
xxx "GnuPG is version 1.4.11 - adopting status fix"
print ${tombpass} | \
gpg --batch --passphrase-fd 0 --no-tty --no-options -d "${keyfile}"
ret=$?
unset tombpass
else # using status-file in gpg != 1.4.11
res=`safe_filename lukskey`
{ test $? = 0 } || { unset tombpass; die "Fatal error creating temp file." }
print ${tombpass} | \
gpg --batch --passphrase-fd 0 --no-tty --no-options --status-fd 2 \
--no-mdc-warning --no-permission-warning --no-secmem-warning \
-d "${keyfile}" 2> $res
unset tombpass
grep 'DECRYPTION_OKAY' $res > /dev/null
ret=$?; rm -f $res
fi
xxx "get_lukskey returns $ret"
return $ret
}
# takes care to encrypt a key
# honored options: --kdf --tomb-pwd
gen_key() {
# $1 the lukskey to encrypt
# $2 is the --cipher-algo to use (string taken by GnuPG)
local lukskey="$1"
local algo="${2:-AES256}"
# here user is prompted for key password
local tombpass=""
local tombpasstmp=""
if ! option_is_set --tomb-pwd; then
while true; do
# 3 tries to write two times a matching password
tombpass=`exec_as_user ${TOMBEXEC} askpass "Secure key for ${tombname}"`
if [[ $? != 0 ]]; then
die "User aborted"
fi
if [ -z $tombpass ]; then
_warning "you set empty password, which is not possible"
continue
fi
tombpasstmp=$tombpass
tombpass=`exec_as_user ${TOMBEXEC} askpass "Secure key for ${tombname} (again)"`
if [[ $? != 0 ]]; then
die "User aborted"
fi
if [ "$tombpasstmp" = "$tombpass" ]; then
break;
fi
unset tombpasstmp
unset tombpass
done
else
tombpass="`option_value --tomb-pwd`"
xxx "gen_key takes tombpass from CLI argument: $tombpass"
fi
header=""
{ test "$KDF" = 1 } && {
{ option_is_set --kdf } && {
# KDF is a new key strenghtening technique against brute forcing
# see: https://github.com/dyne/Tomb/issues/82
itertime="`option_value --kdf`"
# removing support of floating points because they can't be type checked well
if [[ "$itertime" != <-> ]]; then
unset tombpass
unset tombpasstmp
die "Wrong argument for --kdf: must be an integer number (iteration seconds)"
fi
# --kdf takes one parameter: iter time (on present machine) in seconds
local -i microseconds
microseconds=$((itertime*10000))
yes "Using KDF, iterations: $microseconds"
pbkdf2_salt=`tomb-kdb-pbkdf2-gensalt`
pbkdf2_iter=`tomb-kdb-pbkdf2-getiter $microseconds`
# We use a length of 64bytes = 512bits (more than needed!?)
tombpass=`tomb-kdb-pbkdf2 $pbkdf2_salt $pbkdf2_iter 64 <<<"${tombpass}"`
header="_KDF_pbkdf2sha1_${pbkdf2_salt}_${pbkdf2_iter}_64\n"
}
}
print -n $header
print "${tombpass}" \
| gpg --openpgp --force-mdc --cipher-algo ${algo} \
--batch --no-options --no-tty --passphrase-fd 0 --status-fd 2 \
-o - -c -a ${lukskey}
unset tombpass
unset tombpasstmp
}
# prints an array of ciphers available in gnupg (to encrypt keys)
list_gnupg_ciphers() {
# prints an error if GnuPG is not found
which gpg > /dev/null || die "gpg (GnuPG) is not found, Tomb cannot function without it."
ciphers=(`gpg --version | awk '
BEGIN { ciphers=0 }
/^Cipher:/ { gsub(/,/,""); sub(/^Cipher:/,""); print; ciphers=1; next }
/^Hash:/ { ciphers=0 }
{ if(ciphers==0) { next } else { gsub(/,/,""); print; } }
'`)
echo " ${ciphers}"
return 1
}
# Steganographic function to bury a key inside an image.
# Requires steghide(1) to be installed
bury_key() {
tombkey="`option_value -k`"
imagefile=$1
{ is_valid_key ${tombkey} } || {
die "Bury failed: not a tomb key $tombkey" }
file $imagefile | grep JPEG > /dev/null
if [ $? != 0 ]; then
_warning "encode failed: $imagefile is not a jpeg image"
return 1
fi
_success "Encoding key $tombkey inside image $imagefile"
_message "please confirm the key password for the encoding"
tombpass=`ask_key_password $tombkey`
{ test $? = 0 } || {
_warning "Wrong password supplied."
die "You shall not bury a key whose password is unknown to you."
}
# we omit armor strings since having them as constants can give
# ground to effective attacks on steganography
awk '
/^-----/ {next}
/^Version/ {next}
{print $0}' ${tombkey} \
| steghide embed --embedfile - --coverfile ${imagefile} \
-p ${tombpass} -z 9 -e serpent cbc
if [ $? != 0 ]; then
_warning "encoding error: steghide reports problems"
res=1
else
_success "tomb key encoded succesfully into image ${imagefile}"
res=0
fi
unset tombpass
return $res
}
# Steganographic function to exhume a key buries into an image
exhume_key() {
tombkey="`option_value -k`"
imagefile=$1
res=1
file $imagefile | grep JPEG > /dev/null
if [ $? != 0 ]; then
_warning "encode failed: $imagefile is not a jpeg image"
return 1
fi
if [[ -e "$tombkey" ]]; then
_warning "File exists: $tombkey"
{ option_is_set -f } || {
_warning "Make explicit use of --force to overwrite"
die "Refusing to overwrite file. Operation aborted." }
_warning "Use of --force selected: overwriting."
rm -f ${tombkey}
fi
_message "Trying to exhume a key out of image $imagefile"
if option_is_set --tomb-pwd; then
tombpass=`option_value --tomb-pwd`
xxx "ask_key_password takes tombpass from CLI argument: $tombpass"
else
tombpass=`exec_as_user ${TOMBEXEC} askpass "Steg password for ${tombkey}"`
fi
# always steghide required
steghide extract -sf ${imagefile} -p ${tombpass} -xf ${tombkey}
res=$?
unset tombpass
if [ $res = 0 ]; then
_success "${tombkey} succesfully decoded"
return 0
fi
_warning "nothing found in $imagefile"
return 1
}
# Produces a printable image of the key contents so that it can be
# backuped on paper and hidden in books etc.
engrave_key() {
# load key from options
tombkey="`load_key $1`"
{ test $? = 0 } || { die "No key specified." }
keyname=`basename $tombkey`
pngname="$keyname.qr.png"
yes "Rendering a printable QRCode for key: $tombkey"
# we omit armor strings to save space
awk '
/^-----/ {next}
/^Version/ {next}
{print $0}' ${tombkey} | qrencode --size 4 --level H \
--casesensitive -o "$pngname"
{ test $? = 0 } || { die "QREncode reported an error." }
yes "Operation successful:"
_message "`ls -lh $pngname`"
_message "`file $pngname`"
}
# }}} - Key handling
# {{{ Create
# This is a new way to create tombs which dissects the whole create_tomb() into 3 clear steps:
#
# * dig a .tomb (the large file) using /dev/random (takes some minutes at least)
#
# * forge a .key (the small file) using /dev/urandom (good entropy needed)
#
# * lock the .tomb file with the key, binding the key to the tomb (requires dm_crypt format)
forge_key() {
xxx "forge_key()"
# can be specified both as simple argument or using -k
local destkey="$1"
{ option_is_set -k } && { destkey="`option_value -k`" }
{ test "$destkey" = "" } && {
_warning "no key name specified for creation"
return 1 }
{ test -r "$destkey" } && {
_warning "Forging this key would overwrite an existing file. Operation aborted."
die "`ls -lh $destkey`" }
# if swap is on, we remind the user about possible data leaks to disk
if ! option_is_set -f && ! option_is_set --ignore-swap; then check_swap; fi
# create the keyfile in tmpfs so that we leave less traces in RAM
local keytmp=`safe_dir forge`
(( $? )) && die "error creating temp dir"