#!/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-2014 Dyne.org Foundation # # Tomb is designed, written and maintained by Denis Roio # # 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.6 DATE="Sept/2014" TOMBEXEC=$0 typeset -a OLDARGS for arg in ${argv}; do OLDARGS+=($arg); done # Special command requirements typeset -a DD WIPE MKFS DD=(dd) WIPE=(rm -f) MKFS=(mkfs.ext3 -q -F -j -L) # Flag optional commands if available typeset -i 2 KDF=1 typeset -i 2 STEGHIDE=1 typeset -i 2 RESIZER=1 typeset -i 2 SWISH=1 typeset -i 2 QRENCODE=1 # Default mount options MOUNTOPTS="rw,noatime,nodev" # prefix for temporary files TMPPREFIX="/dev/shm/$RANDOM.$RANDOM." # Makes glob matching case insensitive unsetopt CASE_MATCH typeset -AH OPTS # Command line options (see main()) # Command context typeset -H _UID # Running user identifier typeset -H _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 # Key contents (see forge_key(), recover_key()) typeset -H TOMBKEYFILE # Key file (ditto) typeset -H tomb_secret typeset -H tomb_password typeset -aH tomb_tempfiles typeset -aH tomb_loopdevs # Make sure sbin is in PATH PATH+=:/sbin:/usr/sbin # For gettext export TEXTDOMAIN=tomb # }}} # {{{ Safety functions endgame() { # here clear all temp files and flush all pipes # prepare some random material to overwrite vars rr="$RANDOM" while [[ ${#rr} -lt 500 ]]; do rr+="$RANDOM"; done # we make sure no info is left in unallocated mem TOMBPATH="$rr"; unset TOMBPATH TOMBDIR="$rr"; unset TOMBDIR TOMBFILE="$rr"; unset TOMBFILE TOMBNAME="$rr"; unset TOMBNAME TOMBKEY="$rr"; unset TOMBKEY TOMBKEYFILE="$rr"; unset TOMBKEYFILE tomb_secret="$rr"; unset tomb_secret tomb_password="$rr"; unset tomb_password for f in $tomb_tempfiles; do ${=WIPE} "$f"; done unset tomb_tempfiles for l in $tomb_loopdevs; do losetup -d "$l"; done unset tomb_loopdevs } # 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 } check_shm() { # TODO: configure which tmp dir to use from a cli flag SHMPREFIX=/dev/shm [[ -k /dev/shm ]] || [[ -k /run/shm ]] && { SHMPREFIX=/run/shm } \ || { # mount the tmpfs if the SO doesn't already mkdir /run/shm (( $? )) && _failure "Fatal error creating a directory for temporary files" mount -t tmpfs tmpfs /run/shm \ -o nosuid,noexec,nodev,mode=0600,uid=$_UID,gid=$_GID (( $? )) && _failure "Fatal error mounting tmpfs in /run/shm for temporary files" SHMPREFIX=/run/shm } # setup a special env var for zsh to create temp files that will # then be deleted at the exit of each function using them. TMPPREFIX="$SHMPREFIX/$RANDOM.$RANDOM." return 0 } # Define sepulture's plot (setup tomb-related arguments) # Synopsis: _plot "/path/to/the.tomb" _plot() { # We set global variables typeset -g TOMBPATH TOMBDIR TOMBFILE TOMBNAME TOMBPATH="$1" _verbose '_plot TOMBPATH = ::1 tomb path::' $TOMBPATH TOMBDIR=$(dirname $TOMBPATH) _verbose '_plot TOMBDIR = ::1 tomb dir::' $TOMBDIR TOMBFILE=$(basename $TOMBPATH) _verbose '_plot TOMBFILE = ::1 tomb file::' $TOMBFILE # The tomb name is TOMBFILE without an extension. # It can start with dots: ..foo.tomb -> ..foo TOMBNAME="${TOMBFILE%\.[^\.]*}" _verbose '_plot TOMBNAME = ::1 tomb name::' $TOMBNAME # Normalize TOMBFILE name TOMBFILE="${TOMBNAME}.tomb" _verbose '_plot TOMBFILE = ::1 tomb file:: (normalized)' $TOMBFILE # Normalize TOMBPATH TOMBPATH="${TOMBDIR}/${TOMBFILE}" _verbose '_plot TOMBPATH = ::1 tomb path:: (normalized)' $TOMBPATH } # Provide a random filename in shared memory tmp_create() { local tfile="${TMPPREFIX}${RANDOM}" touch "$tfile" (( $? )) && _failure "Fatal error creating a temporary file: ::1 temp file::" $tfile chown $_UID:$_GID "$tfile" chmod 0600 "$tfile" (( $? )) && _failure "Fatal error setting permissions on temporary file: ::1 temp file::" $tfile _verbose "Created tempfile: ::1 temp file::" $tfile tomb_tempfiles+=($tfile) return 0 } tmp_new() { # print out the latest tempfile print - "${tomb_tempfiles[${#tomb_tempfiles}]}" } # 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 '/^\// { print $1 }' /proc/swaps 2>/dev/null)" [[ -z "$swaps" ]] && return 0 # No swap partition is active # Check whether all swaps are encrypted, and return 2 # If any of the swaps is not encrypted, we bail out and return 1. ret=1 for s in $=swaps; do bone=`sudo file $s` if [[ "$bone" =~ "swap file" ]]; then # It's a regular (unencrypted) swap file ret=1 break elif [[ "$bone" =~ "symbolic link" ]]; then # Might link to a block ret=1 if [ "/dev/mapper" = "${s%/*}" ]; then is_crypt=`sudo dmsetup status "$s" | awk '/crypt/ {print $3}'` if [ "crypt" = "$is_crypt" ]; then ret=2 fi else break fi elif [[ "$bone" =~ "block special" ]]; then # Is a block ret=1 is_crypt=`sudo dmsetup status "$s" | awk '/crypt/ {print $3}'` if [ "crypt" = "$is_crypt" ]; then ret=2 else break fi fi done _warning "An active swap partition is detected, this poses security risks." if [[ $ret -eq 2 ]]; then _success "All your swaps are belong to crypt. Good." else _warning "You can deactivate all swap partitions using the command:" _warning " swapoff -a" _warning "But if you want to proceed like this, use the -f (force) flag." _failure "Operation aborted." fi return $ret } # Wrapper to allow encrypted swap and remind the user about # possible data leaks to disk if swap is on, and not to be ignored _check_swap() { if ! option_is_set -f && ! option_is_set --ignore-swap; then check_swap case $? in 0|2) # No, or encrypted swap return 0 ;; *) # Unencrypted swap return 1 ;; esac fi } # 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 </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 _verbose "exec_as_user '::1 user::': ::2::" $SUDO_USER ${(f)@} sudo -u $SUDO_USER "${@[@]}" return $? } # Escalate privileges check_priv() { if [ $UID != 0 ]; then _verbose "Using sudo for root execution of '::1 exec:: ::2 args::'." $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 </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 # make sure necessary kernel modules are loaded modprobe dm_mod modprobe dm_crypt return 0 } # Check if a filename is a valid tomb is_valid_tomb() { _verbose "is_valid_tomb ::1 tomb file::" $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 tomb file::" $1; return 1 } { test -f "$1" } || { _warning "Tomb file is not a regular file: ::1 tomb file::" $1; return 1 } { test -s "$1" } || { _warning "Tomb file is empty (zero length): ::1 tomb file::" $1; return 1 } { test -w "$1" } || { _warning "Tomb file is not writable: ::1 tomb file::" $1; return 1 } # check file type (if its a Luks fs) file "$1" | grep -i "luks encrypted file" > /dev/null || { _warning "File is not yet a tomb: ::1 tomb file::" $1} _plot $1 # Set TOMB{PATH,DIR,FILE,NAME} mount -l | grep "${TOMBFILE}.*\[$TOMBNAME\]$" > /dev/null { test $? = 0 } && { _warning "Tomb is currently in use: ::1 tomb name::" $TOMBNAME; return 1 } _message "Valid tomb file found: ::1 tomb path::" $TOMBPATH return 0 } # $1 is the tomb file to be lomounted lo_mount() { tpath="$1" is_valid_tomb "$tpath" || { _failure "Loopback mount called on invalid tomb: ::1 path::" $tpath } # check if we have support for loop mounting 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 at this conditions." _failure "Operation aborted." } _nstloop=`losetup -f` # get the number for next loopback device losetup -f "$tpath" >& - # allocates the next loopback for our file tomb_loopdevs+=("$_nstloop") # add to array of lodevs used return 0 } # print out latest loopback mounted lo_new() { print - "${tomb_loopdevs[${#tomb_loopdevs}]}" } # $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 tomb_loopdevs=("${(@)tomb_loopdevs:#$1}") } # eventually used for debugging dump_secrets() { _verbose "TOMBFILE: ::1 tomb file::" $TOMBPATH _verbose "TOMBFILE: ::1 tomb file::" $TOMBFILE _verbose "TOMBKEY: ::1 key:: chars long" ${#TOMBKEY} _verbose "TOMBKEYFILE: ::1 key file::" $TOMBKEYFILE _verbose "tomb_secret: ::1 secret:: chars long" ${#tomb_secret} _verbose "tomb_password: ::1 tomb pass::" $tomb_password _verbose "tomb_tempfiles: ::1 temp files::" ${(@)tomb_tempfiles} _verbose "tomb_loopdevs: ::1 loopdevs::" ${(@)tomb_loopdevs} } # }}} # {{{ Commandline interaction usage() { _print "Syntax: tomb [options] command [arguments]" _print "\000" _print "Commands:" _print "\000" _print " // Creation:" _print " dig create a new empty TOMB file of size -s in MB" _print " forge create a new KEY file and set its password" _print " lock installs a lock on a TOMB to use it with KEY" _print "\000" _print " // Operations on tombs:" _print " open open an existing TOMB" _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 " 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)" } _print "\000" _print " // Operations on keys:" _print " passwd change the password of a KEY" _print " setkey change the KEY locking a TOMB (needs old one)" _print "\000" [[ $QRENCODE == 1 ]] && { _print " engrave makes a QR code of a KEY to be saved on paper" } _print "\000" [[ $STEGHIDE == 1 ]] && { _print " bury hide a KEY inside a JPEG image" _print " exhume extract a KEY from a JPEG image" } _print "\000" _print "Options:" _print "\000" _print " -s size of the tomb file when creating/resizing one (in MB)" _print " -k path to the key to be used ('-k -' to read from stdin)" _print " -n don't process the hooks found in tomb" _print " -o mount options used to open (default: rw,noatime,nodev)" _print " -f force operation (i.e. even if swap is active)" [[ $KDF == 1 ]] && { _print " --kdf generate passwords armored against dictionary attacks" } _print "\000" _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" _print "\000" _print "For more informations on Tomb read the manual: man tomb" _print "Please report bugs on ." } # 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"). print -n - "${OPTS[$1]}" } # Messaging function with pretty coloring function _msg() { local msg="$(gettext -s "$2")" for i in $(seq 3 ${#}); do msg=${(S)msg//::$(($i - 2))*::/$*[$i]} done local command="print -P" local progname="$fg[magenta]${TOMBEXEC##*/}$reset_color" local message="$fg_bold[normal]$fg_no_bold[normal]$msg$reset_color" local -i returncode case "$1" in inline) command+=" -n"; pchars=" > "; pcolor="yellow" ;; message) pchars=" . "; pcolor="white"; message="$fg_no_bold[$pcolor]$msg$reset_color" ;; verbose) pchars="[D]"; pcolor="blue" ;; success) pchars="(*)"; pcolor="green"; message="$fg_no_bold[$pcolor]$msg$reset_color" ;; warning) pchars="[W]"; pcolor="yellow"; message="$fg_no_bold[$pcolor]$msg$reset_color" ;; failure) pchars="[E]"; pcolor="red"; message="$fg_no_bold[$pcolor]$msg$reset_color" returncode=1 ;; print) progname="" ;; *) 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" $@ return 0 } function _verbose xxx() { option_is_set -D && _msg verbose $@ return 0 } function _success yes() { option_is_set -q || _msg success $@ return 0 } function _warning no() { option_is_set -q || _msg warning $@ return 1 } function _failure die() { 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 } # 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 >& - || exitv=1 _failure "Cannot find ::1::. It's a requirement to use Tomb, please install it." $req done export PATH=/sbin:/usr/sbin:$PATH # which dd command to use command -v dcfldd >& - && DD=(dcfldd statusinterval=1) # which wipe command to use command -v wipe >& - && WIPE=(wipe -f -s) # check for filesystem creation progs command -v mkfs.ext4 >& - && MKFS=(mkfs.ext4 -q -F -j -L) # check for steghide command -v steghide >& - || STEGHIDE=0 # check for resize command -v e2fsck resize2fs >& - || RESIZER=0 # check for KDF auxiliary tools command -v tomb-kdb-pbkdf2 >& - || KDF=0 # check for Swish-E file content indexer command -v swish-e >& - || SWISH=0 # check for QREncode for paper backups of keys command -v qrencode >& - || QRENCODE=0 } # }}} - Commandline interaction # {{{ Key operations # $1 is the encrypted key contents we are checking is_valid_key() { local key="$1" # Unique argument is an encrypted key to test _verbose "is_valid_key" [[ -z $key ]] && key=$TOMBKEY [[ -z $key ]] && { _warning "is_valid_key() called without an argument." return 1 } # If the key file is an image don't check file header [[ -r $TOMBKEYFILE ]] \ && [[ $(file $TOMBKEYFILE) =~ "JP.G" ]] \ && { _message "Key is an image, it might be valid." return 0 } [[ $key =~ "BEGIN PGP" ]] && { _message "Key is valid." return 0 } return 1 } # $1 is a string containing an encrypted key _tomb_key_recover recover_key() { local key="$1" # Unique argument is an encrypted key _warning "Attempting key recovery." TOMBKEY="" # Reset global variable [[ $key =~ "_KDF_" ]] && TOMBKEY+="`print - $key | $head -n 1`\n" TOMBKEY+="-----BEGIN PGP MESSAGE-----\n" TOMBKEY+="$key\n" TOMBKEY+="-----END PGP MESSAGE-----\n" return 0 } # Retrieve the tomb key from the file specified from the command line, # or from stdin if -k - was selected. Run validity checks on the # file. On success, return 0 and print out the full path of the key. # Set global variables TOMBKEY and TOMBKEYFILE. _load_key load_key() { local keyfile="$1" # Unique argument is a keyfile [[ -z $keyfile ]] && keyfile=$(option_value -k) [[ -z $keyfile ]] && { _failure "This operation requires a key file to be specified using the -k option." } [[ $keyfile == "-" ]] && { _verbose "load_key reading from stdin." _message "Waiting for the key to be piped from stdin... " TOMBKEYFILE=stdin TOMBKEY=$(cat) } || { _verbose "load_key argument: ::1 key file::" $keyfile [[ -r $keyfile ]] || _failure "Key not found, specify one using -k." TOMBKEYFILE=$keyfile TOMBKEY=$(cat $TOMBKEYFILE) } _verbose "load_key: ::1 key::" $TOMBKEYFILE is_valid_key $TOMBKEY || { _warning "The key seems invalid or its format is not known by this version of Tomb." _tomb_key_recover $TOMBKEY } # Declared TOMBKEYFILE (path) # Declared TOMBKEY (contents) return 0 } # takes two args just like get_lukskey # prints out the decrypted content # contains tweaks for different gpg versions gpg_decrypt() { # fix for gpg 1.4.11 where the --status-* options don't work ;^/ gpgver=`gpg --version --no-permission-warning | awk '/^gpg/ {print $3}'` gpgpass="$1\n$TOMBKEY" if [ "$gpgver" = "1.4.11" ]; then _verbose "GnuPG is version 1.4.11 - adopting status fix." tomb_secret=`print - "$gpgpass" | \ gpg --batch --passphrase-fd 0 --no-tty --no-options"` ret=$? unset gpgpass else # using status-file in gpg != 1.4.11 # TODO: use mkfifo tmp_create _status=`tmp_new` tomb_secret=`print - "$gpgpass" | \ gpg --batch --passphrase-fd 0 --no-tty --no-options \ --status-fd 2 --no-mdc-warning --no-permission-warning \ --no-secmem-warning 2> $_status` unset gpgpass grep 'DECRYPTION_OKAY' $_status > /dev/null ret=$? fi return $ret } # 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 _verbose "get_lukskey" _password="$1" exhumedkey="" firstline=$(head -n1 <<< $TOMBKEY) # key is KDF encoded if [[ $firstline =~ '^_KDF_' ]]; then _verbose "KDF: ::1 kdf::" $(cut -d_ -f 3 <<<$firstline) case `cut -d_ -f 3 <<<$firstline` in pbkdf2sha1) pbkdf2_param=`cut -d_ -f 4- <<<$firstline | tr '_' ' '` _password=$(tomb-kdb-pbkdf2 ${=pbkdf2_param} 2>/dev/null <<<$_password) ;; *) _failure "No suitable program for KDF ::1 program::." $(cut -f 3 <<<$firstline) unset _password return 1 ;; esac # key needs to be exhumed from an image elif [[ -r $TOMBKEYFILE && $(file $TOMBKEYFILE) =~ "JP.G" ]]; then exhume_key $TOMBKEYFILE "$_password" fi gpg_decrypt "$_password" # saves decrypted content into $tomb_secret ret="$?" _verbose "get_lukskey returns ::1::" $ret return $ret } # 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 saves # the password in the global variable $tomb_password ask_key_password() { [[ -z $TOMBKEYFILE ]] && { _failure "Internal error: ask_key_password() called before load_key()." } _message "A password is required to use key ::1 key::" $TOMBKEYFILE passok=0 tombpass="" if [[ "$1" = "" ]]; then for c in 1 2 3; do if [[ $c == 1 ]]; then tombpass=$(exec_as_user ${TOMBEXEC} askpass \ "Insert password to use key: $TOMBKEYFILE") else tombpass=$(exec_as_user ${TOMBEXEC} askpass \ "Insert password to use key: $TOMBKEYFILE (attempt $c)") fi if [[ $? != 0 ]]; then _warning "User aborted password dialog." return 1 fi get_lukskey "$tombpass" if [ $? = 0 ]; then passok=1; _message "Password OK." break; fi done else # if a second argument is present then the password is already known tombpass="$1" _verbose "ask_key_password with tombpass: ::1 tomb pass::" $tombpass get_lukskey "$tombpass" if [ $? = 0 ]; then passok=1; _message "Password OK."; fi fi # print the password out in case caller needs to know it [[ $passok == 1 ]] || return 1 TOMBPASSWORD=$tombpass return 0 } # change tomb key password change_passwd() { _check_swap load_key _message "Commanded to change password for tomb key ::1 key::" $TOMBKEYFILE local tmpnewkey lukskey c tombpass tombpasstmp tmp_create tmpnewkey=`tmp_new` if option_is_set --tomb-old-pwd; then tomb_old_pwd="`option_value --tomb-old-pwd`" _verbose "tomb-old-pwd = ::1 old pass::" $tomb_old_pwd ask_key_password "$tomb_old_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied." } _success "Changing password for ::1 key file::" $TOMBKEYFILE # here $tomb_secret contains the key material in clear if option_is_set --tomb-pwd; then tomb_new_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 new pass::" $tomb_new_pwd gen_key "$tomb_new_pwd" >> "$tmpnewkey" else gen_key >> "$tmpnewkey" fi if ! is_valid_key "`cat $tmpnewkey`"; then _failure "Error: the newly generated keyfile does not seem valid." else # copy the new key as the original keyfile name cp -f "${tmpnewkey}" $TOMBKEYFILE _success "Your passphrase was successfully updated." fi return 0 } # takes care to encrypt a key # honored options: --kdf --tomb-pwd -o gen_key() { # $1 the password to use, if not set then ask user # -o is the --cipher-algo to use (string taken by GnuPG) local algopt="`option_value -o`" local algo="${algopt:-AES256}" # here user is prompted for key password tombpass="" tombpasstmp="" if [ "$1" = "" ]; then while true; do # 3 tries to write two times a matching password tombpass=`exec_as_user ${TOMBEXEC} askpass "Type the new password to secure your key"` if [[ $? != 0 ]]; then _failure "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 "Type the new password to secure your key (again)"` if [[ $? != 0 ]]; then _failure "User aborted." fi if [ "$tombpasstmp" = "$tombpass" ]; then break; fi unset tombpasstmp unset tombpass done else tombpass="$1" _verbose "gen_key takes tombpass from CLI argument: ::1 tomb pass::" $tombpass fi header="" [[ $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 _failure "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 )) _success "Using KDF, iterations: ::1 microseconds::" $microseconds _message "generating salt" pbkdf2_salt=`tomb-kdb-pbkdf2-gensalt` _message "calculating iterations" pbkdf2_iter=`tomb-kdb-pbkdf2-getiter $microseconds` _message "encoding the password" # 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 $header # TODO: check result of gpg operation cat <& - || _failure "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() { load_key [[ $? = 0 ]] || { _failure "Bury failed for invalid key: ::1 key::" $TOMBKEYFILE } imagefile=$PARAM file $imagefile | grep -i JPEG > /dev/null if [ $? != 0 ]; then _warning "Encode failed: ::1 image file:: is not a jpeg image." $imagefile return 1 fi _success "Encoding key ::1 tomb key:: inside image ::2 image file::" $TOMBKEY $imagefile _message "Please confirm the key password for the encoding" # We ask the password and test if it is the same encoding the # base key, to insure that the same password is used for the # encryption and the steganography. This is a standard enforced # by Tomb, but its not strictly necessary (and having different # password would enhance security). Nevertheless here we prefer # usability. if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi { test $? = 0 } || { _warning "Wrong password supplied." _failure "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 print - "$TOMBKEY" | awk ' /^-----/ {next} /^Version/ {next} {print $0}' \ | steghide embed --embedfile - --coverfile ${imagefile} \ -p ${tomb_password} -z 9 -e serpent cbc if [ $? != 0 ]; then _warning "Encoding error: steghide reports problems." res=1 else _success "Tomb key encoded succesfully into image ::1 image file::" $imagefile res=0 fi return $res } # mandatory 1st arg: the image file where key is supposed to be # optional 2nd arg: the password to use (same as key, internal use) # optional 3rd arg: the key where to save the result (- for stdout) exhume_key() { imagefile="$1" res=1 knownpass="$2" destkey="$3" [[ "$destkey" = "" ]] && { destkey="`option_value -k`" { test "$destkey" = "" } && { # no key output specified: fallback to stdout destkey="-" _message "printing exhumed key on stdout" } } { test -r "$imagefile" } || { _failure "Exhume failed, image file not found: ::1 image file::" $imagefile } [[ `file "$imagefile"` =~ "JP.G" ]] || { _failure "Exhume failed: ::1 image file:: is not a jpeg image." $imagefile } # when a password is passed as argument then always print out # the exhumed key on stdout without further checks (internal use) { test "$knownpass" = "" } || { TOMBKEY=`steghide extract -sf "$imagefile" -p "$knownpass" -xf -` { test $? = 0 } || { _failure "Wrong password or no steganographic key found" } recover_key $TOMBKEY return 0 } { test "$destkey" = "-" } || { if [[ -s "$destkey" ]]; then _warning "File exists: ::1 tomb key::" $destkey { option_is_set -f } || { _warning "Make explicit use of --force to overwrite." _failure "Refusing to overwrite file. Operation aborted." } _warning "Use of --force selected: overwriting." rm -f ${destkey} fi } _message "Trying to exhume a key out of image ::1 image file::" $imagefile if option_is_set --tomb-pwd; then tombpass="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tombpass elif [[ "$tomb_password" != "" ]]; then # password is known already tombpass="$tomb_password" else tombpass=`exec_as_user ${TOMBEXEC} askpass "Insert password to exhume key from $imagefile"` if [[ $? != 0 ]]; then _warning "User aborted password dialog." return 1 fi fi # always steghide required steghide extract -sf ${imagefile} -p ${tombpass} -xf ${destkey} res=$? unset tombpass [[ "$destkey" = "-" ]] && { destkey="stdout" } if [ $res = 0 ]; then _success "Key succesfully exhumed to ::1 key::." $destkey else _warning "Nothing found in ::1 image file::" $imagefile fi return $res } # 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 load_key || _failure "No key specified." local keyname=$(basename $TOMBKEYFILE) pngname="$keyname.qr.png" _success "Rendering a printable QRCode for key: ::1 tomb key file::" $TOMBKEYFILE # we omit armor strings to save space awk ' /^-----/ {next} /^Version/ {next} {print $0}' $TOMBKEYFILE | qrencode --size 4 --level H \ --casesensitive -o "$pngname" { test $? = 0 } || { _failure "QREncode reported an error." } _success "Operation successful:" ls -lh $pngname file $pngname } # }}} - Key handling # {{{ Create # Since version 1.5.3, tomb creation is a three-step process that replaces create_tomb(): # # * dig a .tomb (the large file) using /dev/urandom (takes some minutes at least) # # * forge a .key (the small file) using /dev/random (good entropy needed) # # * lock the .tomb file with the key, binding the key to the tomb (requires dm_crypt format) # Step one - Dig a tomb # # Synopsis: dig_tomb /path/to/tomb -s sizemegabytes # # It will create an empty file to be formatted as a loopback # filesystem. Initially the file is filled with random data taken # from /dev/urandom to improve overall tomb's security and prevent # some attacks aiming at detecting how much data is in the tomb, or # which blocks in the filesystem contain that data. dig_tomb() { local tombpath="$1" # Path to tomb # Require the specification of the size of the tomb (-s) in MB local -i tombsize=$(option_value -s) _message "Commanded to dig tomb ::1 tomb path::" $tombpath [[ -n "$tombpath" ]] || _failure "Missing path to tomb" [[ -n "$tombsize" ]] || _failure "Size argument missing, use -s" [[ $tombsize == <-> ]] || _failure "Size must be an integer (megabytes)" [[ $tombsize -ge 10 ]] || _failure "Tombs can't be smaller than 10 megabytes" _check_swap # Ensure the available memory is safe to use _plot $tombpath # Set TOMB{PATH,DIR,FILE,NAME} [[ -e $TOMBPATH ]] && { _warning "A tomb exists already. I'm not digging here:" _warning " $(ls -lh $TOMBPATH)" return 1 } _success "Creating a new tomb in ::1 tomb path::" $TOMBPATH _message "Generating ::1 tomb file:: of ::2 size::MiB" $TOMBFILE $tombsize # Ensure that file permissions are safe even if interrupted touch $TOMBPATH chmod 0600 $TOMBPATH chown $_UID:$_GID $TOMBPATH _verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]} ${=DD} if=/dev/urandom bs=1048576 count=$tombsize of=$TOMBPATH [[ $? == 0 && -e $TOMBPATH ]] && { _message " $(ls -lh $TOMBPATH)" } || { _warning "Error creating the tomb ::1 tomb path::" $TOMBPATH _failure "Operation aborted." } _success "Done digging ::1 tomb name::" $TOMBNAME _message "Your tomb is not yet ready, you need to forge a key and lock it:" _message "tomb forge ::1 tomb path::.key" $TOMBPATH _message "tomb lock ::1 tomb path:: -k ::1 tomb path::.key" $TOMBPATH return 0 } forge_key() { # can be specified both as simple argument or using -k destkey="$1" { option_is_set -k } && { destkey="`option_value -k`" } { test "$destkey" = "" } && { _warning "A filename needs to be specified using -k to forge a new key." return 1 } _message "Commanded to forge key ::1 key::" $destkey _check_swap # make sure that gnupg doesn't quits with an error before first run { test -r $HOME/.gnupg/pubring.gpg } || { mkdir $HOME/.gnupg touch $HOME/.gnupg/pubring.gpg } { test -r "$destkey" } && { _warning "Forging this key would overwrite an existing file. Operation aborted." _failure "`ls -lh $destkey`" } { option_is_set -o } && { algopt="`option_value -o`" } algo=${algopt:-AES256} _message "Commanded to forge key ::1 key:: with cipher algorithm ::2 algorithm::" $destkey $algo TOMBKEYFILE="$destkey" # Set global variable _message "This operation takes time, keep using this computer on other tasks," _message "once done you will be asked to choose a password for your tomb." _message "To make it faster you can move the mouse around." _message "If you are on a server, you can use an Entropy Generation Daemon." local random_source=/dev/random if option_is_set --use-urandom; then random_source=/dev/urandom fi _verbose "Data dump using ::1:: from ::2 source::" ${DD[1]} $random_source tomb_secret=`${=DD} bs=1 count=256 if=$random_source` { test $? = 0 } || { _warning "Cannot generate encryption key." _failure "Operation aborted." } # here the global var tomb_secret contains the nude secret _success "Choose the password of your key: ::1 tomb key::" $TOMBKEYFILE _message "(You can also change it later using 'tomb passwd'.)" touch $TOMBKEYFILE chown $_UID:$_GID $TOMBKEYFILE chmod 0600 $TOMBKEYFILE tombname="$TOMBKEYFILE" # XXX ??? # the gen_key() function takes care of the new key's encryption if option_is_set --tomb-pwd; then tomb_new_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 new pass::" $tomb_new_pwd gen_key "$tomb_new_pwd" >> $TOMBKEYFILE else gen_key >> $TOMBKEYFILE fi # load the key contents (set global variable) TOMBKEY=$(cat $TOMBKEYFILE) # this does a check on the file header is_valid_key $TOMBKEY || { _warning "The key does not seem to be valid." _warning "Dumping contents to screen:" cat $TOMBKEY _warning "--" umount ${keytmp} rm -r $keytmp _failure "Operation aborted." } _message "Done forging ::1 key file::" $TOMBKEYFILE _success "Your key is ready:" ls -lh $TOMBKEYFILE } # Step three -- Lock tomb # # Synopsis: tomb_lock file.tomb file.tomb.key # # Lock the given tomb with the given key file, in fact formatting the # loopback volume as a LUKS device. it take arguments as the LUKS # cipher to be used lock_tomb_with_key() { local tombpath="$1" # First argument is the path to the tomb local tombkey="$2" # Second argument is the path to the key file [[ -n $tombpath ]] || { _warning "No tomb specified for locking." _warning "Usage: tomb lock file.tomb file.tomb.key" return 1 } _plot $tombpath _message "Commanded to lock tomb ::1 tomb file::" $TOMBFILE [[ -f $TOMBPATH ]] || { _failure "There is no tomb here. You have to it dig first." } _verbose "Tomb found: ::1 tomb path::" $TOMBPATH lo_mount $TOMBPATH nstloop=`lo_new` _verbose "Loop mounted on ::1 mount point::" $nstloop _message "Checking if the tomb is empty (we never step on somebody else's bones)." cryptsetup isLuks ${nstloop} if [ $? = 0 ]; then # is it a LUKS encrypted nest? then bail out and avoid reformatting it _warning "The tomb was already locked with another key." _failure "Operation aborted. I cannot lock an already locked tomb. Go dig a new one." else _message "Fine, this tomb seems empty." fi # load key from options or file load_key { test $? = 0 } || { _failure "Aborting operations: error loading key." } # make sure to call drop_key later # the encryption cipher for a tomb can be set when locking using -o if option_is_set -o; then cipher="`option_value -o`" else cipher="aes-xts-plain64:sha256" # old default was aes-cbc-essiv:sha256 # for more alternatives refer to cryptsetup(8) fi _message "Locking using cipher: ::1 cipher::" $cipher # get the pass from the user and check it if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied." } _success "Locking ::1 tomb file:: with ::2 tomb key file::" $TOMBFILE $TOMBKEYFILE _message "Formatting Luks mapped device." print -n - "$tomb_secret" | \ cryptsetup --key-file - --batch-mode \ --cipher ${cipher} --key-size 256 --key-slot 0 \ luksFormat ${nstloop} if ! [ $? = 0 ]; then _warning "cryptsetup luksFormat returned an error." _failure "Operation aborted." fi print -n - "$tomb_secret" | \ cryptsetup --key-file - \ --cipher ${cipher} luksOpen ${nstloop} tomb.tmp if ! [ $? = 0 ]; then _warning "cryptsetup luksOpen returned an error." _failure "Operation aborted." fi _message "Formatting your Tomb with Ext3/Ext4 filesystem." ${=MKFS} $TOMBNAME /dev/mapper/tomb.tmp if [ $? != 0 ]; then _warning "Tomb format returned an error." _warning "Your tomb ::1 tomb file:: may be corrupted." $TOMBFILE fi # sync cryptsetup luksClose tomb.tmp _message "Done locking ::1 tomb name:: using Luks dm-crypt ::2 cipher::" $TOMBNAME $cipher _success "Your tomb is ready in ::1 tomb path:: and secured with key ::3 tomb key::" \ $TOMBPATH $TOMBKEYFILE } # This function changes the key that locks a tomb change_tomb_key() { local tombkey="$1" # Path to the tomb's key file local tombpath="$2" # Path to the tomb _message "Commanded to reset key for tomb ::1 tomb path::" $tombpath [[ -z "$tombpath" ]] && { _warning "Command 'setkey' needs two arguments: the old key file and the tomb." _warning "I.e: tomb -k new.tomb.key old.tomb.key secret.tomb" _failure "Execution aborted." } _check_swap _plot $tombpath lo_mount $TOMBPATH nstloop=`lo_new` cryptsetup isLuks ${nstloop} # is it a LUKS encrypted nest? we check one more time { test $? = 0 } || { _failure "Not a valid LUKS encrypted volume: ::1 volume::" $TOMBPATH } load_key $tombkey { test $? = 0 } || { _failure "Aborting operations: error loading old key from arguments" } local oldkey=$TOMBKEY local oldkeyfile=$TOMBKEYFILE # we have everything, prepare to mount _success "Changing lock on tomb ::1 tomb name::" $TOMBNAME _message "Old key: ::1 old key::" $oldkey # render the mapper mapdate=`date +%s` # save date of mount in minutes since 1970 mapper="tomb.$TOMBNAME.$mapdate.$(basename $nstloop)" # load the old key if option_is_set --tomb-old-pwd; then tomb_old_pwd="`option_value --tomb-old-pwd`" _verbose "tomb-old-pwd = ::1 old pass::" $tomb_old_pwd ask_key_password "$tomb_old_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied for the old key." } old_secret="$tomb_secret" # luksOpen the tomb (not really mounting, just on the loopback) print -n - "$old_secret" | \ cryptsetup --key-file - luksOpen ${nstloop} ${mapper} { test $? = 0 } || { _failure "Unexpected error in luksOpen." } load_key { test $? = 0 } || { _failure "Aborting operations: error loading new key from -k" } _message "New key: ::1 key file::" $TOMBKEYFILE if option_is_set --tomb-pwd; then tomb_new_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_new_pwd ask_key_password "$tomb_new_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied for the new key." } new_secret="$tomb_secret" # danger zone: due to cryptsetup limitations, in setkey we need # to write the bare unencrypted key on the tmpfs. tmp_create new_secret_file=`tmp_new` print -n - "$new_secret" >> $new_secret_file print -n - "$old_secret"| \ cryptsetup --key-file - luksChangeKey "$nstloop" "$new_secret_file" { test $? = 0 } || { _failure "Unexpected error in luksChangeKey." } cryptsetup luksClose "${mapper}" { test $? = 0 } || { _failure "Unexpected error in luksClose." } _success "Succesfully changed key for tomb: ::1 tomb file::" $TOMBFILE _message "The new key is: ::1 new key::" $newkey return 0 } # backward compatibility # TODO DEPRECATED remove in 2.0 create_tomb() { _verbose "create_tomb(): ::1:: ::2::" ${=@} ${=OLDARGS} [[ "$1" = "" ]] && { _warning "No tomb name specified for creation." return 1 } { test -s "$1" } && { _warning "Creating this tomb would overwrite an existing file." ls -lh "$1" _failure " Operation aborted." } tombfile=`basename $1` tombdir=`dirname $1` # make sure the file has a .tomb extension tombname=${tombfile%%\.*} tombfile=${tombname}.tomb ${TOMBEXEC} dig ${=PARAM} ${TOMBEXEC} forge ${tombdir}/${tombfile}.key { test $? = 0 } || { _failure "Failed to forge key, operation aborted." } ${TOMBEXEC} lock ${tombdir}/${tombfile} -k ${tombdir}/${tombfile}.key { test $? = 0 } || { _failure "Failed to lock tomb with key, operation aborted." } _success "Tomb ::1 tomb name:: succesfully created." $tombname ls -l ${tombfile}* } # }}} - Creation # {{{ Open # $1 = tombfile $2(optional) = mountpoint mount_tomb() { local tombpath="$1" # First argument is the path to the tomb [[ -n "$tombpath" ]] || _failure "No tomb name specified for opening." _message "Commanded to open tomb ::1 tomb name::" $1 _check_swap _plot $tombpath # check file type (if its a Luks fs) file $TOMBPATH | grep -i 'luks encrypted file' 2>&1 > /dev/null [[ $? == 0 ]] || { _warning "::1 tomb file:: is not a valid tomb file" $TOMBFILE _failure "Operation aborted." } _verbose "Tomb found: ::1 tomb path::" $TOMBPATH # load_key called here load_key ######## { test $? = 0 } || { _failure "Aborting operations: error loading key ::1 key::" $tombkey } if [ "$2" = "" ]; then tombmount=/media/$TOMBFILE _message "Mountpoint not specified, using default: ::1 mount point::" $tombmount else tombmount=$2 fi # check if its already open mount -l | grep "${tombfile}.*\[$tombname\]$" 2>&1 > /dev/null if [ $? = 0 ]; then _warning "::1 tomb name:: is already open." $TOMBNAME _message "Here below its status is reported:" list_tombs $TOMBNAME return 0 fi _success "Opening ::1 tomb file:: on ::2 mount point::" $TOMBFILE $tombmount lo_mount $TOMBPATH nstloop=`lo_new` cryptsetup isLuks ${nstloop} if [ $? != 0 ]; then # is it a LUKS encrypted nest? see cryptsetup(1) _warning "::1 tomb file:: is not a valid Luks encrypted storage file." $TOMBFILE return 1 fi _message "This tomb is a valid LUKS encrypted device." luksdump="`cryptsetup luksDump ${nstloop}`" tombdump=(`print $luksdump | awk ' /^Cipher name/ {print $3} /^Cipher mode/ {print $3} /^Hash spec/ {print $3}'`) _message "Cipher is \"::1 cipher::\" mode \"::2 mode::\" hash \"::3 hash::\"" $tombdump[1] $tombdump[2] $tombdump[3] slotwarn=`print $luksdump | awk ' BEGIN { zero=0 } /^Key slot 0/ { zero=1 } /^Key slot.*ENABLED/ { if(zero==1) print "WARN" }'` { test "$slotwarn" = "WARN" } && { _warning "Multiple key slots are enabled on this tomb. Beware: there can be a backdoor." } # save date of mount in minutes since 1970 mapdate=`date +%s` mapper="tomb.${tombname}.${mapdate}.`basename $nstloop`" _verbose "dev mapper device: ::1 mapper::" $mapper _verbose "Tomb key: ::1 key file::" $TOMBKEYFILE # take the name only, strip extensions _verbose "Tomb name: ::1 tomb name:: (to be engraved)" $TOMBNAME if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied." } print -n - "$tomb_secret" | \ cryptsetup --key-file - luksOpen ${nstloop} ${mapper} if ! [ -r /dev/mapper/${mapper} ]; then _failure "Failure mounting the encrypted file." fi # preserve the loopdev after exit lo_preserve "$nstloop" # array: [ cipher, keysize, loopdevice ] tombstat=(`cryptsetup status ${mapper} | awk ' /cipher:/ {print $2} /keysize:/ {print $2} /device:/ {print $2}'`) _success "Success unlocking tomb ::1 tomb name::" $TOMBNAME _verbose "Key size is ::1 size:: for cipher ::2 cipher::" $tombstat[2] $tombstat[1] _message "Checking filesystem via ::1::" $tombstat[3] fsck -p -C0 /dev/mapper/${mapper} _verbose "Tomb engraved as ::1 tomb name::" $TOMBNAME tune2fs -L $TOMBNAME /dev/mapper/${mapper} > /dev/null # we need root from here on mkdir -p $tombmount mount -o $MOUNTOPTS /dev/mapper/${mapper} ${tombmount} chown $_UID:$_GID ${tombmount} chmod 0711 ${tombmount} _success "Success opening ::1 tomb file:: on ::2 mount point::" $TOMBFILE $tombmount # print out when was opened the last time, by whom and where { test -r ${tombmount}/.last } && { tombtty="`cat ${tombmount}/.tty`" tombhost="`cat ${tombmount}/.host`" tombuid="`cat ${tombmount}/.uid`" tomblast="`cat ${tombmount}/.last`" tombuser=`awk -F: '/:'"$tombuid"':/ {print $1}' /etc/passwd` _message "Last visit by ::1 user::(::2 tomb build::) from ::3 tty:: on ::4 host::" $tombuser $tombuid $tombtty $tombhost _message "on date ::1 date::" $(date --date @$tomblast +%c) } # write down the UID and TTY that opened the tomb rm -f ${tombmount}/.uid echo $_UID > ${tombmount}/.uid rm -f ${tombmount}/.tty echo $_TTY > ${tombmount}/.tty # also the hostname rm -f ${tombmount}/.host echo `hostname` > ${tombmount}/.host # and the "last time opened" information # in minutes since 1970, this is printed at next open rm -f ${tombmount}/.last echo "`date +%s`" > ${tombmount}/.last # human readable: date --date=@"`cat .last`" +%c # process bind-hooks (mount -o bind of directories) # and post-hooks (execute on open) if ! option_is_set -n ; then exec_safe_bind_hooks ${tombmount} exec_safe_post_hooks ${tombmount} open fi return 0 } # ## Hooks execution exec_safe_bind_hooks() { if [[ -n ${(k)OPTS[-o]} ]]; then MOUNTOPTS=${OPTS[-o]} fi local MOUNTPOINT="${1}" local ME=${SUDO_USER:-$(whoami)} local HOME=$(awk -v a="$ME" -F ':' '{if ($1 == a) print $6}' /etc/passwd 2>/dev/null) if [ $? -ne 0 ]; then _warning "How pitiful! A tomb, and no HOME." return 1 fi if [ -z "$MOUNTPOINT" -o ! -d "$MOUNTPOINT" ]; then _warning "Cannot exec bind hooks without a mounted tomb." return 1 fi if ! [ -r "$MOUNTPOINT/bind-hooks" ]; then _verbose "bind-hooks not found in ::1 mount point::" $MOUNTPOINT return 1 fi typeset -al mounted typeset -Al maps maps=($(<"$MOUNTPOINT/bind-hooks")) for dir in ${(k)maps}; do if [ "${dir[1]}" = "/" -o "${dir[1,2]}" = ".." ]; then _warning "bind-hooks map format: local/to/tomb local/to/\$HOME" continue fi if [ "${${maps[$dir]}[1]}" = "/" -o "${${maps[$dir]}[1,2]}" = ".." ]; then _warning "bind-hooks map format: local/to/tomb local/to/\$HOME. Rolling back" for dir in ${mounted}; do umount $dir; done return 1 fi if [ ! -r "$HOME/${maps[$dir]}" ]; then _warning "bind-hook target not existent, skipping ::1 home::/::2 subdir::" $HOME ${maps[$dir]} elif [ ! -r "$MOUNTPOINT/$dir" ]; then _warning "bind-hook source not found in tomb, skipping ::1 mount point::/::2 subdir::" $MOUNTPOINT $dir else mount -o bind,$MOUNTOPTS $MOUNTPOINT/$dir $HOME/${maps[$dir]} mounted+=("$HOME/${maps[$dir]}") fi done } # Post mount hooks exec_safe_post_hooks() { local mnt=$1 # first argument is where the tomb is mounted local ME=${SUDO_USER:-$(whoami)} if ! [ -x ${mnt}/post-hooks ]; then return; fi # if 'post-hooks' is found inside the tomb, check it: if it is an # executable, launch it as a user this might need a dialog for # security on what is being run, however we expect you know well # what is inside your tomb. this feature opens the possibility to # make encrypted executables. cat ${mnt}/post-hooks | head -n1 | grep '^#!/' if [ $? = 0 ]; then _success "Post hooks found, executing as user ::1 user name::." $SUDO_USER exec_as_user ${mnt}/post-hooks "$2" "$1" fi } # }}} - Tomb open # {{{ List # list all tombs mounted in a readable format # $1 is optional, to specify a tomb list_tombs() { # list all open tombs mounted_tombs=(`list_tomb_mounts $1`) { test ${#mounted_tombs} = 0 } && { _failure "I can't see any ::1 status:: tomb, may they all rest in peace." ${1:-open} } for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} tombfs=${t[(ws:;:)3]} tombfsopts=${t[(ws:;:)4]} tombloop=${mapper[(ws:.:)4]} # calculate tomb size ts=`df -hP /dev/mapper/$mapper | awk "/mapper/"' { print $2 ";" $3 ";" $4 ";" $5 }'` tombtot=${ts[(ws:;:)1]} tombused=${ts[(ws:;:)2]} tombavail=${ts[(ws:;:)3]} tombpercent=${ts[(ws:;:)4]} tombp=${tombpercent%%%} tombsince=`date --date=@${mapper[(ws:.:)3]} +%c` # find out who opens it from where { test -r ${tombmount}/.tty } && { tombtty="`cat ${tombmount}/.tty`" tombhost="`cat ${tombmount}/.host`" tombuid="`cat ${tombmount}/.uid`" tombuser=`awk -F: '/:'"$tombuid"':/ {print $1}' /etc/passwd` } if option_is_set --get-mountpoint; then echo $tombmount continue fi # breaking up such strings is good for translation print -n "$fg[green]$tombname" print -n "$fg[white] open on " print -n "$fg_bold[white]$tombmount" print -n "$fg_no_bold[white] using " print "$fg_bold[white]$tombfs $tombfsopts" print -n "$fg_no_bold[green]$tombname" print -n "$fg_no_bold[white] open since " print "$fg_bold[white]$tombsince$fg_no_bold[white]" { test "$tombtty" = "" } || { print -n "$fg_no_bold[green]$tombname" print -n "$fg_no_bold[white] open by " print -n "$fg_bold[white]$tombuser" print -n "$fg_no_bold[white] from " print -n "$fg_bold[white]$tombtty" print -n "$fg_no_bold[white] on " print "$fg_bold[white]$tombhost" } print -n "$fg_no_bold[green]$tombname" print -n "$fg[white] size " print -n "$fg_bold[white]$tombtot" print -n "$fg_no_bold[white] of which " print -n "$fg_bold[white]$tombused" print -n "$fg_no_bold[white] used: " print -n "$fg_bold[white]$tombavail" print -n "$fg_no_bold[white] free (" print -n "$fg_bold[white]$tombpercent" print "$fg_no_bold[white] full)" if [[ ${tombp} -ge 90 ]]; then print -n "$fg_no_bold[green]$tombname" print "$fg_bold[red] Your tomb is almost full!" fi # now check hooks mounted_hooks=(`list_tomb_binds $tombname`) for h in ${mounted_hooks}; do print -n "$fg_no_bold[green]$tombname" print -n "$fg_no_bold[white] hooks " # print -n "$fg_bold[white]`basename ${h[(ws:;:)1]}`" # print -n "$fg_no_bold[white] on " print "$fg_bold[white]${h[(ws:;:)2]}$fg_no_bold[white]" done done } # print out an array of mounted tombs (internal use) # format is semi-colon separated list of attributes # if 1st arg is supplied, then list only that tomb # # String positions in the semicolon separated array: # # 1. full mapper path # # 2. mountpoint # # 3. filesystem type # # 4. mount options # # 5. tomb name list_tomb_mounts() { if [ "$1" = "" ]; then # list all open tombs mount -l \ | awk ' BEGIN { main="" } /^\/dev\/mapper\/tomb/ { if(main==$1) next; print $1 ";" $3 ";" $5 ";" $6 ";" $7 main=$1 } ' else # list a specific tomb mount -l \ | awk -vtomb="[$1]" ' BEGIN { main="" } /^\/dev\/mapper\/tomb/ { if($7!=tomb) next; if(main==$1) next; print $1 ";" $3 ";" $5 ";" $6 ";" $7 main=$1 } ' fi } # list_tomb_binds # print out an array of mounted bind hooks (internal use) # format is semi-colon separated list of attributes # needs an argument: name of tomb whose hooks belong list_tomb_binds() { if [ "$1" = "" ]; then _failure "Internal error: list_tomb_binds called without argument."; fi # list bind hooks on util-linux 2.20 (Debian 7) mount -l \ | awk -vtomb="$1" ' BEGIN { main="" } /^\/dev\/mapper\/tomb/ { if($7!=tomb) next; if(main=="") { main=$1; next; } if(main==$1) print $1 ";" $3 ";" $5 ";" $6 ";" $7 } ' # list bind hooks on util-linux 2.17 (Debian 6) tombmount=`mount -l \ | awk -vtomb="$1" ' /^\/dev\/mapper\/tomb/ { if($7!=tomb) next; print $3; exit; }'` mount -l | grep "^$tombmount" \ | awk -vtomb="$1" ' /bind/ { print $1 ";" $3 ";" $5 ";" $6 ";" $7 }' } # }}} - Tomb list # {{{ Index and search # index files in all tombs for search # $1 is optional, to specify a tomb index_tombs() { { command -v updatedb >& - } || { _failure "Cannot index tombs on this system: updatedb (mlocate) not installed." } updatedbver=`updatedb --version | grep '^updatedb'` [[ "$updatedbver" =~ "GNU findutils" ]] && { _warning "Cannot use GNU findutils for index/search commands." } [[ "$updatedbver" =~ "mlocate" ]] || { _failure "Index command needs 'mlocate' to be installed." } _verbose "$updatedbver" mounted_tombs=(`list_tomb_mounts $1`) { test ${#mounted_tombs} = 0 } && { if [ $1 ]; then _failure "There seems to be no open tomb engraved as [::1::]" $1 else _failure "I can't see any open tomb, may they all rest in peace." fi } _success "Creating and updating search indexes." # start the LibreOffice document converter if installed { command -v unoconv >& - } && { unoconv -l 2>/dev/null & _verbose "unoconv listener launched." sleep 1 } for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} { test -r ${tombmount}/.noindex } && { _message "Skipping ::1 tomb name:: (.noindex found)." $tombname continue } _message "Indexing ::1 tomb name:: filenames..." $tombname updatedb -l 0 -o ${tombmount}/.updatedb -U ${tombmount} # here we use swish to index file contents [[ $SWISH == 1 ]] && { _message "Indexing ::1 tomb name:: contents..." $tombname tmp_create swishrc=`tmp_new` cat < $swishrc # index directives DefaultContents TXT* IndexDir $tombmount IndexFile $tombmount/.swish # exclude images FileRules filename regex /\.jp.?g/i FileRules filename regex /\.png/i FileRules filename regex /\.gif/i FileRules filename regex /\.tiff/i FileRules filename regex /\.svg/i FileRules filename regex /\.xcf/i FileRules filename regex /\.eps/i FileRules filename regex /\.ttf/i # exclude audio FileRules filename regex /\.mp3/i FileRules filename regex /\.ogg/i FileRules filename regex /\.wav/i FileRules filename regex /\.mod/i FileRules filename regex /\.xm/i # exclude video FileRules filename regex /\.mp4/i FileRules filename regex /\.avi/i FileRules filename regex /\.ogv/i FileRules filename regex /\.ogm/i FileRules filename regex /\.mkv/i FileRules filename regex /\.mov/i # exclude system FileRules filename is ok FileRules filename is lock FileRules filename is control FileRules filename is status FileRules filename is proc FileRules filename is sys FileRules filename is supervise FileRules filename regex /\.asc$/i FileRules filename regex /\.gpg$/i # pdf and postscript FileFilter .pdf pdftotext "'%p' -" FileFilter .ps ps2txt "'%p' -" # compressed files FileFilterMatch lesspipe "%p" /\.tgz$/i FileFilterMatch lesspipe "%p" /\.zip$/i FileFilterMatch lesspipe "%p" /\.gz$/i FileFilterMatch lesspipe "%p" /\.bz2$/i FileFilterMatch lesspipe "%p" /\.Z$/ # spreadsheets FileFilterMatch unoconv "-d spreadsheet -f csv --stdout %P" /\.xls.*/i FileFilterMatch unoconv "-d spreadsheet -f csv --stdout %P" /\.xlt.*/i FileFilter .ods unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .ots unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .dbf unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .dif unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .uos unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .sxc unoconv "-d spreadsheet -f csv --stdout %P" # word documents FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.doc.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.odt.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.rtf.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.tex$/i # native html support IndexContents HTML* .htm .html .shtml IndexContents XML* .xml EOF _verbose "Using swish-e to create index." swish-e -c $swishrc -S fs -v3 rm -f $swishrc } _message "Search index updated." done } search_tombs() { { command -v locate >& - } || { _failure "Cannot index tombs on this system: updatedb (mlocate) not installed." } updatedbver=`updatedb --version | grep '^updatedb'` [[ "$updatedbver" =~ "GNU findutils" ]] && { _warning "Cannot use GNU findutils for index/search commands." } [[ "$updatedbver" =~ "mlocate" ]] || { _failure "Index command needs 'mlocate' to be installed." } _verbose "$updatedbver" # list all open tombs mounted_tombs=(`list_tomb_mounts`) if [ ${#mounted_tombs} = 0 ]; then _failure "I can't see any open tomb, may they all rest in peace."; fi _success "Searching for: ::1::" ${(f)@} for t in ${mounted_tombs}; do _verbose "Checking for index: ::1::" ${t} mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} if [ -r ${tombmount}/.updatedb ]; then # use mlocate to search hits on filenames _message "Searching filenames in tomb ::1 tomb name::" $tombname locate -d ${tombmount}/.updatedb -e -i "${(f)@}" _message "Matches found: ::1 matches::" $(locate -d ${tombmount}/.updatedb -e -i -c ${(f)@}) # use swish-e to search over contents [[ $SWISH == 1 && -r $tombmount/.swish ]] && { _message "Searching contents in tomb ::1 tomb name::" $tombname swish-e -w ${=@} -f $tombmount/.swish -H0 } else _warning "Skipping tomb ::1 tomb name::: not indexed." $tombname _warning "Run 'tomb index' to create indexes." fi done _message "Search completed." } # }}} - Index and search # {{{ Resize # resize tomb file size resize_tomb() { local tombpath="$1" # First argument is the path to the tomb _message "Commanded to resize tomb ::1 tomb name:: to ::2 size:: megabytes." $1 $OPTS[-s] [[ -z "$tombpath" ]] && _failure "No tomb name specified for resizing." [[ ! -r $tombpath ]] && _failure "Cannot find ::1::" $tombpath newtombsize="`option_value -s`" { test "$newtombsize" = "" } && { _failure "Aborting operations: new size was not specified, use -s" } _plot $tombpath # Set TOMB{PATH,DIR,FILE,NAME} # load key from options or file load_key ######## local oldtombsize=$(( `stat -c %s "$TOMBPATH" 2>/dev/null` / 1048576 )) local mounted_tomb=`mount -l | awk -vtomb="[$TOMBNAME]" '/^\/dev\/mapper\/tomb/ { if($7==tomb) print $1 }'` if [ "$mounted_tomb" ]; then _failure "Please close the tomb ::1 tomb name:: before trying to resize it." $TOMBNAME fi if ! [ "$newtombsize" ] ; then _failure "You must specify the new size of ::1 tomb name::" $TOMBNAME elif [[ $newtombsize != <-> ]]; then _failure "Size is not an integer." elif [ "$newtombsize" -le "$oldtombsize" ]; then _failure "The new size must be greater then old tomb size." fi delta="$(( $newtombsize - $oldtombsize ))" _message "Generating ::1 tomb file:: of ::2 size::MiB" $TOMBFILE $newtombsize _verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]} ${=DD} if=/dev/urandom bs=1048576 count=${delta} >> $TOMBPATH { test $? = 0 } || { _failure "Error creating the extra resize ::1 size::, operation aborted." $tmp_resize } if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi { test $? = 0 } || { _failure "No valid password supplied." } lo_mount "${tombdir}/${tombfile}" nstloop=`lo_new` mapdate=`date +%s` mapper="tomb.${tombname}.${mapdate}.`basename $nstloop`" print -n - "$tomb_secret" | \ cryptsetup --key-file - luksOpen ${nstloop} ${mapper} if ! [ -r /dev/mapper/${mapper} ]; then _failure "Failure mounting the encrypted file." fi cryptsetup resize "${mapper}" if [ $? != 0 ]; then _failure "cryptsetup failed to resize ::1 mapper::" $mapper fi e2fsck -p -f /dev/mapper/${mapper} if [ $? != 0 ]; then _failure "e2fsck failed to check ::1 mapper::" $mapper fi resize2fs /dev/mapper/${mapper} if [ $? != 0 ]; then _failure "resize2fs failed to resize ::1 mapper::" $mapper fi sleep 1 # needs to settle a bit # close and free the loop device cryptsetup luksClose "${mapper}" return 0 } # }}} # {{{ Close umount_tomb() { local tombs how_many_tombs local pathmap mapper tombname tombmount loopdev local ans pidk pname if [ "$1" = "all" ]; then mounted_tombs=(`list_tomb_mounts`) else mounted_tombs=(`list_tomb_mounts $1`) fi { test ${#mounted_tombs} = 0 } && { _warning "There is no open tomb to be closed." return 1 } { test ${#mounted_tombs} -gt 1 } && { test "$1" = "" } && { _warning "Too many tombs mounted, please specify one (see tomb list)" _warning "or issue the command 'tomb close all' to close them all." return 1 } _message "Tomb close ::1::" $1 for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} tombfs=${t[(ws:;:)3]} tombfsopts=${t[(ws:;:)4]} tombloop=${mapper[(ws:.:)4]} _verbose "Name: ::1 tomb name::" $tombname _verbose "Mount: ::1 mount point::" $tombmount _verbose "Mapper: ::1 mapper::" $mapper { test -e "$mapper" } && { _warning "Tomb not found: ::1 tomb file::" $1 _warning "Please specify an existing tomb." return 0 } if [ $SLAM ]; then _success "Slamming tomb ::1 tomb name:: mounted on ::2 mount point::" $tombname $tombmount _message "Kill all processes busy inside the tomb." if ! slam_tomb "$tombmount"; then _warning "Cannot slam the tomb ::1 tomb name::" $tombname return 1 fi else _message "Closing tomb ::1 tomb name:: mounted on ::2 mount point::" $tombname $tombmount fi # check if there are binded dirs and close them bind_tombs=(`list_tomb_binds $tombname`) for b in ${bind_tombs}; do bind_mapper="${b[(ws:;:)1]}" bind_mount="${b[(ws:;:)2]}" _message "Closing tomb bind hook: ::1 hook::" $bind_mount umount $bind_mount if [[ $? != 0 ]]; then if [ $SLAM ]; then _success "Slamming tomb: killing all processes using this hook." slam_tomb "$bind_mount" if [[ $? == 1 ]]; then _warning "Cannot slam the bind hook ::1 hook::" $bind_mount return 1 fi umount $bind_mount else _warning "Tomb bind hook ::1 hook:: is busy, cannot close tomb." $bind_mount fi fi done # Execute post-hooks for eventual cleanup if ! option_is_set -n ; then exec_safe_post_hooks ${tombmount%%/} close fi _verbose "Performing umount of ::1 mount point::" $tombmount umount ${tombmount} if ! [ $? = 0 ]; then _warning "Tomb is busy, cannot umount!" else # this means we used a "default" mount point { test "${tombmount}" = "/media/${tombname}.tomb" } && { rmdir ${tombmount} } fi cryptsetup luksClose $mapper { test $? = 0 } || { _warning "Error occurred in cryptsetup luksClose ::1 mapper::" $mapper return 1 } losetup -d "/dev/$tombloop" _success "Tomb ::1 tomb name:: closed: your bones will rest in peace." $tombname done # loop across mounted tombs return 0 } # Kill all processes using the tomb slam_tomb() { # $1 = tomb mount point if [[ -z `fuser -m "$1" 2>/dev/null` ]]; then return 0 fi #Note: shells are NOT killed by INT or TERM, but they are killed by HUP for s in TERM HUP KILL; do _verbose "Sending ::1:: to processes inside the tomb:" $s if option_is_set -D; then ps -fp `fuser -m /media/a.tomb 2>/dev/null`| while read line; do _verbose $line done fi fuser -s -m "$1" -k -M -$s if [[ -z `fuser -m "$1" 2>/dev/null` ]]; then return 0 fi if ! option_is_set -f; then sleep 3 fi done return 1 } # }}} - Tomb close # {{{ Main routine main() { local -A subcommands_opts ### Options configuration # # Hi, dear developer! Are you trying to add a new subcommand, or # to add some options? Well, keep in mind that option names are # global: they cannot bear a different meaning or behaviour across # subcommands. # # For example, "-s" means "size" and accepts one argument. If you # are tempted to add an alternate option "-s" (e.g., to mean # "silent", and that doesn't accept any argument) DON'T DO IT! # # There are two reasons for that: # I. Usability; users expect that "-s" is "size" # II. Option parsing WILL EXPLODE if you do this kind of bad # things (it will complain: "option defined more than once") # # If you want to use the same option in multiple commands then you # can only use the non-abbreviated long-option version like: # -force and NOT -f # main_opts=(q -quiet=q D -debug=D h -help=h v -version=v U: -uid=U G: -gid=G T: -tty=T -no-color -unsecure-dev-mode) subcommands_opts[__default]="" subcommands_opts[open]="f -force n -nohook=n k: -key=k -kdf: o: -ignore-swap -sudo-pwd: -tomb-pwd: " subcommands_opts[mount]=${subcommands_opts[open]} subcommands_opts[create]="" # deprecated, will issue warning subcommands_opts[forge]="f -force -ignore-swap k: -key=k -kdf: o: -tomb-pwd: -use-urandom " subcommands_opts[dig]="f -force -ignore-swap s: -size=s " subcommands_opts[lock]="f -force -ignore-swap k: -key=k -kdf: o: -sudo-pwd: -tomb-pwd: " subcommands_opts[setkey]="k: -key=k f -force -ignore-swap -kdf: -sudo-pwd: -tomb-old-pwd: -tomb-pwd: " subcommands_opts[engrave]="k: -key=k " subcommands_opts[passwd]="k: -key=k f -force -ignore-swap -kdf: -tomb-old-pwd: -tomb-pwd: " subcommands_opts[close]="-sudo-pwd: " subcommands_opts[help]="" subcommands_opts[slam]="" subcommands_opts[list]="-get-mountpoint " subcommands_opts[index]="" subcommands_opts[search]="" subcommands_opts[help]="" subcommands_opts[bury]="f -force k: -key=k -tomb-pwd: " subcommands_opts[exhume]="f -force k: -key=k -tomb-pwd: " # subcommands_opts[decompose]="" # subcommands_opts[recompose]="" # subcommands_opts[install]="" subcommands_opts[askpass]="" subcommands_opts[source]="" subcommands_opts[resize]="f -force -ignore-swap s: -size=s k: -key=k -tomb-pwd: " subcommands_opts[check]="-ignore-swap " # subcommands_opts[translate]="" ### Detect subcommand local -aU every_opts #every_opts behave like a set; that is, an array with unique elements for optspec in $subcommands_opts$main_opts; do for opt in ${=optspec}; do every_opts+=${opt} done done local -a oldstar oldstar=($argv) #### detect early: useful for --optiion-parsing zparseopts -M -D -Adiscardme ${every_opts} if [[ -n ${(k)discardme[--option-parsing]} ]]; then echo $1 if [[ -n "$1" ]]; then return 1 fi return 0 fi unset discardme if ! zparseopts -M -E -D -Adiscardme ${every_opts}; then _failure "Error parsing." return 127 fi unset discardme subcommand=$1 if [[ -z $subcommand ]]; then subcommand="__default" fi if [[ -z ${(k)subcommands_opts[$subcommand]} ]]; then _warning "There's no such command \"::1 subcommand::\"." $subcommand exitv=127 _failure "Please try -h for help." fi argv=(${oldstar}) unset oldstar ### Parsing global + command-specific options # zsh magic: ${=string} will split to multiple arguments when spaces occur set -A cmd_opts ${main_opts} ${=subcommands_opts[$subcommand]} # if there is no option, we don't need parsing if [[ -n $cmd_opts ]]; then zparseopts -M -E -D -AOPTS ${cmd_opts} if [[ $? != 0 ]]; then _warning "Some error occurred during option processing." exitv=127 _failure "See \"tomb help\" for more info." fi fi #build PARAM (array of arguments) and check if there are unrecognized options ok=0 PARAM=() for arg in $*; do if [[ $arg == '--' || $arg == '-' ]]; then ok=1 continue #it shouldnt be appended to PARAM elif [[ $arg[1] == '-' ]]; then if [[ $ok == 0 ]]; then exitv=127 _failure "Unrecognized option ::1 arg:: for subcommand ::2 subcommand::" $arg $subcommand fi fi PARAM+=$arg done #first parameter actually is the subcommand: delete it and shift if [[ $subcommand != '__default' ]]; then PARAM[1]=() shift fi ### End parsing command-specific options if ! option_is_set --no-color; then autoload colors; colors fi if ! option_is_set --unsecure-dev-mode; then for opt in --sudo-pwd --tomb-pwd --use-urandom --tomb-old-pwd; do if option_is_set $opt; then exitv=127 _failure "You specified option ::1 option::, which is DANGEROUS and should only be used for testing\nIf you really want so, add --unsecure-dev-mode" $opt fi done fi # when we run as root, we remember the original uid:gid # to set permissions for the calling user and drop privileges if option_is_set -U; then _UID="`option_value -U`"; fi if option_is_set -G; then _GID="`option_value -G`"; fi if option_is_set -T; then _TTY="`option_value -T`"; fi [[ "$PARAM" == "" ]] && { _verbose "Tomb command: ::1 subcommand::" $subcommand } || { _verbose "Tomb command: ::1 subcommand:: ::2 param::" $subcommand $PARAM } [[ $_UID == "" ]] || { _verbose "Caller: uid[::1 uid::], gid[::2 gid::], tty[::3 tty::]." $_UID $_GID $_TTY } case "$subcommand" in # new creation in three steps forge) check_priv forge_key ${=PARAM} ;; dig) dig_tomb ${=PARAM} ;; lock) check_priv lock_tomb_with_key ${=PARAM} ;; setkey) check_priv change_tomb_key ${=PARAM} ;; engrave) [[ $QRENCODE == 0 ]] && { _failure "QREncode not installed: cannot engrave keys on paper." } engrave_key ${=PARAM} ;; # backward compat create) _warning "The create command is deprecated, please use dig, forge and lock instead." _warning "For more informations see Tomb's manual page (man tomb)." ;; mount|open) check_priv mount_tomb $PARAM[1] $PARAM[2] ;; umount|close|slam) check_priv [ "$subcommand" = "slam" ] && SLAM=1 umount_tomb $PARAM[1] ;; passwd) change_passwd $PARAM[1] ;; list) list_tombs $PARAM[1] ;; index) index_tombs $PARAM[1] ;; search) search_tombs ${=PARAM} ;; help) usage ;; bury) [[ $STEGHIDE == 0 ]] && { _failure "Steghide not installed: cannot bury keys into images." } bury_key $PARAM[1] ;; exhume) [[ $STEGHIDE == 0 ]] && { _failure "Steghide not installed: cannot exhume keys from images." } exhume_key $PARAM[1] ;; resize) [[ $RESIZER == 0 ]] && { _failure "Resize2fs not installed: cannot resize tombs." } check_priv resize_tomb $PARAM[1] ;; # internal commands useful to developers 'source') return 0 ;; askpass) ask_password $PARAM[1] $PARAM[2] ;; __default) _print "Tomb ::1 version:: - a strong and gentle undertaker for your secrets" $VERSION _print "\000" _print " Copyright (C) 2007-2014 Dyne.org Foundation, License GNU GPL v3+" _print " This is free software: you are free to change and redistribute it" _print " The latest Tomb sourcecode is published on " _print "\000" option_is_set -v && { _print " This source code is distributed in the hope that it will be useful," _print " but WITHOUT ANY WARRANTY; without even the implied warranty of" _print " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." _print " Please refer to the GNU Public License for more details." _print "\000" _print "System utils:" _print "\000" cat <