-
Notifications
You must be signed in to change notification settings - Fork 0
/
tomb
executable file
·3431 lines (2864 loc) · 101 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
#!/usr/bin/env zsh
#
# Tomb, the Crypto Undertaker
#
# A commandline tool to easily operate encryption of secret data
#
# {{{ License
# Copyright (C) 2007-2019 Dyne.org Foundation
#
# Tomb is designed, written and maintained by Denis Roio <[email protected]>
#
# With contributions by Anathema, Boyska, Hellekin O. Wolf and GDrooid
#
# Gettext internationalization and Spanish translation is contributed by
# GDrooid, French translation by Hellekin, Russian translation by fsLeg,
# German translation by x3nu.
#
# Testing, reviews and documentation are contributed by Dreamer, Shining
# the Translucent, Mancausoft, Asbesto Molesto, Nignux, Vlax, The Grugq,
# Reiven, GDrooid, Alphazo, Brian May, TheJH, fsLeg, JoelMon and the
# Linux Action Show!
#
# Tomb's artwork is contributed by Jordi aka Mon Mort and Logan VanCuren.
#
# Cryptsetup was developed by Christophe Saout and Clemens Fruhwirth.
# 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
typeset VERSION="2.7"
typeset DATE="Oct/2019"
typeset TOMBEXEC=$0
typeset TMPPREFIX=${TMPPREFIX:-/tmp}
# TODO: configure which tmp dir to use from a cli flag
# Tomb is using some global variables set by the shell:
# TMPPREFIX, UID, GID, PATH, TTY, USERNAME
# You can grep 'global variable' to see where they are used.
# Keep a reference of the original command line arguments
typeset -a OLDARGS
for arg in "${(@)argv}"; do OLDARGS+=("$arg"); done
# Special command requirements
typeset -a DD WIPE PINENTRY
DD=(dd)
WIPE=(rm -f)
PINENTRY=(pinentry)
# load zsh regex module
zmodload zsh/mapfile
zmodload -F zsh/stat b:zstat
# make sure variables aren't exported
unsetopt allexport
# Flag optional commands if available (see _ensure_dependencies())
typeset -i KDF=1
typeset -i STEGHIDE=1
typeset -i CLOAKIFY=1
typeset -i DECLOAKIFY=1
typeset -i SPHINX=1
typeset -i RESIZER=1
typeset -i SWISH=1
typeset -i QRENCODE=1
# Default mount options
typeset MOUNTOPTS="rw,noatime,nodev"
# Makes glob matching case insensitive
unsetopt CASE_MATCH
typeset -AH OPTS # Command line options (see main())
# Command context (see _whoami())
typeset -H _USER # Running username
typeset -Hi _UID # Running user identifier
typeset -Hi _GID # Running user group identifier
typeset -H _TTY # Connected input terminal
# Tomb context (see _plot())
typeset -H TOMBPATH # Full path to the tomb
typeset -H TOMBDIR # Directory where the tomb is
typeset -H TOMBFILE # File name of the tomb
typeset -H TOMBNAME # Name of the tomb
# Tomb secrets
typeset -H TOMBKEY # Encrypted key contents (see forge_key(), recover_key())
typeset -H TOMBKEYFILE # Key file (ditto)
typeset -H TOMBSECRET # Raw deciphered key (see forge_key(), gpg_decrypt())
typeset -H TOMBPASSWORD # Raw tomb passphrase (see gen_key(), ask_key_password())
typeset -H TOMBTMP # Filename of secure temp just created (see _tmp_create())
typeset -aH TOMBTMPFILES # Keep track of temporary files
typeset -aH TOMBLOOPDEVS # Keep track of used loop devices
typeset -A TOMBFILESSTAT # Keep track of access date attributes
typeset _MSG_FD_OVERRIDE # if set, _msg will write to this file descriptor
# Make sure sbin is in PATH (man zshparam)
path+=( /sbin /usr/sbin )
# For gettext
export TEXTDOMAIN=tomb
# }}}
# {{{ Safety functions
# Wrap sudo with a more visible message
_sudo() {
local msg="[sudo] Enter password for user ::1 user:: to gain superuser privileges"
command -v gettext 1>/dev/null 2>/dev/null && msg="$(gettext -s "$msg")"
msg=${(S)msg//::1*::/$USER}
sudo -p "
$msg
" ${@}
}
# Cleanup anything sensitive before exiting.
_endgame() {
# Restore access time of sensitive files
[[ -z $TOMBFILESSTAT ]] || _restore_stat
# Prepare some random material to overwrite vars
local rr="$RANDOM"
while [[ ${#rr} -lt 500 ]]; do
rr+="$RANDOM"
done
# Ensure no information is left in unallocated memory
TOMBPATH="$rr"; unset TOMBPATH
TOMBDIR="$rr"; unset TOMBDIR
TOMBFILE="$rr"; unset TOMBFILE
TOMBNAME="$rr"; unset TOMBNAME
TOMBKEY="$rr"; unset TOMBKEY
TOMBKEYFILE="$rr"; unset TOMBKEYFILE
TOMBSECRET="$rr"; unset TOMBSECRET
TOMBPASSWORD="$rr"; unset TOMBPASSWORD
# Clear temporary files
for f in $TOMBTMPFILES; do
${=WIPE} "$f"
done
unset TOMBTMPFILES
# Detach loop devices
for l in $TOMBLOOPDEVS; do
_sudo losetup -d "$l"
done
unset TOMBLOOPDEVS
}
# Trap functions for the _endgame event
TRAPINT() { _endgame INT }
TRAPEXIT() { _endgame EXIT }
TRAPHUP() { _endgame HUP }
TRAPQUIT() { _endgame QUIT }
TRAPABRT() { _endgame ABORT }
TRAPKILL() { _endgame KILL }
TRAPPIPE() { _endgame PIPE }
TRAPTERM() { _endgame TERM }
TRAPSTOP() { _endgame STOP }
_cat() { local -a _arr;
# read file using mapfile, newline fix
_arr=("${(f@)${mapfile[${1}]%$'\n'}}"); print "$_arr"
}
_is_found() {
# returns 0 if binary is found in path
[[ "$1" = "" ]] && return 1
command -v "$1" 1>/dev/null 2>/dev/null
return $?
}
# Track acces and modification time of tomb files.
# $1: file to track
# date format: seconds since Epoch
# stat format: <last access>:<last modified>
_track_stat() {
local file="$1"
local stat=$(stat --format="%X:%Y" "$file")
TOMBFILESSTAT+=("$file" "$stat")
}
# Restore files stats
_restore_stat() {
local file stat
for file stat in "${(@kv)TOMBFILESSTAT}"; do
stats=("${(@s.:.)stat}")
_verbose "Restoring access and modification time for ::1 file::" $file
[[ -z "${stats[1]}" ]] || touch -a --date="@${stats[1]}" "$file"
[[ -z "${stats[2]}" ]] || touch -m --date="@${stats[2]}" "$file"
done
}
# Identify the running user
# Set global variables _UID, _GID, _TTY, and _USER, either from the
# command line, -U, -G, -T, respectively, or from the environment.
# Also update USERNAME and HOME to maintain consistency.
_whoami() {
# Set username from UID or environment
_USER=$SUDO_USER
[[ "$_USER" = "" ]] && { _USER=$USERNAME }
[[ "$_USER" = "" ]] && { _USER=$(id -u) }
[[ "$_USER" = "" ]] && {
_failure "Failing to identify the user who is calling us" }
# Get GID from option -G or the environment
option_is_set -G \
&& _GID=$(option_value -G) || _GID=$(id -g $_USER)
# Get UID from option -U or the environment
option_is_set -U \
&& _UID=$(option_value -U) || _UID=$(id -u $_USER)
_verbose "Identified caller: ::1 username:: (::2 UID:::::3 GID::)" $_USER $_UID $_GID
# Update USERNAME accordingly if possible
# [[ $EUID == 0 && $_USER != $USERNAME ]] && {
# _verbose "Updating USERNAME from '::1 USERNAME::' to '::2 _USER::')" $USERNAME $_USER
# USERNAME=$_USER
# }
# Force HOME to _USER's HOME if necessary
local home=`_get_home $_USER`
[[ $home == $HOME ]] || {
_verbose "Updating HOME to match user's: ::1 home:: (was ::2 HOME::)" \
$home $HOME
HOME=$home }
# Get connecting TTY from option -T or the environment
option_is_set -T && _TTY=$(option_value -T)
[[ -z $_TTY ]] && _TTY=$TTY
}
# Define sepulture's plot (setup tomb-related arguments)
# Synopsis: _plot /path/to/the.tomb
# Set TOMB{PATH,DIR,FILE,NAME}
_plot() {
# We set global variables
typeset -g TOMBPATH TOMBDIR TOMBFILE TOMBNAME
TOMBPATH="$1"
TOMBDIR=$(dirname $TOMBPATH)
TOMBFILE=$(basename $TOMBPATH)
# The tomb name is TOMBFILE without an extension and underscores instead of spaces (for mount and cryptsetup)
# It can start with dots: ..foo bar baz.tomb -> ..foo_bar_baz
TOMBNAME=${${TOMBFILE// /_}%.*}
# use the entire filename if the previous transformation returns
# an empty string. This handles the corner case of tomb being
# hidden files (starting with a dot) and have no extension (only
# one dot in string)
TOMBNAME=${TOMBNAME:-${TOMBFILE}}
[[ "$TOMBNAME" = "" ]] &&
_failure "Tomb won't work without a TOMBNAME."
}
# Provide a random filename in shared memory
_tmp_create() {
[[ -d "$TMPPREFIX" ]] || {
# we create the tempdir with the sticky bit on
_sudo mkdir -m 1777 "$TMPPREFIX"
[[ $? == 0 ]] || _failure "Fatal error creating the temporary directory: ::1 temp dir::" "$TMPPREFIX"
}
# We're going to add one more $RANDOM for each time someone complains
# about this being too weak of a random.
tfile="${TMPPREFIX}/$RANDOM$RANDOM$RANDOM$RANDOM" # Temporary file
umask 066
[[ $? == 0 ]] || {
_failure "Fatal error setting the permission umask for temporary files" }
[[ -r "$tfile" ]] && {
_failure "Someone is messing up with us trying to hijack temporary files." }
touch "$tfile"
[[ $? == 0 ]] || {
_failure "Fatal error creating a temporary file: ::1 temp file::" "$tfile" }
_verbose "Created tempfile: ::1 temp file::" "$tfile"
TOMBTMP="$tfile"
TOMBTMPFILES+=("$tfile")
return 0
}
# Check if a *block* device is encrypted
# Synopsis: _is_encrypted_block /path/to/block/device
# Return 0 if it is an encrypted block device
_is_encrypted_block() {
local b=$1 # Path to a block device
local s="" # lsblk option -s (if available)
# Issue #163
# lsblk --inverse appeared in util-linux 2.22
# but --version is not consistent...
lsblk --help | grep -Fq -- --inverse
[[ $? -eq 0 ]] && s="--inverse"
sudo lsblk $s -o type -n $b 2>/dev/null \
| egrep -q '^crypt$'
return $?
}
# Check if swap is activated
# Return 0 if NO swap is used, 1 if swap is used.
# Return 1 if any of the swaps is not encrypted.
# Return 2 if swap(s) is(are) used, but ALL encrypted.
# Use _check_swap in functions. It will call this function and
# exit if unsafe swap is present.
_ensure_safe_swap() {
local -i r=1 # Return code: 0 no swap, 1 unsafe swap, 2 encrypted
local -a swaps # List of swap partitions
local bone is_crypt
swaps="$(awk '/^\// { print $1 }' /proc/swaps 2>/dev/null)"
[[ -z "$swaps" ]] && return 0 # No swap partition is active
_message "An active swap partition is detected..."
for s in $=swaps; do
if _is_encrypted_block $s; then
r=2;
else
# We're dealing with unencrypted stuff.
# Maybe it lives on an encrypted filesystem anyway.
# @todo: verify it's actually on an encrypted FS (see #163 and !189)
# Well, no: bail out.
r=1; break;
fi
done
if [[ $r -eq 2 ]]; then
_success "The undertaker found that all swap partitions are encrypted. Good."
else
_warning "This poses a security risk."
_warning "You can deactivate all swap partitions using the command:"
_warning " swapoff -a"
_warning "[#163] I may not detect plain swaps on an encrypted volume."
_warning "But if you want to proceed like this, use the -f (force) flag."
fi
return $r
}
# Wrapper to allow encrypted swap and remind the user about possible
# data leaks to disk if swap is on, which shouldn't be ignored. It could
# be run once in main(), but as swap evolves, it's better to run it
# whenever swap may be needed.
# Exit if unencrypted swap is active on the system.
_check_swap() {
if ! option_is_set -f && ! option_is_set --ignore-swap; then
_ensure_safe_swap
case $? in
0|2) # No, or encrypted swap
return 0
;;
*) # Unencrypted swap
_failure "Operation aborted."
;;
esac
fi
}
pinentry_assuan_getpass() {
# simply prints out commands for pinentry's stdin to activate the
# password dialog
cat <<EOF
OPTION ttyname=$TTY
OPTION lc-ctype=$LANG
SETTITLE $title
SETDESC $description
SETPROMPT Password:
GETPIN
EOF
}
# Ask user for a password
# Wraps around the pinentry command, from the GnuPG project, as it
# provides better security and conveniently use the right toolkit.
ask_password() {
local description="$1"
local title="${2:-Enter tomb password.}"
local output
local password
local gtkrc
local theme
# Distributions have broken wrappers for pinentry: they do
# implement fallback, but they disrupt the output somehow. We are
# better off relying on less intermediaries, so we implement our
# own fallback mechanisms. Pinentry supported: curses, gtk-2, qt4, qt5
# and x11.
# make sure LANG is set, default to C
LANG=${LANG:-C}
_verbose "asking password with tty=$TTY lc-ctype=$LANG"
if [[ "$DISPLAY" = "" ]]; then
if _is_found "pinentry-curses"; then
_verbose "using pinentry-curses"
output=$(pinentry_assuan_getpass | pinentry-curses)
else
_failure "Cannot find pinentry-curses and no DISPLAY detected."
fi
else # a DISPLAY is found to be active
# customized gtk2 dialog with a skull (if extras are installed)
if _is_found "pinentry-gtk-2"; then
_verbose "using pinentry-gtk2"
gtkrc=""
theme=/share/themes/tomb/gtk-2.0-key/gtkrc
for i in /usr/local /usr; do
[[ -r $i/$theme ]] && {
gtkrc="$i/$theme"
break
}
done
[[ "$gtkrc" = "" ]] || {
gtkrc_old="$GTK2_RC_FILES"
export GTK2_RC_FILES="$gtkrc"
}
output=$(pinentry_assuan_getpass | pinentry-gtk-2)
[[ "$gtkrc" = "" ]] || export GTK2_RC_FILES="$gtkrc_old"
# TODO QT5 customization of dialog
elif _is_found "pinentry-qt5"; then
_verbose "using pinentry-qt5"
output=$(pinentry_assuan_getpass | pinentry-qt5)
# TODO QT4 customization of dialog
elif _is_found "pinentry-qt4"; then
_verbose "using pinentry-qt4"
output=$(pinentry_assuan_getpass | pinentry-qt4)
# TODO X11 customization of dialog
elif _is_found "pinentry-x11"; then
_verbose "using pinentry-x11"
output=$(pinentry_assuan_getpass | pinentry-x11)
else
if _is_found "pinentry-curses"; then
_verbose "using pinentry-curses"
_warning "Detected DISPLAY, but only pinentry-curses is found."
output=$(pinentry_assuan_getpass | pinentry-curses)
else
_failure "Cannot find any pinentry: impossible to ask for password."
fi
fi
fi # end of DISPLAY block
# parse the pinentry output
for i in ${(f)output}; do
[[ "$i" =~ "^ERR.*" ]] && {
_warning "Pinentry error: ::1 error::" ${i[(w)3]}
print "canceled"
return 1
}
# here the password is found
[[ "$i" =~ "^D .*" ]] && password="${i##D }";
done
# if sphinx mode is chosen, use the provided input
# as master password to retrieve the actual password
if option_is_set --sphx-user || option_is_set --sphx-host; then
password=$(sphinx_get_password "$password")
fi
[[ "$password" = "" ]] && {
_warning "Empty password"
print "empty"
return 1
}
print "$password"
return 0
}
# Retrieve PASSWORD from sphinx
# $1 MASTER password for the password store
# requires --sphx-host and --sphx-user flags to be set
sphinx_get_password() {
local errorfile
local password
if option_is_set --sphx-user && option_is_set --sphx-host; then
# value error in sphinx doesn't set exit code
# using tempfile as a workaround to notice the error
errorfile=$(mktemp /tmp/tomb_error.XXXXXXXXX)
password=$(echo "$1" | sphinx get $(option_value --sphx-user) $(option_value --sphx-host) 2>$errorfile)
if ! grep -q "ValueError: fail" $errorfile ; then
echo "$password"
rm $errorfile
return 0
else
_warning "sphinx returns error: ::1 error::" $(cat $errorfile)
rm $errorfile
_failure "Failed to retrieve actual password with sphinx."
fi
else
_failure "Both host and user have to be set to use sphinx"
fi
}
# Create PASSWORD in sphinx
# $1 MASTER password for the password store
# requires --sphx-host and --sphx-user flags to be set
sphinx_set_password() {
local errorfile
local password
if option_is_set --sphx-user && option_is_set --sphx-host; then
# value error in sphinx doesn't set exit code
# using tempfile as a workaround to notice the error
errorfile=$(mktemp /tmp/tomb_error.XXXXXXXXX)
# check first if this host/user combination exists in store
# if yes, there is no need to make a call to create
password=$(echo "$1" | sphinx get $(option_value --sphx-user) $(option_value --sphx-host) 2>$errorfile)
if ! grep -q "ValueError: fail" $errorfile ; then
echo "$password"
rm $errorfile
return 0
fi
# no such host/user combination in store, create one
password=$(echo "$1" | sphinx create $(option_value --sphx-user) $(option_value --sphx-host) ulsd 0 2>$errorfile)
if ! grep -q "ValueError: fail" $errorfile ; then
echo "$password"
rm $errorfile
return 0
else
_warning "sphinx returns error: ::1 error::" $(cat $errorfile)
rm $errorfile
_failure "Failed to create password with sphinx"
fi
else
_failure "Both host and user have to be set to use sphinx"
fi
}
# Check if a filename is a valid tomb
is_valid_tomb() {
_verbose "is_valid_tomb ::1 tomb file::" $1
# First argument must be the path to a tomb
[[ -z "$1" ]] && {
_failure "Tomb file is missing from arguments." }
_fail=0
# Tomb file must be a readable, writable, non-empty regular file.
# If passed the "ro" mount option, the writable check is skipped.
[[ ! -w "$1" ]] && [[ $(option_value -o) != *"ro"* ]] && {
_warning "Tomb file is not writable: ::1 tomb file::" $1
_fail=1
}
_verbose "tomb file is readable"
[[ ! -f "$1" ]] && {
_warning "Tomb file is not a regular file: ::1 tomb file::" $1
_fail=1
}
_verbose "tomb file is a regular file"
[[ ! -s "$1" ]] && {
_warning "Tomb file is empty (zero length): ::1 tomb file::" $1
_fail=1
}
_verbose "tomb file is not empty"
# no more checking on the uid
# _uid="`zstat +uid $1`"
# [[ "$_uid" = "$UID" ]] || {
# _user="`zstat -s +uid $1`"
# _warning "Tomb file is owned by another user: ::1 tomb owner::" $_user
# }
# _verbose "tomb is not owned by another user"
[[ $_fail = 1 ]] && {
_failure "Tomb command failed: ::1 command name::" $subcommand
}
# TODO: split the rest of that function out.
# We already have a valid tomb, now we're checking
# whether we can alter it.
# Tomb file may be a LUKS FS (or we are creating it)
[[ "`file $1`" =~ "luks encrypted file" ]] || {
_warning "File is not yet a tomb: ::1 tomb file::" $1 }
_plot $1 # Set TOMB{PATH,DIR,FILE,NAME}
# Tomb already mounted (or we cannot alter it)
[[ "`_sudo findmnt -rvo SOURCE,TARGET,FSTYPE,OPTIONS,LABEL |
awk -vtomb="[$TOMBNAME]" '
/^\/dev\/mapper\/tomb/ { if($5==tomb) print $1 }'`" = "" ]] || {
_failure "Tomb is currently in use: ::1 tomb name::" $TOMBNAME
}
_verbose "tomb file is not currently in use"
_message "Valid tomb file found: ::1 tomb path::" $TOMBPATH
return 0
}
# $1 is the tomb file to be lomounted
lo_mount() {
tpath="$1"
# check if we have support for loop mounting
_nstloop=`_sudo losetup -f`
[[ $? = 0 ]] || {
_warning "Loop mount of volumes is not possible on this machine, this error"
_warning "often occurs on VPS and kernels that don't provide the loop module."
_warning "It is impossible to use Tomb on this machine under these conditions."
_failure "Operation aborted."
}
_sudo losetup -f "$tpath" # allocates the next loopback for our file
TOMBLOOPDEVS+=("$_nstloop") # add to array of lodevs used
return 0
}
# print out latest loopback mounted
lo_new() { print - "${TOMBLOOPDEVS[${#TOMBLOOPDEVS}]}" }
# $1 is the path to the lodev to be preserved after quit
lo_preserve() {
_verbose "lo_preserve on ::1 path::" $1
# remove the lodev from the tomb_lodevs array
TOMBLOOPDEVS=("${(@)TOMBLOOPDEVS:#$1}")
}
# eventually used for debugging
dump_secrets() {
print "TOMBPATH: $TOMBPATH"
print "TOMBNAME: $TOMBNAME"
print "TOMBKEY len: ${#TOMBKEY}"
print "TOMBKEYFILE: $TOMBKEYFILE"
print "TOMBSECRET len: ${#TOMBSECRET}"
print "TOMBPASSWORD: $TOMBPASSWORD"
print "TOMBTMPFILES: ${(@)TOMBTMPFILES}"
print "TOMBLOOPDEVS: ${(@)TOMBLOOPDEVS}"
}
# }}}
# {{{ Commandline interaction
usage() {
_print "Syntax: tomb [options] command [arguments]"
echo
_print "Commands:"
echo
_print " // Creation:"
_print " dig create a new empty TOMB file of size -s in MiB"
_print " forge create a new KEY file and set its password"
_print " lock installs a lock on a TOMB to use it with KEY"
echo
_print " // Operations on tombs:"
_print " open open an existing TOMB (-k KEY file or - for stdin)"
_print " index update the search indexes of tombs"
_print " search looks for filenames matching text patterns"
_print " list list of open TOMBs and information on them"
_print " ps list of running processes inside open TOMBs"
_print " close close a specific TOMB (or 'all')"
_print " slam slam a TOMB killing all programs using it"
[[ $RESIZER == 1 ]] && {
_print " resize resize a TOMB to a new size -s (can only grow)"
}
echo
_print " // Operations on keys:"
_print " passwd change the password of a KEY (needs old pass)"
_print " setkey change the KEY locking a TOMB (needs old key and pass)"
echo
[[ $QRENCODE == 1 ]] && {
_print " // Backup on paper:"
_print " engrave makes a QR code of a KEY to be saved on paper"
echo
}
[[ $STEGHIDE == 1 || $CLOAKIFY == 1 || $DECLOAKIFY == 1 ]] && {
_print " // Steganography:"
[[ $STEGHIDE == 1 ]] && {
_print " bury hide a KEY inside a JPEG image (for use with -k)"
_print " exhume extract a KEY from a JPEG image (prints to stdout)"
}
[[ $CLOAKIFY == 1 ]] && {
_print " cloak transform a KEY into TEXT using CIPHER (for use with -k)"
}
[[ $DECLOAKIFY == 1 ]] && {
_print " uncloak extract a KEY from a TEXT using CIPHER (prints to stdout)"
}
echo
}
_print "Options:"
echo
_print " -s size of the tomb file when creating/resizing one (in MiB)"
_print " -k path to the key to be used ('-k -' to read from stdin)"
_print " -n don't launch the execution hooks found in tomb"
_print " -p preserve the ownership of all files in tomb"
_print " -o options passed to commands: open, lock, forge (see man)"
_print " -f force operation (i.e. even if swap is active)"
_print " -g use a GnuPG key to encrypt a tomb key"
_print " -r provide GnuPG recipients (separated by comma)"
_print " -R provide GnuPG hidden recipients (separated by comma)"
[[ $SPHINX == 1 ]] && {
_print " --sphx-user user associated with the key (for use with pitchforkedsphinx)"
_print " --sphx-host host associated with the key (for use with pitchforkedsphinx)"
}
[[ $KDF == 1 ]] && {
_print " --kdf forge keys armored against dictionary attacks"
}
echo
_print " -h print this help"
_print " -v print version, license and list of available ciphers"
_print " -q run quietly without printing informations"
_print " -D print debugging information at runtime"
echo
_print "For more information on Tomb read the manual: man tomb"
_print "Please report bugs on <http://github.com/dyne/tomb/issues>."
}
# Check whether a commandline option is set.
#
# Synopsis: option_is_set -flag [out]
#
# First argument is the commandline flag (e.g., "-s").
# If the second argument is present and set to 'out', print out the
# result: either 'set' or 'unset' (useful for if conditions).
#
# Return 0 if is set, 1 otherwise
option_is_set() {
local -i r # the return code (0 = set, 1 = unset)
[[ -n ${(k)OPTS[$1]} ]];
r=$?
[[ $2 == "out" ]] && {
[[ $r == 0 ]] && { print 'set' } || { print 'unset' }
}
return $r;
}
# Print the option value matching the given flag
# Unique argument is the commandline flag (e.g., "-s").
option_value() {
print -n - "${OPTS[$1]}"
}
# Messaging function with pretty coloring
function _msg() {
local msg="$2"
local i
command -v gettext 1>/dev/null 2>/dev/null && msg="$(gettext -s "$2")"
for i in {3..${#}}; do
msg=${(S)msg//::$(($i - 2))*::/$*[$i]}
done
local command="print -P"
local progname="${TOMBEXEC##*/}"
local pchars=""
local pcolor="normal"
local fd=1
local -i returncode
case "$1" in
inline)
command+=" -n"; pchars=" > "; pcolor="yellow"
;;
message)
pchars=" . "; pcolor="white"
;;
verbose)
pchars="[D]"; pcolor="blue"
;;
success)
pchars="(*)"; pcolor="green"
;;
warning)
pchars="[W]"; pcolor="yellow"
;;
failure)
pchars="[E]"; pcolor="red"
fd=2
returncode=1
;;
print)
progname=""
;;
*)
pchars="[F]"; pcolor="red"
msg="Developer oops! Usage: _msg MESSAGE_TYPE \"MESSAGE_CONTENT\""
fd=2
returncode=127
;;
esac
[[ -n $_MSG_FD_OVERRIDE ]] && fd=$_MSG_FD_OVERRIDE
if [[ -t $fd ]]; then
[[ -n "$progname" ]] && progname="$fg[magenta]$progname$reset_color"
[[ -n "$pchars" ]] && pchars="$fg_bold[$pcolor]$pchars$reset_color"
msg="$fg[$pcolor]$msg$reset_color"
fi
${=command} "${progname}" "${pchars}" "${msg}" >&$fd
return $returncode
}
function _message() {
local notice="message"
[[ "$1" = "-n" ]] && shift && notice="inline"
option_is_set -q || _msg "$notice" $@
return 0
}
function _verbose() {
option_is_set -D && _msg verbose $@
return 0
}
function _success() {
option_is_set -q || _msg success $@
return 0
}
function _warning() {
option_is_set -q || _msg warning $@
return 1
}
function _failure() {
typeset -i exitcode=${exitv:-1}
option_is_set -q || _msg failure $@
# be sure we forget the secrets we were told
exit $exitcode
}
function _print() {
option_is_set -q || _msg print $@
return 0
}
_list_optional_tools() {
typeset -a _deps
_deps=(gettext dcfldd shred steghide)
_deps+=(resize2fs tomb-kdb-pbkdf2 qrencode swish-e unoconv lsof)
for d in $_deps; do
_print "`which $d`"
done
return 0
}
# Check program dependencies
#
# Tomb depends on system utilities that must be present, and other
# functionality that can be provided by various programs according to
# what's available on the system. If some required commands are
# missing, bail out.
_ensure_dependencies() {
# Check for required programs
for req in cryptsetup pinentry sudo gpg mkfs.ext4 e2fsck; do
command -v $req 1>/dev/null 2>/dev/null || {
_failure "Missing required dependency ::1 command::. Please install it." $req; }
done
# Ensure system binaries are available in the PATH
path+=(/sbin /usr/sbin) # zsh magic
# Which dd command to use
command -v dcfldd 1>/dev/null 2>/dev/null && DD=(dcfldd statusinterval=1)
# Which wipe command to use
command -v shred 1>/dev/null 2>/dev/null && WIPE=(shred -f -u)
# Check for lsof for slamming tombs
command -v lsof 1>/dev/null 2>/dev/null || LSOF=0
# Check for steghide
command -v steghide 1>/dev/null 2>/dev/null || STEGHIDE=0
# Check for python2
command -v python2 -V 1>/dev/null 2>/dev/null || PYTHON2=0
# Check for cloakify
command -v cloakify 1>/dev/null 2>/dev/null || CLOAKIFY=0
# Check for decloakify
command -v decloakify 1>/dev/null 2>/dev/null || DECLOAKIFY=0
# Check for pitchforkedsphinx client
command -v sphinx 1>/dev/null 2>/dev/null || SPHINX=0
# Check for resize
command -v resize2fs 1>/dev/null 2>/dev/null || RESIZER=0
# Check for KDF auxiliary tools
command -v tomb-kdb-pbkdf2 1>/dev/null 2>/dev/null || KDF=0
# Check for Swish-E file content indexer
command -v swish-e 1>/dev/null 2>/dev/null || SWISH=0
# Check for QREncode for paper backups of keys
command -v qrencode 1>/dev/null 2>/dev/null || QRENCODE=0
}
# }}} - Commandline interaction
# {{{ Key operations
# $@ is the list of all the recipient used to encrypt a tomb key
is_valid_recipients() {
typeset -a recipients
recipients=($@)
trusted=(m f u w s)
_verbose "is_valid_recipients"
# All the keys ID must be valid (the public keys must be present in the database)
for gpg_id in ${recipients[@]}; do
trust="$(gpg --with-colons --batch --list-keys "$gpg_id" 2> /dev/null |
awk 'BEGIN { FS=":" } /^pub/ { print $2; exit}')"
[[ $? != 0 ]] && {
_warning "Not a valid GPG key ID: ::1 gpgid:: " $gpg_id
return 1
}
[[ ${trusted[(r)$trust]} != $trust ]] && {
_warning "The key ::1 gpgid:: is not trusted enough" $gpg_id
return 1
}
done
# At least one private key must be present
for gpg_id in ${recipients[@]}; do
gpg --with-colons --batch --list-secret-keys "$gpg_id" &> /dev/null
[[ $? = 0 ]] && {
return 0
}
done
return 1
}
# $@ is the list of all the recipient used to encrypt a tomb key
# Print the recipient arg to be used in gpg.
_recipients_arg() {
local arg="$1"; shift
typeset -a recipients
recipients=($@)
for gpg_id in ${recipients[@]}; do
print -R -n "$arg $gpg_id "
done
return 0
}
# $1 is a GPG key recipient
# Print the fingerprint of the GPG key
_gpg_fingerprint() {