2016-12-29 12:49:03 +00:00
#!/usr/bin/env zsh
2010-08-22 13:04:19 +00:00
#
2011-01-13 13:37:52 +00:00
# Tomb, the Crypto Undertaker
2010-08-22 13:04:19 +00:00
#
2013-05-28 09:57:58 +00:00
# A commandline tool to easily operate encryption of secret data
2013-05-28 10:53:26 +00:00
#
2013-05-28 09:57:58 +00:00
# {{{ License
2011-12-01 19:04:56 +00:00
2024-01-23 23:31:49 +00:00
# Copyright (C) 2007-2024 Dyne.org Foundation
2013-05-29 15:21:36 +00:00
#
# Tomb is designed, written and maintained by Denis Roio <jaromil@dyne.org>
2010-08-22 13:04:19 +00:00
#
2020-11-17 12:58:07 +00:00
# Please refer to the AUTHORS file for more information.
2010-08-22 13:04:19 +00:00
#
2014-10-21 16:19:57 +00:00
# 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.
2014-11-23 17:25:42 +00:00
#
2014-10-21 16:19:57 +00:00
# This source code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
2018-01-03 19:27:14 +00:00
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Please refer
2014-10-21 16:19:57 +00:00
# to the GNU Public License for more details.
2014-11-23 17:25:42 +00:00
#
2014-10-21 16:19:57 +00:00
# You should have received a copy of the GNU Public License along with
2020-11-17 12:58:07 +00:00
# this source code; if not, , see <https://www.gnu.org/licenses/>.
2013-05-28 09:57:58 +00:00
# }}} - License
# {{{ Global variables
2011-12-01 19:04:56 +00:00
2024-07-12 10:35:57 +00:00
typeset VERSION="2.11.0"
typeset DATE="Jul/2024"
2014-11-14 16:42:49 +00:00
typeset TOMBEXEC=$0
2021-01-01 20:58:23 +00:00
typeset TMPDIR=${${TMPPREFIX%/*}:-/tmp}
2014-11-23 13:49:41 +00:00
# TODO: configure which tmp dir to use from a cli flag
2014-10-24 01:48:05 +00:00
# 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
2011-08-02 00:10:31 +00:00
typeset -a OLDARGS
2014-11-14 19:12:30 +00:00
for arg in "${(@)argv}"; do OLDARGS+=("$arg"); done
2014-10-21 16:24:47 +00:00
# Special command requirements
2021-10-20 14:27:27 +00:00
typeset -a DD WIPE PINENTRY SUDO
2014-10-21 16:24:47 +00:00
DD=(dd)
WIPE=(rm -f)
2014-11-15 01:36:31 +00:00
# load zsh regex module
zmodload zsh/mapfile
2015-01-17 01:14:38 +00:00
zmodload -F zsh/stat b:zstat
2014-11-15 01:36:31 +00:00
2014-11-23 17:26:06 +00:00
# make sure variables aren't exported
unsetopt allexport
2014-10-24 01:48:05 +00:00
# Flag optional commands if available (see _ensure_dependencies())
2014-10-29 13:26:43 +00:00
typeset -i KDF=1
typeset -i STEGHIDE=1
2019-02-21 09:28:21 +00:00
typeset -i CLOAKIFY=1
typeset -i DECLOAKIFY=1
2014-10-29 13:26:43 +00:00
typeset -i RESIZER=1
2024-05-12 21:29:14 +00:00
typeset -i RECOLL=1
2014-10-29 13:26:43 +00:00
typeset -i QRENCODE=1
2014-10-21 16:33:59 +00:00
# Default mount options
2018-01-03 19:27:14 +00:00
typeset MOUNTOPTS="rw,noatime,nodev"
2014-08-25 19:01:50 +00:00
2014-10-22 22:39:47 +00:00
# Makes glob matching case insensitive
2014-08-25 22:54:41 +00:00
unsetopt CASE_MATCH
2018-01-03 19:27:14 +00:00
typeset -AH OPTS # Command line options (see main())
2013-03-29 11:51:43 +00:00
2014-10-24 01:48:05 +00:00
# Command context (see _whoami())
2021-01-01 21:35:52 +00:00
typeset -H _USER # Running username
2018-01-03 19:27:14 +00:00
typeset -Hi _UID # Running user identifier
typeset -Hi _GID # Running user group identifier
2021-01-01 21:35:52 +00:00
typeset -H _TTY # Connected input terminal
2011-07-14 13:47:20 +00:00
2020-11-17 07:19:36 +00:00
# Tomb context (see is_valid_tomb())
2018-01-03 19:27:14 +00:00
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
2014-08-25 19:01:50 +00:00
2014-10-23 06:30:02 +00:00
# Tomb secrets
2018-01-03 19:27:14 +00:00
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())
2014-08-25 19:01:50 +00:00
2018-01-03 19:27:14 +00:00
typeset -aH TOMBTMPFILES # Keep track of temporary files
typeset -aH TOMBLOOPDEVS # Keep track of used loop devices
2018-09-23 21:21:05 +00:00
typeset -A TOMBFILESSTAT # Keep track of access date attributes
2014-08-06 05:43:25 +00:00
2018-11-01 01:43:49 +00:00
typeset _MSG_FD_OVERRIDE # if set, _msg will write to this file descriptor
2014-10-24 01:48:05 +00:00
# Make sure sbin is in PATH (man zshparam)
path+=( /sbin /usr/sbin )
2013-06-12 11:33:54 +00:00
2014-08-11 20:56:26 +00:00
# For gettext
export TEXTDOMAIN=tomb
2011-12-01 17:53:12 +00:00
# }}}
2012-08-04 16:34:10 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Safety functions
2011-12-01 19:41:04 +00:00
2021-04-07 17:20:12 +00:00
# Wrap sudo with a more visible message or apply user-supplied alternative to sudo
2015-02-08 17:33:10 +00:00
_sudo() {
2022-02-20 20:57:05 +00:00
if option_is_set --sudo; then
pescmd=`option_value --sudo`
case `basename $pescmd` in
"doas"|"sup"|"sud"|"pkexec")
command -v $pescmd > /dev/null || _failure "$pescmd executable not found"
_verbose "Super user execution using $pescmd"
${pescmd} ${@}
return $?
;;
"skip"|"none")
_verbose "Super user execution skipped (SUID caller)"
${@}
return $?
;;
*)
_failure "Super user execution not supported: ::1 sudo::" "`option_value --sudo`"
;;
esac
2022-03-03 09:27:35 +00:00
2022-02-20 20:57:05 +00:00
else
2024-05-12 23:30:58 +00:00
if [[ "`id -u`" = "0" ]]; then
_verbose "Super user execution skipped (SUID caller)"
${@}
return $?
elif command -v sudo 1>/dev/null 2>/dev/null; then
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}
[[ -n "$SUDO_ASKPASS" ]] && local sudo_askpass="--askpass"
sudo $sudo_askpass -p "
2022-02-20 20:57:05 +00:00
$msg
" ${@}
2024-05-12 23:30:58 +00:00
return $?
elif command -v doas 1>/dev/null 2>/dev/null; then
local msg="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}
doas ${@}
return $?
else
_failure "No way found to escalate privileges to super user."
fi
2022-02-20 20:57:05 +00:00
fi
2021-10-20 14:27:27 +00:00
}
2015-02-08 17:33:10 +00:00
2014-10-23 06:58:35 +00:00
# Cleanup anything sensitive before exiting.
_endgame() {
2014-08-25 19:01:50 +00:00
2021-01-25 17:26:49 +00:00
option_value_contains -o ro || {
# Restore access time of sensitive files
[[ -z $TOMBFILESSTAT ]] || _restore_stat
}
2018-09-23 21:21:05 +00:00
2018-01-03 19:27:14 +00:00
# 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
2024-08-05 13:26:08 +00:00
# Clear information regarding loop devices
# No need for an explicit detach as cryptsetup
# sets the AUTOCLEAR flag
2018-01-03 19:27:14 +00:00
unset TOMBLOOPDEVS
2014-08-14 07:58:15 +00:00
}
2014-10-23 06:58:35 +00:00
# Trap functions for the _endgame event
2022-03-03 09:27:35 +00:00
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; }
2014-08-14 07:58:15 +00:00
2014-11-26 16:44:23 +00:00
_is_found() {
2018-01-03 19:27:14 +00:00
# returns 0 if binary is found in path
2020-12-15 17:22:38 +00:00
[[ -z $1 ]] && return 1
2018-01-03 19:27:14 +00:00
command -v "$1" 1>/dev/null 2>/dev/null
return $?
2014-11-26 16:44:23 +00:00
}
2014-11-15 01:36:31 +00:00
2018-09-23 21:21:05 +00:00
# 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"
2018-09-24 11:58:51 +00:00
[[ -z "${stats[2]}" ]] || touch -m --date="@${stats[2]}" "$file"
2018-09-23 21:21:05 +00:00
done
}
2014-10-24 01:48:05 +00:00
# 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() {
2014-10-24 04:37:58 +00:00
2018-01-03 19:27:14 +00:00
# Set username from UID or environment
_USER=$SUDO_USER
2020-12-15 17:22:38 +00:00
[[ -z $_USER ]] && { _USER=$USERNAME }
2021-01-01 21:35:52 +00:00
[[ -z $_USER ]] && { _USER=$(id -un) }
2020-12-15 17:22:38 +00:00
[[ -z $_USER ]] && {
2018-01-03 19:27:14 +00:00
_failure "Failing to identify the user who is calling us" }
2014-11-03 20:36:52 +00:00
2018-01-03 19:27:14 +00:00
# Get GID from option -G or the environment
option_is_set -G \
&& _GID=$(option_value -G) || _GID=$(id -g $_USER)
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
# Get UID from option -U or the environment
option_is_set -U \
&& _UID=$(option_value -U) || _UID=$(id -u $_USER)
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
_verbose "Identified caller: ::1 username:: (::2 UID:::::3 GID::)" $_USER $_UID $_GID
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
# Update USERNAME accordingly if possible
# [[ $EUID == 0 && $_USER != $USERNAME ]] && {
# _verbose "Updating USERNAME from '::1 USERNAME::' to '::2 _USER::')" $USERNAME $_USER
# USERNAME=$_USER
# }
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
# Force HOME to _USER's HOME if necessary
2019-08-22 15:07:12 +00:00
local home=`_get_home $_USER`
2018-01-03 19:27:14 +00:00
[[ $home == $HOME ]] || {
_verbose "Updating HOME to match user's: ::1 home:: (was ::2 HOME::)" \
$home $HOME
HOME=$home }
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
# Get connecting TTY from option -T or the environment
option_is_set -T && _TTY=$(option_value -T)
[[ -z $_TTY ]] && _TTY=$TTY
2014-10-24 04:37:58 +00:00
2014-10-24 01:48:05 +00:00
}
2011-12-01 19:41:04 +00:00
2013-05-28 09:57:58 +00:00
# Provide a random filename in shared memory
2014-11-14 17:42:11 +00:00
_tmp_create() {
2021-01-01 20:58:23 +00:00
[[ -d "$TMPDIR" ]] || {
2018-01-03 19:27:14 +00:00
# we create the tempdir with the sticky bit on
2021-01-01 20:58:23 +00:00
_sudo mkdir -m 1777 "$TMPDIR"
[[ $? == 0 ]] || _failure "Fatal error creating the temporary directory: ::1 temp dir::" "$TMPDIR"
2018-01-03 19:27:14 +00:00
}
# We're going to add one more $RANDOM for each time someone complains
# about this being too weak of a random.
2021-01-01 20:58:23 +00:00
tfile="${TMPDIR}/$RANDOM$RANDOM$RANDOM$RANDOM" # Temporary file
2018-01-03 19:27:14 +00:00
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
2011-11-03 14:13:49 +00:00
}
2013-05-28 09:57:58 +00:00
2015-02-22 02:03:29 +00:00
# Check if a *block* device is encrypted
2022-10-19 12:53:46 +00:00
# Check if a *block* device is a zram device
# Synopsis: _is_zramswap /path/to/block/device
# Return 0 if it is a zramswap
# Return 1 if it is not a zramswap
_is_zramswap() {
local b=$1 # Path to a block device
# check if device b is a zram block device
zramctl --raw -o NAME | grep "^$b" >/dev/null
return $?
}
# Check if a zram device uses the writeback feature that writes data onto a disk
# Synopsis: _zramswap_uses_writeback /path/to/block/device
# Return 0 if the zram device writes to disk
# Return 1 if the zram device does not write to disk
_zramswap_uses_writeback() {
local b=$1 # Path to a block device
local m="" # major device number
local n="" # minor device number
read n m < <(stat -c '%T %t' $b) # get major and minor device number in hex
printf -v m %d $((16#$m)) # get major device number in decimal
printf -v n %d $((16#$n)) # get minor device number in decimal
if grep '^none$' "/sys/dev/block/$m:$n/backing_dev" > /dev/null; then
return 1
fi
return 0
}
# Check if a *block* device is a zram device
# Synopsis: _is_zramswap /path/to/block/device
# Return 0 if it is a zramswap
# Return 1 if it is not a zramswap
_is_zramswap() {
local b=$1 # Path to a block device
zramctl --raw -o NAME | grep "^$b" >/dev/null
# @todo How to do this without zramctl?
# - device node major is dynamically allocated to zram0
# - in /sys/ there seems to be no file identifying a zram device
return $?
}
# Check if a zram device uses the writeback feature that writes data onto a disk
# Synopsis: _zramswap_uses_writeback /path/to/block/device
# Return 0 if the zram device writes to disk
# Return 1 if the zram device does not write to disk
_zramswap_uses_writeback() {
local b=$1 # Path to a block device
local m="" # major device number
local n="" # minor device number
read n m < <(stat -c '%T %t' $b) # get major and minor device number in hex
printf -v m %d $((16#$m)) # get major device number in decimal
printf -v n %d $((16#$n)) # get minor device number in decimal
if grep '^none$' "/sys/dev/block/$m:$n/backing_dev" > /dev/null; then
return 1
fi
return 0
}
2015-02-08 17:54:27 +00:00
# Synopsis: _is_encrypted_block /path/to/block/device
# Return 0 if it is an encrypted block device
_is_encrypted_block() {
2018-01-03 19:27:14 +00:00
local b=$1 # Path to a block device
local s="" # lsblk option -s (if available)
2015-02-08 17:54:27 +00:00
2018-01-03 19:27:14 +00:00
# Issue #163
# lsblk --inverse appeared in util-linux 2.22
# but --version is not consistent...
lsblk --help | grep -Fq -- --inverse
[[ $? -eq 0 ]] && s="--inverse"
2015-02-08 22:50:52 +00:00
2021-04-07 17:20:12 +00:00
_sudo lsblk $s -o type -n $b 2>/dev/null \
2018-01-03 19:27:14 +00:00
| egrep -q '^crypt$'
2015-02-08 17:54:27 +00:00
2018-01-03 19:27:14 +00:00
return $?
2015-02-08 17:54:27 +00:00
}
2013-05-28 09:57:58 +00:00
# Check if swap is activated
2014-10-24 04:37:58 +00:00
# Return 0 if NO swap is used, 1 if swap is used.
# Return 1 if any of the swaps is not encrypted.
2022-10-19 12:53:46 +00:00
# Return 2 if swap(s) is(are) used, but ALL encrypted or zramswap without writeback to disk.
2015-09-20 21:32:00 +00:00
# Use _check_swap in functions. It will call this function and
2014-10-24 04:37:58 +00:00
# exit if unsafe swap is present.
_ensure_safe_swap() {
2018-01-03 19:27:14 +00:00
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
2014-10-24 04:37:58 +00:00
2018-01-03 19:27:14 +00:00
swaps="$(awk '/^\// { print $1 }' /proc/swaps 2>/dev/null)"
[[ -z "$swaps" ]] && return 0 # No swap partition is active
2014-10-24 04:37:58 +00:00
2018-01-03 19:27:14 +00:00
_message "An active swap partition is detected..."
for s in $=swaps; do
if _is_encrypted_block $s; then
2017-01-02 05:03:29 +00:00
r=2;
2022-10-19 12:53:46 +00:00
elif _is_zramswap $s; then
if _zramswap_uses_writeback $s; then
# We're dealing with unencrypted stuff written to disk.
# Maybe it lives on an encrypted filesystem anyway.
# @todo verify it's actually written to an encrypted FS
# Well, no: bail out.
2022-10-20 07:00:12 +00:00
_message "Found zramswap with writeback enabled."
2022-10-19 12:53:46 +00:00
r=1; break;
else
2022-10-20 07:00:12 +00:00
_message "Found zramswap without writeback to disk."
r=2
2022-10-19 12:53:46 +00:00
fi
2017-01-02 05:03:29 +00:00
else
2022-10-19 12:53:46 +00:00
# We're dealing with unencrypted stuff written to disk.
2018-01-03 19:27:14 +00:00
# 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
2022-10-20 07:00:12 +00:00
_success "The undertaker found that all swap partitions are encrypted. Good."
2018-01-03 19:27:14 +00:00
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
2014-10-24 04:37:58 +00:00
2011-07-10 20:11:10 +00:00
}
2012-01-17 13:00:20 +00:00
2014-10-24 04:37:58 +00:00
# Wrapper to allow encrypted swap and remind the user about possible
2015-09-20 21:32:00 +00:00
# data leaks to disk if swap is on, which shouldn't be ignored. It could
2014-10-24 04:37:58 +00:00
# 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.
2013-12-16 21:23:10 +00:00
_check_swap() {
2018-01-03 19:27:14 +00:00
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
2011-07-10 20:11:10 +00:00
}
2012-01-17 13:00:20 +00:00
2018-01-29 08:47:42 +00:00
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
}
2013-05-28 09:57:58 +00:00
# Ask user for a password
2014-11-03 00:55:19 +00:00
# Wraps around the pinentry command, from the GnuPG project, as it
# provides better security and conveniently use the right toolkit.
2013-05-28 09:57:58 +00:00
ask_password() {
2011-02-20 13:59:30 +00:00
2018-01-03 19:27:14 +00:00
local description="$1"
local title="${2:-Enter tomb password.}"
local output
local password
local gtkrc
local theme
2020-11-16 09:24:37 +00:00
local pass_asked
2014-11-25 01:37:05 +00:00
2018-01-03 19:27:14 +00:00
# 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
2018-01-28 17:50:08 +00:00
# own fallback mechanisms. Pinentry supported: curses, gtk-2, qt4, qt5
2018-01-03 19:27:14 +00:00
# and x11.
2014-11-26 16:44:23 +00:00
2018-01-03 19:27:14 +00:00
# make sure LANG is set, default to C
LANG=${LANG:-C}
2015-01-29 17:11:25 +00:00
2018-01-03 19:27:14 +00:00
_verbose "asking password with tty=$TTY lc-ctype=$LANG"
2015-07-04 09:28:37 +00:00
2020-11-16 09:24:37 +00:00
pass_asked=0
2014-11-26 16:44:23 +00:00
2024-08-31 03:38:45 +00:00
while true; do
[[ ! -z $WAYLAND_DISPLAY ]] && {
_verbose "wayland display detected"
_is_found "pinentry-gnome3" && {
_verbose "using pinentry-gnome3 on wayland"
output=$(pinentry_assuan_getpass | pinentry-gnome3)
break; }
# TODO: pinentry on KDE running in wayland?
}
[[ ! -z $DISPLAY ]] && [[ $pass_asked == 0 ]] && {
_verbose "X11 display detected"
_is_found "pinentry-gtk-2" && {
_verbose "using pinentry-gtk2"
output=$(pinentry_assuan_getpass | pinentry-gtk-2)
break; }
_is_found "pinentry-x11" && {
_verbose "using pinentry-x11"
output=$(pinentry_assuan_getpass | pinentry-x11)
break; }
_is_found "pinentry-gnome3" && {
_verbose "using pinentry-gnome3 on X11"
output=$(pinentry_assuan_getpass | pinentry-gnome3)
break; }
_is_found "pinentry-qt5" && {
_verbose "using pinentry-qt5"
output=$(pinentry_assuan_getpass | pinentry-qt5)
break; }
_is_found "pinentry-qt4" && {
_verbose "using pinentry-qt4"
output=$(pinentry_assuan_getpass | pinentry-qt4)
break; }
2020-11-16 09:24:37 +00:00
}
_verbose "no display detected"
2024-08-31 03:38:45 +00:00
_is_found "pinentry-curses" && {
2020-11-16 09:24:37 +00:00
_verbose "using pinentry-curses with no display"
2020-11-21 21:26:42 +00:00
output=$(pinentry_assuan_getpass | pinentry-curses)
2024-08-31 03:38:45 +00:00
break; }
_is_found "pinentry-tty" && {
2024-05-12 22:48:07 +00:00
_verbose "using pinentry-tty with no display"
output=$(pinentry_assuan_getpass | pinentry-tty)
2024-08-31 03:38:45 +00:00
break; }
# TODO: fallback using read -s - and beware
# using read with or without -r may break
# passwords, so this must be covered by a test
# for compatibility
2024-05-12 22:48:07 +00:00
_failure "Cannot find any pinentry and no DISPLAY detected."
2024-08-31 03:38:45 +00:00
exit 1
done
2014-11-26 16:44:23 +00:00
2018-01-03 19:27:14 +00:00
# parse the pinentry output
2020-11-16 09:24:37 +00:00
local pinentry_error
2018-01-03 19:27:14 +00:00
for i in ${(f)output}; do
2020-12-29 09:52:16 +00:00
[[ "$i" =~ "^ERR.*" ]] && {
pinentry_error="${i[(w)3]}"
2017-01-02 05:13:52 +00:00
}
2014-11-03 00:55:19 +00:00
2018-01-03 19:27:14 +00:00
# here the password is found
[[ "$i" =~ "^D .*" ]] && password="${i##D }";
done
2014-11-03 00:55:19 +00:00
2020-12-15 17:22:38 +00:00
[[ ! -z $pinentry_error ]] && [[ -z $password ]] && {
2020-11-16 09:24:37 +00:00
_warning "Pinentry error: ::1 error::" ${pinentry_error}
print "canceled"
return 1
}
2020-03-23 22:07:46 +00:00
2020-12-15 17:22:38 +00:00
[[ -z $password ]] && {
2018-01-03 19:27:14 +00:00
_warning "Empty password"
print "empty"
return 1
2017-01-02 05:13:52 +00:00
}
2013-05-28 09:57:58 +00:00
2018-01-03 19:27:14 +00:00
print "$password"
return 0
2011-02-03 16:11:08 +00:00
}
2013-05-28 09:57:58 +00:00
2014-10-23 05:10:24 +00:00
# Check if a filename is a valid tomb
2013-06-19 18:20:17 +00:00
is_valid_tomb() {
2020-11-17 07:19:36 +00:00
_verbose "is_valid_tomb ::1 tomb file::" $1
2018-01-03 19:27:14 +00:00
# First argument must be the path to a tomb
2020-12-15 17:22:38 +00:00
[[ ! -z $1 ]] || _failure "Tomb file is missing from arguments."
2018-01-03 19:27:14 +00:00
2020-11-17 07:19:36 +00:00
local _fail=0
2018-01-03 19:27:14 +00:00
# Tomb file must be a readable, writable, non-empty regular file.
# If passed the "ro" mount option, the writable check is skipped.
2024-08-31 03:38:45 +00:00
while true; do
option_value_contains -o ro || {
[[ ! -w "$1" ]] && {
_warning "Tomb file is not writable: ::1 tomb file::" $1
_fail=1; break; }
2021-01-25 17:26:49 +00:00
}
2024-08-31 03:38:45 +00:00
_verbose "tomb file is readable"
[[ ! -f "$1" ]] && {
_warning "Tomb file is not a regular file: ::1 tomb file::" $1
_fail=1; break; }
_verbose "tomb file is a regular file"
[[ ! -s "$1" ]] && {
_warning "Tomb file is empty (zero length): ::1 tomb file::" $1
_fail=1; break; }
_verbose "tomb file is not empty"
break;
done
2020-11-17 07:19:36 +00:00
[[ $_fail == 1 ]] && {
2018-01-03 19:27:14 +00:00
_failure "Tomb command failed: ::1 command name::" $subcommand
}
2014-10-28 18:46:36 +00:00
2018-01-03 19:27:14 +00:00
# Tomb file may be a LUKS FS (or we are creating it)
2020-11-17 07:19:36 +00:00
[[ "`file $1`" =~ "luks encrypted file" ]] || {
2022-02-20 20:57:05 +00:00
_message "File is not yet a tomb: ::1 tomb file::" $1 }
2014-08-25 19:01:50 +00:00
2020-11-16 22:35:03 +00:00
# We set global variables
typeset -g TOMBPATH TOMBDIR TOMBFILE TOMBNAME TOMBMAPPER
2014-10-23 05:10:24 +00:00
2020-11-16 22:35:03 +00:00
TOMBPATH="$1"
2014-10-28 18:46:36 +00:00
2020-11-16 22:35:03 +00:00
TOMBDIR=$(dirname $TOMBPATH)
2014-10-28 18:46:36 +00:00
2020-11-16 22:35:03 +00:00
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}}
2020-12-15 17:22:38 +00:00
[[ -z $TOMBNAME ]] &&
2020-11-16 22:35:03 +00:00
_failure "Tomb won't work without a TOMBNAME."
2014-02-19 11:08:26 +00:00
2020-11-16 22:35:03 +00:00
# checks if Tomb already mounted (or we cannot alter it)
2024-05-12 23:17:23 +00:00
local maphash=`realpath $TOMBPATH | sha256sum`
2024-08-05 13:26:08 +00:00
lo_check # fills TOMBLOOP with next loop if available
2022-02-20 20:57:05 +00:00
TOMBMAPPER="tomb.$TOMBNAME.${maphash[(w)1]}.`basename $TOMBLOOP`"
2020-11-13 21:49:40 +00:00
local mounted_tombs=(`list_tomb_mounts`)
local usedmapper
for t in ${mounted_tombs}; do
usedmapper=`basename "${t[(ws:;:)1]}"`
2020-11-16 22:35:03 +00:00
[[ "${usedmapper%.*}" == "${TOMBMAPPER%.*}" ]] &&
_failure "Tomb file already in use: ::1 tombname::" $TOMBPATH
2020-11-13 21:49:40 +00:00
done
2020-11-16 22:35:03 +00:00
_verbose "Mapper: ::1 mapper::" $TOMBMAPPER
_verbose "tomb file is not currently in use"
_message "Valid tomb file found: ::1 tomb path::" $TOMBPATH
return 0
2020-11-13 21:49:40 +00:00
}
2024-08-05 13:26:08 +00:00
# $1 is the tomb file which needs a loop device
lo_check() {
2018-01-03 19:27:14 +00:00
tpath="$1"
# check if we have support for loop mounting
2022-04-07 13:20:38 +00:00
TOMBLOOP=`_sudo losetup -f`
2018-01-03 19:27:14 +00:00
[[ $? = 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."
}
2014-08-25 19:01:50 +00:00
2022-02-20 20:57:05 +00:00
[[ "$tpath" == "" ]] && return 0
2020-11-16 22:35:03 +00:00
TOMBLOOPDEVS+=("$TOMBLOOP") # add to array of lodevs used
2022-02-20 20:57:05 +00:00
2018-01-03 19:27:14 +00:00
return 0
2014-08-25 19:01:50 +00:00
}
2014-08-25 21:32:32 +00:00
# eventually used for debugging
2014-08-25 19:01:50 +00:00
dump_secrets() {
2018-01-03 19:27:14 +00:00
print "TOMBPATH: $TOMBPATH"
print "TOMBNAME: $TOMBNAME"
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
print "TOMBKEY len: ${#TOMBKEY}"
print "TOMBKEYFILE: $TOMBKEYFILE"
print "TOMBSECRET len: ${#TOMBSECRET}"
print "TOMBPASSWORD: $TOMBPASSWORD"
2014-08-29 10:31:23 +00:00
2018-01-03 19:27:14 +00:00
print "TOMBTMPFILES: ${(@)TOMBTMPFILES}"
print "TOMBLOOPDEVS: ${(@)TOMBLOOPDEVS}"
2014-08-25 19:01:50 +00:00
}
2014-10-28 18:46:36 +00:00
2011-12-01 17:53:12 +00:00
# }}}
2011-10-31 23:36:14 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Commandline interaction
2013-05-28 10:58:05 +00:00
2011-03-31 17:42:05 +00:00
usage() {
2018-01-03 19:27:14 +00:00
_print "Syntax: tomb [options] command [arguments]"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print "Commands:"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print " // Creation:"
2018-11-25 15:45:40 +00:00
_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"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print " // Operations on tombs:"
2018-11-25 15:45:40 +00:00
_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"
2018-01-03 19:27:14 +00:00
[[ $RESIZER == 1 ]] && {
2018-11-25 15:45:40 +00:00
_print " resize resize a TOMB to a new size -s (can only grow)"
2018-01-03 19:27:14 +00:00
}
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print " // Operations on keys:"
2018-11-25 15:45:40 +00:00
_print " passwd change the password of a KEY (needs old pass)"
_print " setkey change the KEY locking a TOMB (needs old key and pass)"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
[[ $QRENCODE == 1 ]] && {
_print " // Backup on paper:"
2023-06-26 19:10:37 +00:00
_print " engrave makes a QR code of a KEY to be saved on paper"
2018-11-25 15:45:40 +00:00
echo
2018-01-03 19:27:14 +00:00
}
2019-02-21 09:28:21 +00:00
[[ $STEGHIDE == 1 || $CLOAKIFY == 1 || $DECLOAKIFY == 1 ]] && {
2018-01-03 19:27:14 +00:00
_print " // Steganography:"
2019-02-21 09:28:21 +00:00
[[ $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)"
}
2018-11-25 15:45:40 +00:00
echo
2018-01-03 19:27:14 +00:00
}
_print "Options:"
2018-11-01 01:43:49 +00:00
echo
2018-11-25 15:45:40 +00:00
_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)"
2022-02-20 20:57:05 +00:00
_print " --sudo super user exec alternative to sudo (doas or none)"
2018-01-03 19:27:14 +00:00
[[ $KDF == 1 ]] && {
2018-11-25 15:45:40 +00:00
_print " --kdf forge keys armored against dictionary attacks"
2018-01-03 19:27:14 +00:00
}
2018-11-01 01:43:49 +00:00
echo
2018-11-25 15:45:40 +00:00
_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"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print "For more information on Tomb read the manual: man tomb"
_print "Please report bugs on <http://github.com/dyne/tomb/issues>."
2011-03-31 17:42:05 +00:00
}
2011-05-09 11:26:36 +00:00
2014-10-24 03:03:48 +00:00
# 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
2013-05-28 09:57:58 +00:00
option_is_set() {
2018-01-03 19:27:14 +00:00
local -i r # the return code (0 = set, 1 = unset)
2014-10-24 03:03:48 +00:00
2018-01-03 19:27:14 +00:00
[[ -n ${(k)OPTS[$1]} ]];
r=$?
2014-10-24 03:03:48 +00:00
2018-01-03 19:27:14 +00:00
[[ $2 == "out" ]] && {
[[ $r == 0 ]] && { print 'set' } || { print 'unset' }
}
2014-10-24 03:03:48 +00:00
2018-01-03 19:27:14 +00:00
return $r;
2013-05-28 09:57:58 +00:00
}
2011-05-09 11:26:36 +00:00
2014-10-24 03:03:48 +00:00
# Print the option value matching the given flag
# Unique argument is the commandline flag (e.g., "-s").
2013-05-28 09:57:58 +00:00
option_value() {
2018-01-03 19:27:14 +00:00
print -n - "${OPTS[$1]}"
2013-05-28 09:57:58 +00:00
}
2011-05-09 11:26:36 +00:00
2021-01-25 17:26:49 +00:00
# check if the option value contains a string between commas
option_value_contains() {
local opt="${OPTS[$1]}"
local str="$2"
for i in ${(s:,:)opt}; do
[[ "$i" == "$2" ]] && return 0
done
return 1
}
2013-05-28 09:57:58 +00:00
# Messaging function with pretty coloring
function _msg() {
2018-01-03 19:27:14 +00:00
local msg="$2"
2017-12-11 07:05:40 +00:00
local i
2018-01-03 19:27:14 +00:00
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"
2018-11-01 01:43:49 +00:00
local progname="${TOMBEXEC##*/}"
local pchars=""
local pcolor="normal"
2020-11-25 13:47:54 +00:00
local fd=2
2018-01-03 19:27:14 +00:00
local -i returncode
case "$1" in
inline)
command+=" -n"; pchars=" > "; pcolor="yellow"
;;
message)
2018-11-01 01:43:49 +00:00
pchars=" . "; pcolor="white"
2018-01-03 19:27:14 +00:00
;;
verbose)
pchars="[D]"; pcolor="blue"
;;
success)
2018-11-01 01:43:49 +00:00
pchars="(*)"; pcolor="green"
2018-01-03 19:27:14 +00:00
;;
warning)
2018-11-01 01:43:49 +00:00
pchars="[W]"; pcolor="yellow"
2018-01-03 19:27:14 +00:00
;;
failure)
2018-11-01 01:43:49 +00:00
pchars="[E]"; pcolor="red"
2018-01-03 19:27:14 +00:00
returncode=1
;;
print)
progname=""
2020-11-25 13:47:54 +00:00
fd=1
2018-01-03 19:27:14 +00:00
;;
*)
pchars="[F]"; pcolor="red"
2018-11-01 01:43:49 +00:00
msg="Developer oops! Usage: _msg MESSAGE_TYPE \"MESSAGE_CONTENT\""
2018-01-03 19:27:14 +00:00
returncode=127
;;
esac
2018-11-01 01:43:49 +00:00
[[ -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
2018-01-03 19:27:14 +00:00
return $returncode
2013-05-28 09:57:58 +00:00
}
2011-05-09 11:26:36 +00:00
2017-01-02 05:03:29 +00:00
function _message() {
2018-01-03 19:27:14 +00:00
local notice="message"
[[ "$1" = "-n" ]] && shift && notice="inline"
option_is_set -q || _msg "$notice" $@
return 0
2013-05-28 09:57:58 +00:00
}
2011-12-01 19:04:56 +00:00
2017-01-02 05:03:29 +00:00
function _verbose() {
2018-01-03 19:27:14 +00:00
option_is_set -D && _msg verbose $@
return 0
2013-05-28 09:57:58 +00:00
}
2011-12-01 19:04:56 +00:00
2017-01-02 05:03:29 +00:00
function _success() {
2018-01-03 19:27:14 +00:00
option_is_set -q || _msg success $@
return 0
2013-05-28 09:57:58 +00:00
}
2011-12-01 19:04:56 +00:00
2017-01-02 05:03:29 +00:00
function _warning() {
2018-01-03 19:27:14 +00:00
option_is_set -q || _msg warning $@
return 1
2013-05-28 09:57:58 +00:00
}
2011-12-01 19:04:56 +00:00
2017-01-02 05:03:29 +00:00
function _failure() {
2018-01-03 19:27:14 +00:00
typeset -i exitcode=${exitv:-1}
option_is_set -q || _msg failure $@
# be sure we forget the secrets we were told
exit $exitcode
2011-05-09 11:26:36 +00:00
}
2011-12-01 17:53:12 +00:00
2014-09-13 14:55:03 +00:00
function _print() {
2018-01-03 19:27:14 +00:00
option_is_set -q || _msg print $@
return 0
2014-09-13 14:55:03 +00:00
}
2014-11-16 10:34:35 +00:00
_list_optional_tools() {
2018-01-03 19:27:14 +00:00
typeset -a _deps
_deps=(gettext dcfldd shred steghide)
2024-05-12 21:29:14 +00:00
_deps+=(resize2fs tomb-kdb-pbkdf2 argon2 qrencode recoll unoconv lsof)
2018-01-03 19:27:14 +00:00
for d in $_deps; do
_print "`which $d`"
done
return 0
2014-11-16 10:34:35 +00:00
}
2014-10-24 01:48:05 +00:00
# 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.
2014-11-16 10:34:35 +00:00
_ensure_dependencies() {
2014-10-24 01:48:05 +00:00
2018-01-03 19:27:14 +00:00
# Check for required programs
2024-05-12 23:30:58 +00:00
for req in cryptsetup gpg mkfs.ext4 e2fsck; do
2018-01-03 19:27:14 +00:00
command -v $req 1>/dev/null 2>/dev/null || {
_failure "Missing required dependency ::1 command::. Please install it." $req; }
done
2024-08-31 03:38:45 +00:00
# Check for pinentry or at least pinentry-tty (which has no alias)
if ! command -v pinentry 1>/dev/null 2>/dev/null; then
if ! command -v pinentry-tty 1>/dev/null 2>/dev/null; then
2024-05-12 22:48:07 +00:00
_failure "Missing required dependency ::1 command::. Please install it." pinentry
2024-08-31 03:38:45 +00:00
fi
fi
2018-01-03 19:27:14 +00:00
# Ensure system binaries are available in the PATH
path+=(/sbin /usr/sbin) # zsh magic
2021-10-20 14:27:27 +00:00
# use pkexec in place of sudo if found in path and polkitd is running
2021-10-21 09:49:54 +00:00
# command -v pkexec 1>/dev/null 2>/dev/null
# [[ $? == 0 ]] && ps ax | grep '[p]olkitd' 1>/dev/null 2>/dev/null && {
# SUDO=(pkexec) }
2024-05-12 23:30:58 +00:00
# [[ "$SUDO" == "sudo" ]] && {
# command -v sudo 1>/dev/null 2>/dev/null ||
# _failure "No privilege escalation tool found, not even sudo"
# }
2021-10-20 14:27:27 +00:00
2018-01-03 19:27:14 +00:00
# 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
2019-02-21 09:28:21 +00:00
# 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
2018-01-03 19:27:14 +00:00
# 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
2022-02-20 21:05:01 +00:00
# Check for ARGON2 KDF auxiliary tools
command -v argon2 1>/dev/null 2>/dev/null || ARGON2=0
2024-05-12 21:29:14 +00:00
# Check for Recoll file content indexer
command -v recoll 1>/dev/null 2>/dev/null || RECOLL=0
2018-01-03 19:27:14 +00:00
# Check for QREncode for paper backups of keys
command -v qrencode 1>/dev/null 2>/dev/null || QRENCODE=0
2013-05-28 09:57:58 +00:00
}
# }}} - Commandline interaction
# {{{ Key operations
2017-02-03 17:28:56 +00:00
# $@ is the list of all the recipient used to encrypt a tomb key
2017-01-31 15:11:50 +00:00
is_valid_recipients() {
2018-01-03 19:27:14 +00:00
typeset -a recipients
recipients=($@)
2019-06-27 18:58:58 +00:00
trusted=(m f u w s)
2018-01-03 19:27:14 +00:00
_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
2019-06-27 18:58:58 +00:00
trust="$(gpg --with-colons --batch --list-keys "$gpg_id" 2> /dev/null |
awk 'BEGIN { FS=":" } /^pub/ { print $2; exit}')"
2022-04-13 13:46:35 +00:00
[[ "${trust}" == "" ]] && {
2018-01-03 19:27:14 +00:00
_warning "Not a valid GPG key ID: ::1 gpgid:: " $gpg_id
return 1
}
2019-06-27 18:58:58 +00:00
[[ ${trusted[(r)$trust]} != $trust ]] && {
_warning "The key ::1 gpgid:: is not trusted enough" $gpg_id
return 1
}
2018-01-03 19:27:14 +00:00
done
# At least one private key must be present
2022-04-13 13:58:09 +00:00
# for gpg_id in ${recipients[@]}; do
# gpg --with-colons --batch --list-secret-keys "$gpg_id" &> /dev/null
# [[ $? = 0 ]] && {
# return 0
# }
# done
2018-01-03 19:27:14 +00:00
2022-04-13 13:58:09 +00:00
return 0
2017-02-03 17:28:56 +00:00
}
# $@ is the list of all the recipient used to encrypt a tomb key
# Print the recipient arg to be used in gpg.
_recipients_arg() {
2018-01-03 19:27:14 +00:00
local arg="$1"; shift
typeset -a recipients
recipients=($@)
for gpg_id in ${recipients[@]}; do
print -R -n "$arg $gpg_id "
done
return 0
2017-01-31 15:11:50 +00:00
}
2017-02-03 17:55:06 +00:00
# $1 is a GPG key recipient
# Print the fingerprint of the GPG key
2019-05-05 09:29:25 +00:00
_gpg_fingerprint() {
gpg --with-colons --fingerprint "$1" |
awk 'BEGIN { FS=":" } /^fpr/ { print $10; exit }' }
_gpg_uid() {
gpg --with-colons --list-key "$1" |
awk 'BEGIN { FS=":" } /^uid/ { print $10; exit}' }
2017-02-03 17:55:06 +00:00
2019-08-22 15:07:12 +00:00
# helpers to retrieve data from passwd using getent
2019-09-14 10:06:13 +00:00
_get_username() { getent passwd ${1} | awk -F: '{print $1}' }
_get_home() { getent passwd ${1} | awk -F: '{print $6}' }
2017-02-03 17:55:06 +00:00
2014-08-25 22:54:41 +00:00
# $1 is the encrypted key contents we are checking
is_valid_key() {
2018-01-03 19:27:14 +00:00
local key="$1" # Unique argument is an encrypted key to test
_verbose "is_valid_key"
[[ -z $key ]] && key=$TOMBKEY
[[ "$key" = "cleartext" ]] && {
{ option_is_set --unsafe } || {
_warning "cleartext key from stdin selected: this is unsafe."
exitv=127 _failure "please use --unsafe if you really want to do this."
}
_warning "received key in cleartext from stdin (unsafe mode)"
return 0 }
[[ -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 }
2018-11-03 21:15:48 +00:00
[[ $KDF == 1 ]] && { ! option_is_set -g } && { option_is_set --kdf } && {
_head="${key[(f)1]}"
[[ $_head =~ '^_KDF_' ]] || {
_warning "Key is missing KDF header."
return 1
}
}
2018-01-03 19:27:14 +00:00
[[ $key =~ "BEGIN PGP" ]] && {
_message "Key is valid."
return 0 }
return 1
2014-08-25 22:54:41 +00:00
}
# $1 is a string containing an encrypted key
2017-01-02 05:03:29 +00:00
recover_key() {
2018-01-03 19:27:14 +00:00
local key="${1}" # Unique argument is an encrypted key
2014-10-23 06:30:02 +00:00
2018-01-03 19:27:14 +00:00
_warning "Attempting key recovery."
2014-11-26 16:44:23 +00:00
2018-01-03 19:27:14 +00:00
_head="${key[(f)1]}" # take the first line
2014-08-25 22:54:41 +00:00
2018-01-03 19:27:14 +00:00
TOMBKEY="" # Reset global variable
2014-10-23 06:30:02 +00:00
2018-01-03 19:27:14 +00:00
[[ $_head =~ "^_KDF_" ]] && TOMBKEY+="$_head\n"
2014-10-23 06:30:02 +00:00
2018-01-03 19:27:14 +00:00
TOMBKEY+="-----BEGIN PGP MESSAGE-----\n"
TOMBKEY+="$key\n"
TOMBKEY+="-----END PGP MESSAGE-----\n"
2014-08-25 22:54:41 +00:00
2018-01-03 19:27:14 +00:00
return 0
2014-08-25 22:54:41 +00:00
}
2014-10-23 06:30:02 +00:00
# Retrieve the tomb key from the file specified from the command line,
# or from stdin if -k - was selected. Run validity checks on the
2018-01-03 19:27:14 +00:00
# file. On success, return 0 and print out the full path of the key.
2014-10-23 06:30:02 +00:00
# Set global variables TOMBKEY and TOMBKEYFILE.
2014-11-04 04:04:18 +00:00
_load_key() {
2018-01-03 19:27:14 +00:00
local keyfile="$1" # Unique argument is an optional keyfile
[[ -z $keyfile ]] && keyfile=$(option_value -k)
[[ -z $keyfile ]] && {
_failure "This operation requires a key file to be specified using the -k option." }
2024-08-31 03:38:45 +00:00
while true; do
[[ $keyfile == "-" ]] && {
_verbose "load_key reading from stdin."
_message "Waiting for the key to be piped from stdin... "
TOMBKEYFILE=stdin
TOMBKEY=$(cat)
break; }
[[ $keyfile == "cleartext" ]] && {
_verbose "load_key reading SECRET from stdin"
_message "Waiting for the key to be piped from stdin... "
TOMBKEYFILE=cleartext
TOMBKEY=cleartext
TOMBSECRET=$(cat)
break; }
2018-01-03 19:27:14 +00:00
_verbose "load_key argument: ::1 key file::" $keyfile
[[ -r $keyfile ]] || _failure "Key not found, specify one using -k."
2018-09-23 21:21:05 +00:00
_track_stat "$keyfile"
2018-01-03 19:27:14 +00:00
TOMBKEYFILE=$keyfile
TOMBKEY="${mapfile[$TOMBKEYFILE]}"
2024-08-31 03:38:45 +00:00
break
done
2018-01-03 19:27:14 +00:00
_verbose "load_key: ::1 key::" $TOMBKEYFILE
2020-12-15 17:22:38 +00:00
[[ -z $TOMBKEY ]] && {
2018-01-03 19:27:14 +00:00
# something went wrong, there is no key to load
# this occurs especially when piping from stdin and aborted
_failure "Key not found, specify one using -k."
}
is_valid_key $TOMBKEY || {
_warning "The key seems invalid or its format is not known by this version of Tomb."
2017-01-02 05:03:29 +00:00
recover_key $TOMBKEY
2018-01-03 19:27:14 +00:00
}
2014-11-21 21:32:38 +00:00
2018-01-03 19:27:14 +00:00
# Declared TOMBKEYFILE (path)
# Declared TOMBKEY (contents)
2014-10-23 06:30:02 +00:00
2018-01-03 19:27:14 +00:00
return 0
2013-05-28 09:57:58 +00:00
}
2014-08-05 15:05:49 +00:00
# takes two args just like get_lukskey
# prints out the decrypted content
# contains tweaks for different gpg versions
2017-02-03 18:53:31 +00:00
# support both symmetric and asymmetric encryption
2014-08-05 15:05:49 +00:00
gpg_decrypt() {
2018-01-03 19:27:14 +00:00
# fix for gpg 1.4.11 where the --status-* options don't work ;^/
local gpgver=$(gpg --version --no-permission-warning | awk '/^gpg/ {print $3}')
local gpgpass="$1\n$TOMBKEY"
local tmpres ret
typeset -a gpgopt
gpgpopt=(--batch --no-tty --passphrase-fd 0 --no-options)
{ option_is_set -g } && {
gpgpass="$TOMBKEY"
gpgpopt=(--yes)
# GPG option '--try-secret-key' exist since GPG 2.1
{ option_is_set -R } && { autoload -U is-at-least && is-at-least "2.1" $gpgver } && {
typeset -a recipients
recipients=(${(s:,:)$(option_value -R)})
{ is_valid_recipients $recipients } || {
_failure "You set an invalid GPG ID."
}
gpgpopt+=(`_recipients_arg "--try-secret-key" $recipients`)
}
}
[[ $gpgver == "1.4.11" ]] && {
_verbose "GnuPG is version 1.4.11 - adopting status fix."
TOMBSECRET=`print - "$gpgpass" | \
gpg --decrypt ${gpgpopt[@]}`
ret=$?
unset gpgpass
return $ret
}
_tmp_create
tmpres=$TOMBTMP
TOMBSECRET=`print - "$gpgpass" | \
2021-01-01 21:35:52 +00:00
gpg --decrypt ${gpgpopt[@]} \
2018-01-03 19:27:14 +00:00
--status-fd 2 --no-mdc-warning --no-permission-warning \
--no-secmem-warning 2> $tmpres`
unset gpgpass
ret=1
for i in ${(f)"$(cat $tmpres)"}; do
_verbose "$i"
[[ "$i" =~ "DECRYPTION_OKAY" ]] && ret=0;
done
return $ret
2014-08-05 15:05:49 +00:00
}
2014-08-06 09:21:08 +00:00
# Gets a key file and a password, prints out the decoded contents to
# be used directly by Luks as a cryptographic key
get_lukskey() {
2018-01-03 19:27:14 +00:00
# $1 is the password
_verbose "get_lukskey"
_password="$1"
firstline="${TOMBKEY[(f)1]}"
# key is KDF encoded
if [[ $firstline =~ '^_KDF_' ]]; then
kdf_hash="${firstline[(ws:_:)2]}"
_verbose "KDF: ::1 kdf::" "$kdf_hash"
case "$kdf_hash" in
"pbkdf2sha1")
kdf_salt="${firstline[(ws:_:)3]}"
kdf_ic="${firstline[(ws:_:)4]}"
kdf_len="${firstline[(ws:_:)5]}"
_message "Unlocking KDF key protection (::1 kdf::)" $kdf_hash
_verbose "KDF salt: $kdf_salt"
_verbose "KDF ic: $kdf_ic"
_verbose "KDF len: $kdf_len"
_password=$(tomb-kdb-pbkdf2 $kdf_salt $kdf_ic $kdf_len 2>/dev/null <<<$_password)
;;
2022-02-20 21:05:01 +00:00
"argon2")
kdf_salt="${firstline[(ws:_:)3]}"
kdf_ic="${firstline[(ws:_:)4]}"
kdf_mem="${firstline[(ws:_:)5]}"
_message "Unlocking KDF key protection (::1 kdf::)" $kdf_hash
_verbose "KDF salt: $kdf_salt"
_verbose "KDF ic: $kdf_ic"
_verbose "KDF mem: $kdf_mem"
_password=$(argon2 $kdf_salt -m $kdf_mem -t $kdf_ic -l 64 -r 2>/dev/null <<<$_password)
;;
2018-01-03 19:27:14 +00:00
*)
_failure "No suitable program for KDF ::1 program::." $pbkdf_hash
unset _password
return 1
;;
esac
# key needs to be exhumed from an image
elif [[ -r $TOMBKEYFILE && $(file $TOMBKEYFILE) =~ "JP.G" ]]; then
if option_is_set -g; then
# When using a GPG key, the tomb key is buried using a steganography password
if option_is_set --tomb-pwd; then
_password="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 tomb pass::" $_password
else
_password=$(ask_password "Insert password to exhume key from $imagefile")
[[ $? != 0 ]] && {
_warning "User aborted password dialog."
return 1
}
fi
exhume_key $TOMBKEYFILE "$_password"
unset _password
else
exhume_key $TOMBKEYFILE "$_password"
fi
fi
gpg_decrypt "$_password" # Save decrypted contents into $TOMBSECRET
ret="$?"
_verbose "get_lukskey returns ::1::" $ret
return $ret
2014-08-06 09:21:08 +00:00
}
2013-05-28 09:57:58 +00:00
# This function asks the user for the password to use the key it tests
2014-08-25 21:32:32 +00:00
# it against the return code of gpg on success returns 0 and saves
2014-10-23 06:44:45 +00:00
# the password in the global variable $TOMBPASSWORD
2013-05-28 09:57:58 +00:00
ask_key_password() {
2018-01-03 19:27:14 +00:00
[[ -z "$TOMBKEYFILE" ]] && {
_failure "Internal error: ask_key_password() called before _load_key()." }
[[ "$TOMBKEYFILE" = "cleartext" ]] && {
_verbose "no password needed, using secret bytes from stdin"
return 0 }
if option_is_set -g; then
_verbose "no password needed, using GPG key"
get_lukskey
return $?
fi
_message "A password is required to use key ::1 key::" $TOMBKEYFILE
passok=0
tombpass=""
2020-12-15 17:22:38 +00:00
if [[ -z $1 ]]; then
2018-01-03 19:27:14 +00:00
for c in 1 2 3; do
if [[ $c == 1 ]]; then
tombpass=$(ask_password "Insert password to: $TOMBKEYFILE")
else
tombpass=$(ask_password "Insert password to: $TOMBKEYFILE (attempt $c)")
fi
[[ $? = 0 ]] || {
_warning "User aborted password dialog."
return 1
}
get_lukskey "$tombpass"
[[ $? = 0 ]] && {
passok=1; _message "Password OK."
break;
}
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"
[[ $? = 0 ]] && {
passok=1; _message "Password OK."
}
fi
[[ $passok == 1 ]] || return 1
TOMBPASSWORD=$tombpass
return 0
2013-05-28 09:57:58 +00:00
}
2014-11-20 08:59:11 +00:00
# call cryptsetup with arguments using the currently known secret
# echo flags eliminate newline and disable escape (BSD_ECHO)
_cryptsetup() {
2021-06-24 17:04:59 +00:00
if option_is_set -q; then
print -R -n - "$TOMBSECRET" | _sudo cryptsetup --type luks1 --key-file - ${@} 2> /dev/null
else
print -R -n - "$TOMBSECRET" | _sudo cryptsetup --type luks1 --key-file - ${@}
fi
2018-01-03 19:27:14 +00:00
return $?
2014-11-20 08:59:11 +00:00
}
2013-05-28 09:57:58 +00:00
# change tomb key password
change_passwd() {
2018-01-03 19:27:14 +00:00
local tmpnewkey lukskey c tombpass tombpasstmp
_check_swap # Ensure swap is secure, if any
_load_key # Try loading key from option -k and set TOMBKEYFILE
{ option_is_set -g } && {
_message "Commanded to change GnuPG key for tomb key ::1 key::" $TOMBKEYFILE
} || {
_message "Commanded to change password for tomb key ::1 key::" $TOMBKEYFILE
}
_tmp_create
tmpnewkey=$TOMBTMP
if option_is_set --tomb-old-pwd; then
local tomboldpwd="`option_value --tomb-old-pwd`"
_verbose "tomb-old-pwd = ::1 old pass::" $tomboldpwd
ask_key_password "$tomboldpwd"
else
ask_key_password
fi
[[ $? == 0 ]] || _failure "No valid password supplied."
{ option_is_set -g } && {
_success "Changing GnuPG key for ::1 key file::" $TOMBKEYFILE
} || {
_success "Changing password for ::1 key file::" $TOMBKEYFILE
}
# Here $TOMBSECRET contains the key material in clear
{ option_is_set --tomb-pwd } && {
local tombpwd="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 new pass::" $tombpwd
2018-11-01 01:43:49 +00:00
gen_key "$tmpnewkey" "$tombpwd"
2018-01-03 19:27:14 +00:00
} || {
2018-11-01 01:43:49 +00:00
gen_key "$tmpnewkey"
2018-01-03 19:27:14 +00:00
}
{ is_valid_key "${mapfile[$tmpnewkey]}" } || {
_failure "Error: the newly generated keyfile does not seem valid." }
# Copy the new key as the original keyfile name
cp -f "${tmpnewkey}" $TOMBKEYFILE
{ option_is_set -g } && {
_success "Your GnuPG key was successfully changed"
} || {
_success "Your passphrase was successfully updated."
}
return 0
2013-05-28 09:57:58 +00:00
}
# takes care to encrypt a key
2017-02-09 20:59:10 +00:00
# honored options: --kdf --tomb-pwd -o -g -r
2013-05-28 09:57:58 +00:00
gen_key() {
2018-11-01 01:43:49 +00:00
# $1 key file
# $2 the password to use; if not set ask user
2018-01-03 19:27:14 +00:00
# -o is the --cipher-algo to use (string taken by GnuPG)
local algopt="`option_value -o`"
local algo="${algopt:-AES256}"
local gpgpass opt
local recipients_opt
typeset -a gpgopt
2019-03-03 16:56:26 +00:00
local sphx_host_tmp
local sphx_user_tmp
2018-01-03 19:27:14 +00:00
# here user is prompted for key password
tombpass=""
tombpasstmp=""
2019-08-22 12:37:47 +00:00
if option_is_set -g; then
2018-01-03 19:27:14 +00:00
gpgopt=(--encrypt)
2019-08-22 12:37:47 +00:00
if option_is_set -r || option_is_set -R; then
2018-01-03 19:27:14 +00:00
typeset -a recipients
2019-08-22 12:37:47 +00:00
if option_is_set -r; then
2018-01-03 19:27:14 +00:00
recipients=(${(s:,:)$(option_value -r)})
recipients_opt="--recipient"
2019-08-22 12:37:47 +00:00
else
2018-01-03 19:27:14 +00:00
recipients=(${(s:,:)$(option_value -R)})
recipients_opt="--hidden-recipient"
2019-08-22 12:37:47 +00:00
fi
2018-01-03 19:27:14 +00:00
2019-08-22 12:37:47 +00:00
is_valid_recipients $recipients || {
2018-01-03 19:27:14 +00:00
_failure "You set an invalid GPG ID."
}
_warning "You are going to encrypt a tomb key with ::1 nrecipients:: recipient(s)." ${#recipients}
_warning "It is your responsibility to check these fingerprints."
_warning "The fingerprints are:"
for gpg_id in ${recipients[@]}; do
2019-05-05 09:29:25 +00:00
_warning " `_gpg_fingerprint "$gpg_id"` :: `_gpg_uid "$gpg_id"`"
2018-01-03 19:27:14 +00:00
done
gpgopt+=(`_recipients_arg "$recipients_opt" $recipients`)
2019-08-22 12:37:47 +00:00
else
2018-01-03 19:27:14 +00:00
_message "No recipient specified, using default GPG key."
gpgopt+=("--default-recipient-self")
2019-08-22 12:37:47 +00:00
fi
2018-01-03 19:27:14 +00:00
# Set gpg inputs and options
gpgpass="$TOMBSECRET"
opt=''
2022-03-03 09:27:35 +00:00
else
2018-11-01 01:43:49 +00:00
if [ "$2" = "" ]; then
2018-01-03 19:27:14 +00:00
while true; do
# 3 tries to write two times a matching password
tombpass=`ask_password "Type the new password to secure your key"`
if [[ $? != 0 ]]; then
_failure "User aborted."
fi
if [ -z $tombpass ]; then
_failure "You set empty password, which is not possible."
fi
tombpasstmp=$tombpass
tombpass=`ask_password "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
2018-11-01 01:43:49 +00:00
tombpass="$2"
2018-01-03 19:27:14 +00:00
_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
2022-02-20 21:05:01 +00:00
# if [[ "$itertime" != <-> ]]; then
# unset tombpass
# unset tombpasstmp
# _warning "Wrong argument for --kdf: must be an integer number (iteration seconds)."
# _failure "Depending on the speed of machines using this tomb, use 1 to 10, or more"
# return 1
# fi
# # --kdf takes one parameter: iter time (on present machine) in seconds
kdftype="`option_value --kdftype`"
kdftype=${kdftype:-pbkdf2}
case ${kdftype} in
pbkdf2)
local -i microseconds
microseconds=$(( itertime * 1000000 ))
_success "Using KDF, iteration time: ::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"
;;
argon2)
_success "Using KDF Argon2"
kdfmem="`option_value --kdfmem`"
kdfmem=${kdfmem:-18}
_message "memory used: 2^::1 kdfmemory::" $kdfmem
2024-05-12 21:38:25 +00:00
itertime="`option_value --kdf`"
itertime=${itertime:-3}
2022-02-20 21:05:01 +00:00
kdfsalt=`tomb-kdb-pbkdf2-gensalt`
_message "kdf salt: ::1 kdfsalt::" $kdfsalt
_message "kdf iterations: ::1 kdfiterations::" $itertime
tombpass=`argon2 $kdfsalt -m $kdfmem -t $itertime -l 64 -r <<<"${tombpass}"`
header="_KDF_argon2_${kdfsalt}_${itertime}_${kdfmem}_64\n"
;;
esac
2018-01-03 19:27:14 +00:00
}
}
2018-11-01 01:43:49 +00:00
print $header >> "$1"
2018-01-03 19:27:14 +00:00
# Set gpg inputs and options
gpgpass="${tombpass}\n$TOMBSECRET"
gpgopt=(--passphrase-fd 0 --symmetric --no-options)
opt='-n'
2019-08-22 12:37:47 +00:00
fi
2018-01-03 19:27:14 +00:00
_tmp_create
local tmpres=$TOMBTMP
print $opt - "$gpgpass" \
| gpg --openpgp --force-mdc --cipher-algo ${algo} \
2018-08-17 19:03:33 +00:00
--batch --no-tty ${gpgopt} \
2018-11-01 01:43:49 +00:00
--status-fd 2 -o - --armor 2> $tmpres >> "$1"
2018-01-03 19:27:14 +00:00
unset gpgpass
# check result of gpg operation
for i in ${(f)"$(cat $tmpres)"}; do
_verbose "$i"
done
# print -n "${tombpass}" \
# | gpg --openpgp --force-mdc --cipher-algo ${algo} \
# --batch --no-options --no-tty --passphrase-fd 0 --status-fd 2 \
# -o - -c -a ${lukskey}
TOMBPASSWORD="$tombpass" # Set global variable
unset tombpass
unset tombpasstmp
2013-05-28 09:57:58 +00:00
}
# prints an array of ciphers available in gnupg (to encrypt keys)
list_gnupg_ciphers() {
2018-01-07 20:40:32 +00:00
# On gpg1 and gpg2 line 10 always point to available ciphers.
# Print those until the next section is found
2018-01-03 19:27:14 +00:00
ciphers=(`gpg --version | awk '
2013-05-28 09:57:58 +00:00
BEGIN { ciphers=0 }
2018-01-07 20:40:32 +00:00
NR==11 { gsub(/,/,""); sub(/^.*:/,""); print; ciphers=1; next }
/^.*:/ { ciphers=0 }
2013-05-28 09:57:58 +00:00
{ if(ciphers==0) { next } else { gsub(/,/,""); print; } }
'`)
2018-01-07 19:53:20 +00:00
print "${ciphers}"
2018-01-03 19:27:14 +00:00
return 1
2013-05-28 09:57:58 +00:00
}
# Steganographic function to bury a key inside an image.
2013-06-12 11:33:54 +00:00
# Requires steghide(1) to be installed
2013-05-28 09:57:58 +00:00
bury_key() {
2014-11-04 04:04:18 +00:00
2018-01-03 19:27:14 +00:00
_load_key # Try loading key from option -k and set TOMBKEY
imagefile=$PARAM
[[ "`file $imagefile`" =~ "JPEG" ]] || {
_warning "Encode failed: ::1 image file:: is not a jpeg image." $imagefile
return 1
}
_success "Encoding key ::1 tomb key:: inside image ::2 image file::" $TOMBKEY $imagefile
{ option_is_set -g } && {
_message "Using GnuPG Key ID"
} || {
_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 it isn't strictly necessary (and having different
# password would enhance security). Nevertheless here we prefer
# usability.
# However, steganography cannot be done with GPG key. Therefore,
# if using a GPG key, we test if the user can decrypt the tomb
# with its key and we ask for a steganography password.
{ option_is_set --tomb-pwd } && { ! option_is_set -g } && {
local tombpwd="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 tomb pass::" $tombpwd
ask_key_password "$tombpwd"
} || {
ask_key_password
}
[[ $? != 0 ]] && {
_warning "Wrong password/GnuPG ID supplied."
_failure "You shall not bury a key whose password is unknown to you." }
if option_is_set -g && option_is_set --tomb-pwd; then
TOMBPASSWORD="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 tomb pass::" $TOMBPASSWORD
elif option_is_set -g; then
tombpass=""
tombpasstmp=""
while true; do
# 3 tries to write two times a matching password
tombpass=`ask_password "Type a password to bury your key"`
if [[ $? != 0 ]]; then
_failure "User aborted."
fi
if [ -z $tombpass ]; then
_failure "You set empty password, which is not possible."
fi
tombpasstmp=$tombpass
tombpass=`ask_password "Type a password to bury your key (again)"`
if [[ $? != 0 ]]; then
_failure "User aborted."
fi
if [ "$tombpasstmp" = "$tombpass" ]; then
break;
fi
unset tombpasstmp
unset tombpass
done
TOMBPASSWORD="$tombpass"
fi
# We omit armor strings since having them as constants can give
# ground to effective attacks on steganography
print - "$TOMBKEY" | awk '
2011-12-01 17:53:12 +00:00
/^-----/ {next}
/^Version/ {next}
2014-08-25 21:32:32 +00:00
{print $0}' \
2018-01-03 19:27:14 +00:00
| steghide embed --embedfile - --coverfile ${imagefile} \
-p $TOMBPASSWORD -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
2011-12-01 17:53:12 +00:00
}
2014-08-05 15:05:49 +00:00
# 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)
2013-05-28 09:57:58 +00:00
exhume_key() {
2020-12-15 17:22:38 +00:00
[[ -z $1 ]] && {
2018-01-03 19:27:14 +00:00
_failure "Exhume failed, no image specified" }
local imagefile="$1" # The image file where to look for the key
local tombpass="$2" # (Optional) the password to use (internal use)
local destkey="$3" # (Optional) the key file where to save the
# result (- for stdout)
local r=1 # Return code (default: fail)
2018-11-01 01:43:49 +00:00
# write all messages to stderr to avoid polluting stdout
_MSG_FD_OVERRIDE=2
2018-01-03 19:27:14 +00:00
# Ensure the image file is a readable JPEG
[[ ! -r $imagefile ]] && {
_failure "Exhume failed, image file not found: ::1 image file::" "${imagefile:-none}" }
[[ ! $(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)
[[ -n "$tombpass" ]] && {
TOMBKEY=$(steghide extract -sf $imagefile -p $tombpass -xf -)
[[ $? != 0 ]] && {
_failure "Wrong password or no steganographic key found" }
recover_key $TOMBKEY
return 0
}
# Ensure we have a valid destination for the key
[[ -z $destkey ]] && { option_is_set -k } && destkey=$(option_value -k)
[[ -z $destkey ]] && {
destkey="-" # No key was specified: fallback to stdout
_message "printing exhumed key on stdout" }
# Bail out if destination exists, unless -f (force) was passed
[[ $destkey != "-" && -s $destkey ]] && {
_warning "File exists: ::1 tomb key::" $destkey
{ option_is_set -f } && {
_warning "Use of --force selected: overwriting."
rm -f $destkey
} || {
_warning "Make explicit use of --force to overwrite."
_failure "Refusing to overwrite file. Operation aborted." }
}
_message "Trying to exhume a key out of image ::1 image file::" $imagefile
{ option_is_set --tomb-pwd } && {
tombpass=$(option_value --tomb-pwd)
_verbose "tomb-pwd = ::1 tomb pass::" $tombpass
} || {
[[ -n $TOMBPASSWORD ]] && tombpass=$TOMBPASSWORD
} || {
tombpass=$(ask_password "Insert password to exhume key from $imagefile")
[[ $? != 0 ]] && {
_warning "User aborted password dialog."
return 1
}
}
# Extract the key from the image
steghide extract -sf $imagefile -p ${tombpass} -xf $destkey
r=$?
# Report to the user
[[ "$destkey" = "-" ]] && destkey="stdout"
[[ $r == 0 ]] && {
_success "Key succesfully exhumed to ::1 key::." $destkey
} || {
_warning "Nothing found in ::1 image file::" $imagefile
}
2018-11-01 01:43:49 +00:00
unset _MSG_FD_OVERRIDE
2018-01-03 19:27:14 +00:00
return $r
2011-12-01 17:53:12 +00:00
}
2012-01-17 16:28:40 +00:00
2019-02-21 09:28:21 +00:00
# Steganographic function to transform a key into harmless-looking text
# using a cipher
# Requires cloakify to be installed
#
# mandatory 1st arg: the cipher to use
# optional 2nd arg: the output file where to save the result (none for stdout)
cloakify_key() {
_load_key # Try loading key from option -k and set TOMBKEY
local cipher="$1" # The cipher to use
local destfile="$2" # (Optional) the output file where to save the
# result (none for stdout)
2024-05-12 22:31:07 +00:00
[[ -r "${cipher}" ]] ||
_failure "Cloak cipher file not found, see tomb/extras/cloak/ciphers"
2019-02-21 09:28:21 +00:00
_success "Encoding key ::1 tomb key:: using cipher ::2 cipher file::" $TOMBKEYFILE $cipher
# Ensure we have a valid destination for the cloaked key
[[ -z $destfile ]] && {
destfile="/dev/stdout" # No file was specified: fallback to stdout
_message "printing cloaked key on stdout" }
# Bail out if destination exists, unless -f (force) was passed
[[ $destfile != "/dev/stdout" && -s $destfile ]] && {
_warning "File exists: ::1 output file::" $destfile
{ option_is_set -f } && {
_warning "Use of --force selected: overwriting."
rm -f $destfile
} || {
_warning "Make explicit use of --force to overwrite."
_failure "Refusing to overwrite file. Operation aborted." }
}
# Cipher the key
2024-05-12 22:31:07 +00:00
cloakify -i $TOMBKEYFILE -c $cipher >$destfile
2019-02-21 09:28:21 +00:00
if [ $? != 0 ]; then
_warning "Encoding error: cloakify reports problems."
res=1
else
_success "Tomb key encoded succesfully"
res=0
fi
return $res
}
# mandatory 1st arg: the text file where key is supposed to be
# mandatory 2nd arg: the cipher to use
# optional 3rd arg: the key where to save the result (none for stdout)
decloakify_key() {
2020-12-15 17:22:38 +00:00
[[ -z $1 ]] && {
2019-02-21 09:28:21 +00:00
_failure "Uncloak failed, no text file specified" }
2020-12-15 17:22:38 +00:00
[[ -z $2 ]] && {
2019-02-21 09:28:21 +00:00
_failure "Uncloak failed, no cipher file specified" }
local textfile="$1" # The text file where to look for the key
local cipher="$2" # The cipher to use
local destkey="$3" # (Optional) the key file where to save the
# result (none for stdout)
local r=1 # Return code (default: fail)
# write all messages to stderr to avoid polluting stdout
_MSG_FD_OVERRIDE=2
# Ensure the text file is readable
[[ ! -r $textfile ]] && {
_failure "Uncloak failed, text file not found: ::1 text file::" "${textfile:-none}" }
# Ensure the cipher file is readable
[[ ! -r $cipher ]] && {
_failure "Uncloak failed, cipher file not found: ::1 cipher file::" "${cipher:-none}" }
# Ensure we have a valid destination for the key
[[ -z $destkey ]] && { option_is_set -k } && destkey=$(option_value -k)
[[ -z $destkey ]] && {
2024-05-12 22:31:07 +00:00
# No key was specified: fallback to stdout
2019-02-21 09:28:21 +00:00
_message "printing uncloaked key on stdout" }
# Bail out if destination exists, unless -f (force) was passed
[[ $destkey != "/dev/stdout" && -s $destkey ]] && {
_warning "File exists: ::1 tomb key::" $destkey
{ option_is_set -f } && {
_warning "Use of --force selected: overwriting."
rm -f $destkey
} || {
_warning "Make explicit use of --force to overwrite."
_failure "Refusing to overwrite file. Operation aborted." }
}
# Extract the key from the text file
2024-05-12 22:31:07 +00:00
if [[ -z "$destkey" ]]; then
decloakify -i "${textfile}" -c "${cipher}"
else
decloakify -i "${textfile}" -c "${cipher}" -o "${destkey}"
fi
2019-02-21 09:28:21 +00:00
r=$?
# Report to the user
2024-05-12 22:31:07 +00:00
[[ -z "$destkey" ]] && destkey="stdout"
2019-02-21 09:28:21 +00:00
[[ $r == 0 ]] && {
_success "Key succesfully uncloaked to ::1 key::." $destkey
} || {
_warning "Nothing found in ::1 text file::" $textfile
}
unset _MSG_FD_OVERRIDE
return $r
}
2015-09-20 21:32:00 +00:00
# Produces a printable image of the key contents so a backup on paper
# can be made and hidden in books etc.
2013-06-20 08:26:12 +00:00
engrave_key() {
2014-11-04 04:04:18 +00:00
2018-01-03 19:27:14 +00:00
_load_key # Try loading key from option -k and set TOMBKEYFILE
2014-10-28 18:46:36 +00:00
2018-01-03 19:27:14 +00:00
local keyname=$(basename $TOMBKEYFILE)
local pngname="$keyname.qr.png"
2013-06-19 18:52:21 +00:00
2018-01-03 19:27:14 +00:00
_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
[[ $? != 0 ]] && {
_failure "QREncode reported an error." }
2014-10-28 18:46:36 +00:00
2018-01-03 19:27:14 +00:00
_success "Operation successful:"
# TODO: only if verbose and/or not silent
ls -lh $pngname
file $pngname
2013-06-19 18:52:21 +00:00
}
2013-05-28 09:57:58 +00:00
# }}} - Key handling
2011-12-01 19:27:05 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Create
2011-12-01 19:04:56 +00:00
2014-10-23 05:10:24 +00:00
# Since version 1.5.3, tomb creation is a three-step process that replaces create_tomb():
2013-05-28 09:57:58 +00:00
#
2014-04-28 12:56:21 +00:00
# * dig a .tomb (the large file) using /dev/urandom (takes some minutes at least)
2013-05-28 09:57:58 +00:00
#
2014-04-28 12:56:21 +00:00
# * forge a .key (the small file) using /dev/random (good entropy needed)
2013-05-28 09:57:58 +00:00
#
# * lock the .tomb file with the key, binding the key to the tomb (requires dm_crypt format)
2014-10-23 05:10:24 +00:00
# Step one - Dig a tomb
#
2015-11-07 13:20:43 +00:00
# Synopsis: dig_tomb /path/to/tomb -s sizemebibytes
2014-10-23 05:10:24 +00:00
#
# 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() {
2020-11-17 07:19:36 +00:00
# $1 arg is path to tomb
2018-01-03 19:27:14 +00:00
# Require the specification of the size of the tomb (-s) in MiB
local -i tombsize=$(option_value -s)
2014-10-23 05:10:24 +00:00
2018-01-03 19:27:14 +00:00
_message "Commanded to dig tomb ::1 tomb path::" $tombpath
2014-10-23 05:10:24 +00:00
2020-12-15 17:22:38 +00:00
[[ ! -z $1 ]] || _failure "Missing path to tomb"
2018-01-03 19:27:14 +00:00
[[ -n "$tombsize" ]] || _failure "Size argument missing, use -s"
[[ $tombsize == <-> ]] || _failure "Size must be an integer (mebibytes)"
[[ $tombsize -ge 10 ]] || _failure "Tombs can't be smaller than 10 mebibytes"
2014-10-23 05:10:24 +00:00
2020-11-17 07:19:36 +00:00
[[ -e $1 ]] && {
2018-01-03 19:27:14 +00:00
_warning "A tomb exists already. I'm not digging here:"
2020-11-17 07:19:36 +00:00
ls -lh $1
2018-01-03 19:27:14 +00:00
return 1
}
2014-10-23 05:10:24 +00:00
2020-11-17 07:19:36 +00:00
_success "Creating a new tomb in ::1 tomb path::" $1
_message "Generating ::1 tomb file:: of ::2 size::MiB" $1 $tombsize
2014-10-23 05:10:24 +00:00
2020-11-17 07:19:36 +00:00
touch "$1"
2018-01-03 19:27:14 +00:00
[[ $? = 0 ]] || {
2020-11-17 07:19:36 +00:00
_warning "Error creating the tomb ::1 tomb path::" $1
2018-01-03 19:27:14 +00:00
_failure "Operation aborted."
}
2020-11-17 07:19:36 +00:00
# Ensure that file permissions are safe even if interrupted
2021-01-01 20:02:54 +00:00
[[ -n $SUDO_USER ]] && chown ${_UID}:${_GID} "$1"
2020-11-17 07:19:36 +00:00
chmod 0600 $1
2018-01-03 19:27:14 +00:00
_verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]}
2020-11-17 07:19:36 +00:00
${=DD} if=/dev/urandom bs=1048576 count=$tombsize of=$1
ls -lh "$1"
2014-10-23 05:10:24 +00:00
2020-11-17 07:19:36 +00:00
_success "Done digging ::1 tomb name::" $1
2018-01-03 19:27:14 +00:00
_message "Your tomb is not yet ready, you need to forge a key and lock it:"
2020-11-17 07:19:36 +00:00
_message "tomb forge ::1 tomb path::.key" $1
_message "tomb lock ::1 tomb path:: -k ::1 tomb path::.key" $1
2014-10-23 05:10:24 +00:00
2018-01-03 19:27:14 +00:00
return 0
2014-10-23 05:10:24 +00:00
}
2014-12-26 23:54:51 +00:00
# Step two -- Create a detached key to lock a tomb with
#
2017-03-24 20:08:33 +00:00
# Synopsis: forge_key [destkey|-k destkey] [-o cipher] [-r|-R gpgid]
2014-12-26 23:54:51 +00:00
#
# Arguments:
2018-01-03 19:27:14 +00:00
# -k path to destination keyfile
# -o Use an alternate algorithm
# -r GPG recipients to be used
2014-12-26 23:54:51 +00:00
#
2013-03-22 20:13:59 +00:00
forge_key() {
2018-01-03 19:27:14 +00:00
# can be specified both as simple argument or using -k
local destkey="$1"
{ option_is_set -k } && { destkey=$(option_value -k) }
local algo="AES256" # Default encryption algorithm
[[ -z "$destkey" ]] && {
_failure "A filename needs to be specified using -k to forge a new key." }
# _message "Commanded to forge key ::1 key::" $destkey
_check_swap # Ensure the available memory is safe to use
# Ensure GnuPG won't exit with an error before first run
2020-11-13 22:16:05 +00:00
local gpghome=${GNUPGHOME:-$HOME/.gnupg}
[[ -r $gpghome/pubring.gpg ]] || {
mkdir -p -m 0700 $gpghome
touch $gpghome/pubring.gpg }
2018-01-03 19:27:14 +00:00
# Do not overwrite any files accidentally
[[ -r "$destkey" ]] && {
ls -lh $destkey
_failure "Forging this key would overwrite an existing file. Operation aborted." }
touch $destkey
[[ $? == 0 ]] || {
_warning "Cannot generate encryption key."
_failure "Operation aborted." }
chmod 0600 $destkey
# Update algorithm if it was passed on the command line with -o
{ option_is_set -o } && algopt="$(option_value -o)"
[[ -n "$algopt" ]] && algo=$algopt
_message "Commanded to forge key ::1 key:: with cipher algorithm ::2 algorithm::" \
$destkey $algo
[[ $KDF == 1 ]] && { ! option_is_set -g } && {
_message "Using KDF to protect the key password (`option_value --kdf` rounds)"
}
TOMBKEYFILE="$destkey" # Set global variable
_warning "This operation takes time. Keep using this computer on other tasks."
_warning "Once done you will be asked to choose a password for your tomb."
_warning "To make it faster you can move the mouse around."
_warning "If you are on a server, you can use an Entropy Generation Daemon."
2019-05-22 07:55:02 +00:00
# Use /dev/urandom as the entropy source, unless --use-random is specified
local random_source=/dev/urandom
{ option_is_set --use-random } && random_source=/dev/random
2018-01-03 19:27:14 +00:00
_verbose "Data dump using ::1:: from ::2 source::" ${DD[1]} $random_source
TOMBSECRET=$(${=DD} bs=1 count=512 if=$random_source)
[[ $? == 0 ]] || {
_warning "Cannot generate encryption key."
_failure "Operation aborted." }
# Here the global variable TOMBSECRET contains the naked secret
{ option_is_set -g } && {
_success "Using GnuPG key(s) to encrypt your key: ::1 tomb key::" $TOMBKEYFILE
} || {
_success "Choose the password of your key: ::1 tomb key::" $TOMBKEYFILE
}
_message "(You can also change it later using 'tomb passwd'.)"
# _user_file $TOMBKEYFILE
tombname="$TOMBKEYFILE" # XXX ???
# the gen_key() function takes care of the new key's encryption
{ option_is_set --tomb-pwd } && {
local tombpwd="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 new pass::" $tombpwd
2018-11-01 01:43:49 +00:00
gen_key $TOMBKEYFILE "$tombpwd"
2018-01-03 19:27:14 +00:00
} || {
2018-11-01 01:43:49 +00:00
gen_key $TOMBKEYFILE
2018-01-03 19:27:14 +00:00
}
# load the key contents (set global variable)
TOMBKEY="${mapfile[$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:"
print "${mapfile[$TOMBKEY]}"
_warning "--"
2019-08-22 09:47:14 +00:00
rm -f ${TOMBKEYFILE}
2018-01-03 19:27:14 +00:00
_failure "Operation aborted."
}
2021-01-01 20:46:11 +00:00
[[ -n $SUDO_USER ]] && chown ${_UID}:${_GID} "$TOMBKEYFILE"
2018-01-03 19:27:14 +00:00
_message "Done forging ::1 key file::" $TOMBKEYFILE
_success "Your key is ready:"
ls -lh $TOMBKEYFILE
2013-03-22 20:13:59 +00:00
}
2014-10-23 05:10:24 +00:00
# Step three -- Lock tomb
#
2017-02-03 18:53:31 +00:00
# Synopsis: tomb_lock file.tomb file.tomb.key [-o cipher] [-r gpgid]
2014-10-23 05:10:24 +00:00
#
# Lock the given tomb with the given key file, in fact formatting the
2014-12-26 23:54:51 +00:00
# loopback volume as a LUKS device.
2019-11-18 09:17:38 +00:00
# Default cipher 'aes-xts-plain64'can be overridden with -o
2013-03-22 21:22:55 +00:00
lock_tomb_with_key() {
2018-01-03 19:27:14 +00:00
# old default was aes-cbc-essiv:sha256
# Override with -o
# for more alternatives refer to cryptsetup(8)
2019-05-01 20:43:04 +00:00
local cipher="aes-xts-plain64"
2014-12-26 23:54:51 +00:00
2018-01-03 19:27:14 +00:00
local tombpath="$1" # First argument is the path to the tomb
2014-10-23 05:10:24 +00:00
2018-01-03 19:27:14 +00:00
[[ -n $tombpath ]] || {
_warning "No tomb specified for locking."
2019-04-18 11:24:30 +00:00
_warning "Usage: tomb lock file.tomb -k file.tomb.key"
2018-01-03 19:27:14 +00:00
return 1
}
2013-03-22 21:22:55 +00:00
2022-03-03 09:27:35 +00:00
2020-11-16 22:35:03 +00:00
is_valid_tomb $tombpath
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_message "Commanded to lock tomb ::1 tomb file::" $TOMBFILE
2014-10-09 22:05:00 +00:00
2018-01-03 19:27:14 +00:00
[[ -f $TOMBPATH ]] || {
_failure "There is no tomb here. You have to dig it first." }
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_verbose "Tomb found: ::1 tomb path::" $TOMBPATH
2013-03-22 21:22:55 +00:00
2020-12-29 12:50:04 +00:00
local filesystem=ext4
2024-08-31 03:47:30 +00:00
option_is_set --filesystem && {
2020-12-29 12:50:04 +00:00
filesystem=`option_value --filesystem`
2022-10-25 11:45:34 +00:00
local tombsize=`stat --format '%s' $tombpath`
2020-12-29 12:50:04 +00:00
case $filesystem in
ext3|ext4) ;;
2022-10-25 11:45:34 +00:00
ext3maxinodes|ext4maxinodes) ;;
btrfs)
2024-08-31 03:53:47 +00:00
if [[ $tombsize -lt 114294784 ]]; then
_failure "Filesystem ::1 filesystem:: not supported on tombs smaller than ::2 size::" \
$filesystem "114MB"
2022-10-25 11:45:34 +00:00
fi
;;
btrfsmixedmode)
2023-09-30 20:39:35 +00:00
if [[ $tombsize -lt 18874368 ]]; then
2024-08-31 03:53:47 +00:00
_failure "Filesystem ::1 filesystem:: not supported on tombs smaller than ::2 size::" \
$filesystem "18MB"
2022-10-25 11:45:34 +00:00
fi
;;
2020-12-29 12:50:04 +00:00
*)
_failure "Filesystem not supported: ::1 filesystem::" $filesystem
return 1
;;
esac
2021-01-25 17:26:49 +00:00
_success "Selected filesystem type $filesystem."
2020-12-29 12:50:04 +00:00
}
2024-08-05 13:26:08 +00:00
lo_check "$TOMBPATH"
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_message "Checking if the tomb is empty (we never step on somebody else's bones)."
2024-08-05 13:26:08 +00:00
_sudo cryptsetup isLuks ${TOMBPATH}
2018-01-03 19:27:14 +00:00
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
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_load_key # Try loading key from option -k and set TOMBKEYFILE
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
# the encryption cipher for a tomb can be set when locking using -c
{ option_is_set -o } && algopt="$(option_value -o)"
[[ -n "$algopt" ]] && cipher=$algopt
_message "Locking using cipher: ::1 cipher::" $cipher
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
# 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
[[ $? == 0 ]] || _failure "No valid password supplied."
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_success "Locking ::1 tomb file:: with ::2 tomb key file::" $TOMBFILE $TOMBKEYFILE
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
_message "Formatting Luks mapped device."
_cryptsetup --batch-mode \
2019-05-01 20:43:04 +00:00
--cipher ${cipher} --hash sha512 --key-size 512 --key-slot 0 \
2024-08-05 13:26:08 +00:00
luksFormat ${TOMBPATH}
2018-01-03 19:27:14 +00:00
[[ $? == 0 ]] || {
_warning "cryptsetup luksFormat returned an error."
_failure "Operation aborted." }
2013-05-25 13:05:21 +00:00
2024-08-05 13:26:08 +00:00
_cryptsetup --cipher ${cipher} --hash sha512 luksOpen ${TOMBPATH} tomb.tmp
2018-01-03 19:27:14 +00:00
[[ $? == 0 ]] || {
_warning "cryptsetup luksOpen returned an error."
_failure "Operation aborted." }
2013-03-22 21:22:55 +00:00
2020-12-29 12:50:04 +00:00
_message "Formatting your Tomb with $filesystem filesystem."
case $filesystem in
ext3|ext4)
_sudo mkfs.${filesystem} -q -F -j -L $TOMBNAME /dev/mapper/tomb.tmp
;;
2022-10-25 11:45:34 +00:00
ext3maxinodes|ext4maxinodes) # TODO: cover with test
filesystem=${filesystem:0:4}
_sudo mkfs.${filesystem} -q -F -j -i 1024 -b 1024 -L $TOMBNAME /dev/mapper/tomb.tmp
;;
2020-12-29 12:50:04 +00:00
btrfs) # TODO: cover with test
_sudo mkfs.${filesystem} -q -L $TOMBNAME /dev/mapper/tomb.tmp
;;
2022-10-25 11:45:34 +00:00
btrfsmixedmode) # TODO: cover with test
filesystem=${filesystem:0:5}
_sudo mkfs.${filesystem} -q -M -L $TOMBNAME /dev/mapper/tomb.tmp
;;
2020-12-29 12:50:04 +00:00
esac
2013-03-22 21:22:55 +00:00
2018-01-03 19:27:14 +00:00
[[ $? == 0 ]] || {
_warning "Tomb format returned an error."
2020-12-29 09:56:20 +00:00
_sudo cryptsetup luksClose tomb.tmp
_failure "Your tomb ::1 tomb file:: may be corrupted." $TOMBFILE }
2013-05-28 09:57:58 +00:00
2018-01-03 19:27:14 +00:00
# Sync
_sudo cryptsetup luksClose tomb.tmp
2013-05-28 09:57:58 +00:00
2018-01-03 19:27:14 +00:00
_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 ::2 tomb key::" \
$TOMBPATH $TOMBKEYFILE
2020-12-29 10:52:23 +00:00
return 0
2012-09-05 15:47:00 +00:00
}
2013-06-19 18:20:17 +00:00
# This function changes the key that locks a tomb
change_tomb_key() {
2018-01-03 19:27:14 +00:00
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
is_valid_tomb $tombpath
2024-08-05 13:26:08 +00:00
lo_check "$TOMBPATH"
_sudo cryptsetup isLuks ${TOMBPATH}
2018-01-03 19:27:14 +00:00
# is it a LUKS encrypted nest? we check one more time
[[ $? == 0 ]] || {
_failure "Not a valid LUKS encrypted volume: ::1 volume::" $TOMBPATH }
2020-11-13 21:49:40 +00:00
_load_key $tombkey # Try loading given key and set TOMBKEY
2018-01-03 19:27:14 +00:00
# TOMBKEYFILE
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::" $oldkeyfile
# 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
[[ $? == 0 ]] || {
_failure "No valid password supplied for the old key." }
old_secret=$TOMBSECRET
# luksOpen the tomb (not really mounting, just on the loopback)
print -R -n - "$old_secret" | _sudo cryptsetup --key-file - \
2024-08-05 13:26:08 +00:00
luksOpen ${TOMBPATH} ${TOMBMAPPER}
2018-01-03 19:27:14 +00:00
[[ $? == 0 ]] || _failure "Unexpected error in luksOpen."
_load_key # Try loading new key from option -k and set TOMBKEYFILE
_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
[[ $? == 0 ]] || {
_failure "No valid password supplied for the new key." }
_tmp_create
tmpnewkey=$TOMBTMP
print -R -n - "$TOMBSECRET" >> $tmpnewkey
print -R -n - "$old_secret" | _sudo cryptsetup --key-file - \
2024-08-05 13:26:08 +00:00
luksChangeKey "$TOMBPATH" "$tmpnewkey"
2018-01-03 19:27:14 +00:00
[[ $? == 0 ]] || _failure "Unexpected error in luksChangeKey."
2020-11-16 22:35:03 +00:00
_sudo cryptsetup luksClose "${TOMBMAPPER}" || _failure "Unexpected error in luksClose."
2018-01-03 19:27:14 +00:00
2022-10-17 21:47:20 +00:00
_success "Successfully changed key for tomb: ::1 tomb file::" $TOMBFILE
2018-01-03 19:27:14 +00:00
_message "The new key is: ::1 new key::" $TOMBKEYFILE
return 0
2013-06-19 18:20:17 +00:00
}
2013-05-28 09:57:58 +00:00
# }}} - Creation
2011-12-01 19:04:56 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Open
2011-12-01 19:04:56 +00:00
2018-01-03 11:12:19 +00:00
_update_control_file() {
2019-11-18 09:15:12 +00:00
# make sure a control file exists, gives it user ownership
# and replaces it with new contents
2018-01-03 11:12:19 +00:00
# stdin = contents
# $1 = path to control file
# $2 = contents
2020-12-15 17:22:38 +00:00
[[ -z $2 ]] && return 1
2019-06-26 06:56:05 +00:00
_sudo touch "$1"
2018-01-03 11:12:19 +00:00
_sudo chown ${_UID}:${_GID} "$1"
2019-11-18 09:15:12 +00:00
print "$2" > "$1"
2018-01-03 11:12:19 +00:00
_verbose "updated control file $1 = $2"
}
2020-12-29 12:50:04 +00:00
_detect_filesystem() {
local device=$1
_verbose "detecting filesystem of ::1 device::" $device
print "`lsblk -in -o FSTYPE $device`"
}
2012-01-17 15:49:03 +00:00
# $1 = tombfile $2(optional) = mountpoint
2010-08-22 14:44:35 +00:00
mount_tomb() {
2020-11-16 22:35:03 +00:00
[[ -n "$1" ]] || _failure "No tomb name specified for opening."
2018-01-03 19:27:14 +00:00
2020-11-16 22:35:03 +00:00
_message "Commanded to open tomb ::1 tomb name::" $1
2018-01-03 19:27:14 +00:00
_check_swap
2020-11-16 22:35:03 +00:00
is_valid_tomb $1
2018-01-03 19:27:14 +00:00
2020-11-16 22:35:03 +00:00
_track_stat "$TOMBPATH"
2018-09-23 21:21:05 +00:00
2018-01-03 19:27:14 +00:00
_load_key # Try loading new key from option -k and set TOMBKEYFILE
tombmount="$2"
2022-02-20 20:10:47 +00:00
[[ -z "$tombmount" ]] && {
tombmount="/media/$TOMBNAME"
2018-01-03 19:27:14 +00:00
[[ -d /media ]] || { # no /media found, adopting /run/media/$USER (udisks2 compat)
2022-02-20 20:10:47 +00:00
tombmount="/run/media/$_USER/$TOMBNAME"
2018-01-03 19:27:14 +00:00
}
2022-02-20 20:10:47 +00:00
_message "Mountpoint not specified, using default: ::1 mount point::" "$tombmount"
2018-01-03 19:27:14 +00:00
}
2022-02-20 20:10:47 +00:00
_success "Opening ::1 tomb file:: on ::2 mount point::" $TOMBNAME "$tombmount"
2020-11-13 21:49:40 +00:00
2019-05-21 22:30:48 +00:00
# check if the mountpoint is already used
mounted_tombs=(`list_tomb_mounts`)
for t in ${mounted_tombs}; do
usedmount=${t[(ws:;:)2]}
[[ "$usedmount" == "$tombmount" ]] &&
2022-02-20 20:10:47 +00:00
_failure "Mountpoint already in use: ::1 mount point::" "$tombmount"
2019-05-21 22:30:48 +00:00
done
2018-01-03 19:27:14 +00:00
2024-08-05 13:26:08 +00:00
lo_check "$TOMBPATH"
_sudo cryptsetup isLuks ${TOMBPATH} || {
2018-01-03 19:27:14 +00:00
# is it a LUKS encrypted nest? see cryptsetup(1)
_failure "::1 tomb file:: is not a valid Luks encrypted storage file." $TOMBFILE }
_message "This tomb is a valid LUKS encrypted device."
2024-08-05 13:26:08 +00:00
luksdump="`_sudo cryptsetup luksDump ${TOMBPATH}`"
2018-01-03 19:27:14 +00:00
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" }'`
[[ "$slotwarn" == "WARN" ]] && {
_warning "Multiple key slots are enabled on this tomb. Beware: there can be a backdoor." }
_verbose "Tomb key: ::1 key file::" $TOMBKEYFILE
# take the name only, strip extensions
_verbose "Tomb name: ::1 tomb name:: (to be engraved)" $TOMBNAME
{ option_is_set --tomb-pwd } && { ! option_is_set -g } && {
tomb_pwd="`option_value --tomb-pwd`"
_verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd
ask_key_password "$tomb_pwd"
} || {
ask_key_password
}
[[ $? == 0 ]] || _failure "No valid password supplied."
2024-08-05 13:26:08 +00:00
_cryptsetup luksOpen ${TOMBPATH} ${TOMBMAPPER}
2018-01-03 19:27:14 +00:00
[[ $? = 0 ]] || {
_failure "Failure mounting the encrypted file." }
# array: [ cipher, keysize, loopdevice ]
2020-11-16 22:35:03 +00:00
tombstat=(`_sudo cryptsetup status ${TOMBMAPPER} | awk '
2018-01-03 19:27:14 +00:00
/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]
2020-12-29 12:50:04 +00:00
filesystem=`_detect_filesystem /dev/mapper/${TOMBMAPPER}`
_message "Filesystem detected: ::1 filesystem::" $filesystem
2024-08-05 13:26:08 +00:00
# TODO: check if FS is supported, else close luks
2020-12-29 12:50:04 +00:00
2018-01-03 19:27:14 +00:00
_verbose "Tomb engraved as ::1 tomb name::" $TOMBNAME
2020-12-29 12:50:04 +00:00
2021-01-25 17:26:49 +00:00
if option_value_contains -o ro; then
_message "Skipping filesystem checks in read-only"
else
_message "Checking filesystem via ::1::" $tombstat[3]
case $filesystem in
ext3|ext4)
2021-06-24 16:57:23 +00:00
if option_is_set -q; then
_sudo fsck -p -C0 /dev/mapper/${TOMBMAPPER} > /dev/null
else
_sudo fsck -p -C0 /dev/mapper/${TOMBMAPPER}
fi
2021-01-25 17:26:49 +00:00
# TODO: btrfs filesystem label [<device>|<mount_point>] [<newlabel>]
_sudo tune2fs -L $TOMBNAME /dev/mapper/${TOMBMAPPER} > /dev/null
;;
btrfs)
_sudo btrfs check /dev/mapper/${TOMBMAPPER}
_sudo btrfs filesystem label /dev/mapper/${TOMBMAPPER} ${TOMBNAME}
;;
esac
fi
2018-01-03 19:27:14 +00:00
# we need root from here on
2022-02-20 20:10:47 +00:00
_sudo mkdir -p "$tombmount"
2018-01-03 19:27:14 +00:00
# Default mount options are overridden with the -o switch
{ option_is_set -o } && {
local oldmountopts=$MOUNTOPTS
MOUNTOPTS="$(option_value -o)" }
# TODO: safety check MOUNTOPTS
# safe_mount_options &&
2022-02-20 20:10:47 +00:00
_sudo mount -o $MOUNTOPTS /dev/mapper/${TOMBMAPPER} "${tombmount}"
2018-01-03 19:27:14 +00:00
# Clean up if the mount failed
[[ $? == 0 ]] || {
2022-02-20 20:10:47 +00:00
_warning "Error mounting ::1 mapper:: on ::2 tombmount::" $TOMBMAPPER "$tombmount"
2018-01-03 19:27:14 +00:00
[[ $oldmountopts != $MOUNTOPTS ]] && \
_warning "Are mount options '::1 mount options::' valid?" $MOUNTOPTS
# TODO: move cleanup to _endgame()
2022-02-20 20:10:47 +00:00
[[ -d "$tombmount" ]] && _sudo rmdir "$tombmount"
2020-11-16 22:35:03 +00:00
[[ -e /dev/mapper/$TOMBMAPPER ]] && _sudo cryptsetup luksClose $TOMBMAPPER
2018-01-03 19:27:14 +00:00
_failure "Cannot mount ::1 tomb name::" $TOMBNAME
}
2022-02-20 20:10:47 +00:00
_success "Success opening ::1 tomb file:: on ::2 mount point::" $TOMBFILE "$tombmount"
2018-01-03 19:27:14 +00:00
local tombtty tombhost tombuid tombuser
# print out when it was opened the last time, by whom and where
2022-02-20 20:10:47 +00:00
[[ -r "${tombmount}/.last" ]] && {
tombsince=$(cat "${tombmount}/.last")
2018-01-03 19:27:14 +00:00
tombsince=$(date --date=@$tombsince +%c)
2022-02-20 20:10:47 +00:00
tombtty=$(cat "${tombmount}/.tty")
tombhost=$(cat "${tombmount}/.host")
tomblast=$(cat "${tombmount}/.last")
tombuid=$(cat "${tombmount}/.uid" | tr -d ' ')
2018-01-03 19:27:14 +00:00
2019-08-22 15:07:12 +00:00
tombuser=`_get_username $tombuid`
2018-01-03 19:27:14 +00:00
_message "Last visit by ::1 user::(::2 tomb build::) from ::3 tty:: on ::4 host::" $tombuser $tombuid $tombtty $tombhost
_message "on date ::1 date::" $tombsince
2022-10-11 06:26:37 +00:00
[[ -r "${tombmount}"/.cleanexit ]] || _message "the door was slammed or shutdown called before umount."
2018-01-03 19:27:14 +00:00
}
# write down the UID and TTY that opened the tomb
2021-01-25 17:26:49 +00:00
option_value_contains -o ro || {
2022-02-20 20:10:47 +00:00
_update_control_file "${tombmount}/.uid" $_UID
_update_control_file "${tombmount}/.tty" $_TTY
2021-01-25 17:26:49 +00:00
# also the hostname
2022-02-20 20:57:05 +00:00
if command -v hostname >/dev/null; then
_update_control_file "${tombmount}/.host" `hostname`
elif [[ -r /etc/hostname ]]; then
2023-12-16 13:33:24 +00:00
_update_control_file "${tombmount}/.host" $(cat /etc/hostname)
2022-02-20 20:57:05 +00:00
else
_update_control_file "${tombmount}/.host" localhost
fi
2021-01-25 17:26:49 +00:00
# and the "last time opened" information
# in minutes since 1970, this is printed at next open
2022-02-20 20:10:47 +00:00
_update_control_file "${tombmount}/.last" `date +%s`
2021-01-25 17:26:49 +00:00
# human readable: date --date=@"`cat .last`" +%c
}
2018-01-03 19:27:14 +00:00
# process bind-hooks (mount -o bind of directories)
# and exec-hooks (execute on open)
option_is_set -n || {
2022-02-20 20:10:47 +00:00
exec_safe_bind_hooks "${tombmount}"
exec_safe_func_hooks open "${tombmount}"
2017-06-06 10:45:29 +00:00
}
2014-11-04 05:20:26 +00:00
2018-01-03 11:12:19 +00:00
# Changes ownership to current user. This facilitates a lot
2021-01-25 17:26:49 +00:00
# usability by single users. If a Tomb is opened read-only or it
# is "multiuser" and contains ACL "by convention" using UNIX
# ownership that needs to be preserved, then this behavior can be
# deactivated using -p
local dochown=true
option_value_contains -o ro && dochown=false
option_is_set -p && dochown=false
2022-02-20 20:10:47 +00:00
$dochown && _sudo chown -R ${_UID}:${_GID} "${tombmount}"
2018-01-03 11:12:19 +00:00
2018-01-03 19:27:14 +00:00
return 0
2013-05-28 09:57:58 +00:00
}
2014-10-24 01:48:05 +00:00
## HOOKS EXECUTION
#
# Execution of code inside a tomb may present a security risk, e.g.,
# if the tomb is shared or compromised, an attacker could embed
# malicious code. When in doubt, open the tomb with the -n switch in
# order to skip this feature and verify the files mount-hooks and
# bind-hooks inside the tomb yourself before letting them run.
# Mount files and directories from the tomb to the current user's HOME.
#
# Synopsis: exec_safe_bind_hooks /path/to/mounted/tomb
#
# This can be a security risk if you share tombs with untrusted people.
# In that case, use the -n switch to turn off this feature.
2013-05-28 09:57:58 +00:00
exec_safe_bind_hooks() {
2018-01-03 19:27:14 +00:00
local mnt="$1" # First argument is the mount point of the tomb
# Default mount options are overridden with the -o switch
[[ -n ${(k)OPTS[-o]} ]] && MOUNTOPTS=${OPTS[-o]}
# No HOME set? Note: this should never happen again.
[[ -z $HOME ]] && {
_warning "How pitiful! A tomb, and no HOME."
return 1 }
[[ -z $mnt || ! -d $mnt ]] && {
_warning "Cannot exec bind hooks without a mounted tomb."
return 1 }
[[ -r "$mnt/bind-hooks" ]] || {
_verbose "bind-hooks not found in ::1 mount point::" $mnt
return 0 }
typeset -Al maps # Maps of files and directories to mount
typeset -al mounted # Track already mounted files and directories
# better parsing for bind hooks checks for two separated words on
# each line, using zsh word separator array subscript
_bindhooks="${mapfile[${mnt}/bind-hooks]}"
for h in ${(f)_bindhooks}; do
2023-12-15 09:41:57 +00:00
h=${h//\\ /__ESC_SPACE__}
2018-01-03 19:27:14 +00:00
s="${h[(w)1]}"
d="${h[(w)2]}"
2023-12-15 09:41:57 +00:00
s=${s//__ESC_SPACE__/ }
d=${d//__ESC_SPACE__/ }
2020-12-15 17:22:38 +00:00
[[ -z $s ]] && { _warning "bind-hooks file is broken"; return 1 }
[[ -z $d ]] && { _warning "bind-hooks file is broken"; return 1 }
2018-01-03 19:27:14 +00:00
maps+=($s $d)
_verbose "bind-hook found: $s -> $d"
done
unset _bindhooks
for dir in ${(k)maps}; do
[[ "${dir[1]}" == "/" || "${dir[1,2]}" == ".." ]] && {
_warning "bind-hooks map format: local/to/tomb local/to/\$HOME"
continue }
[[ "${${maps[$dir]}[1]}" == "/" || "${${maps[$dir]}[1,2]}" == ".." ]] && {
_warning "bind-hooks map format: local/to/tomb local/to/\$HOME. Rolling back"
for dir in ${mounted}; do _sudo umount $dir; done
return 0 }
2024-08-31 03:38:45 +00:00
while true; do
[[ ! -r "$mnt/$dir" ]] && {
_warning "bind-hook source not found in tomb, skipping ::1 mount point::/::2 subdir::" $mnt $dir
break; }
[[ ! -r "$HOME/${maps[$dir]}" ]] && {
_warning "bind-hook target not existent, skipping ::1 home::/::2 subdir::" $HOME ${maps[$dir]}
break; }
_sudo mount -o bind,$MOUNTOPTS \
$mnt/$dir $HOME/${maps[$dir]} \
2018-01-03 19:27:14 +00:00
&& mounted+=("$HOME/${maps[$dir]}")
2024-08-31 03:38:45 +00:00
break
done
2018-01-03 19:27:14 +00:00
done
2013-05-28 09:57:58 +00:00
}
2014-10-24 01:48:05 +00:00
# Execute automated actions configured in the tomb.
#
2018-01-03 19:27:14 +00:00
# Synopsis: exec_safe_func_hooks /path/to/mounted/tomb
2014-10-24 01:48:05 +00:00
#
2017-06-06 14:30:48 +00:00
# If an executable file named 'exec-hooks' is found inside the tomb,
2018-01-03 19:27:14 +00:00
# run it as a user. This might need a dialog for security on what is
2014-10-24 01:48:05 +00:00
# being run, however we expect you know well what is inside your tomb.
# If you're mounting an untrusted tomb, be safe and use the -n switch
# to verify what it would run if you let it. This feature opens the
# possibility to make encrypted executables.
2017-06-06 10:45:29 +00:00
exec_safe_func_hooks() {
2018-01-03 13:37:15 +00:00
local mnt
mnt="$2"
2018-01-03 19:27:14 +00:00
# Only run if post-hooks has the executable bit set
[[ -x $mnt/exec-hooks ]] && {
_success "Exec hook: ::1 exec hook:: ::2 action::" \
2018-01-03 13:37:15 +00:00
"${mnt}/exec-hooks" "$1"
# here call two actions: open or close. Synopsis:
2018-01-03 19:27:14 +00:00
# $1 $2 $3 $4 $5
# open "$tombmount"
2020-11-16 22:35:03 +00:00
# close "$tombmount" "$tombname" "$tombloop" "$TOMBMAPPER"
2018-01-03 19:27:14 +00:00
$mnt/exec-hooks "$1" "$2" "$3" "$4" "$5"
2017-06-06 14:30:48 +00:00
return $?
2018-01-03 19:27:14 +00:00
}
2017-06-06 14:30:48 +00:00
return 0
2013-05-28 09:57:58 +00:00
}
# }}} - Tomb open
# {{{ List
# list all tombs mounted in a readable format
# $1 is optional, to specify a tomb
list_tombs() {
2018-01-03 19:27:14 +00:00
local tombname tombmount tombfs tombfsopts tombloop
local ts tombtot tombused tombavail tombpercent tombp tombsince
local tombtty tombhost tombuid tombuser
# list all open tombs
mounted_tombs=(`list_tomb_mounts $1`)
[[ ${#mounted_tombs} == 0 ]] && {
2024-01-26 01:25:13 +00:00
_failure "I can't see any open tomb, may they all rest in peace." }
2018-01-03 19:27:14 +00:00
for t in ${mounted_tombs}; do
mapper=`basename ${t[(ws:;:)1]}`
tombname=${t[(ws:;:)5]}
2022-02-20 20:10:47 +00:00
tombmount="${t[(ws:;:)2]}"
2018-01-03 19:27:14 +00:00
tombfs=${t[(ws:;:)3]}
tombfsopts=${t[(ws:;:)4]}
tombloop=${mapper[(ws:.:)4]}
# calculate tomb size
2020-11-25 13:47:43 +00:00
ts=`df -hP /dev/mapper/$mapper |
2014-11-04 05:20:26 +00:00
awk "/mapper/"' { print $2 ";" $3 ";" $4 ";" $5 }'`
2018-01-03 19:27:14 +00:00
tombtot=${ts[(ws:;:)1]}
tombused=${ts[(ws:;:)2]}
tombavail=${ts[(ws:;:)3]}
tombpercent=${ts[(ws:;:)4]}
tombp=${tombpercent%%%}
# obsolete way to get the last open date from /dev/mapper
# which doesn't work when tomb filename contain dots
# tombsince=`date --date=@${mapper[(ws:.:)3]} +%c`
# find out who opens it from where
2022-02-20 20:10:47 +00:00
[[ -r "${tombmount}/.tty" ]] && {
tombsince=$(cat "${tombmount}/.last")
2018-01-03 19:27:14 +00:00
tombsince=$(date --date=@$tombsince +%c)
2022-02-20 20:10:47 +00:00
tombtty=$(cat "${tombmount}/.tty")
tombhost=$(cat "${tombmount}/.host")
tombuid=$(cat "${tombmount}/.uid" | tr -d ' ')
2018-01-03 19:27:14 +00:00
2019-08-22 15:07:12 +00:00
tombuser=`_get_username $tombuid`
2018-01-03 19:27:14 +00:00
}
2022-02-20 20:10:47 +00:00
{ option_is_set --get-mountpoint } && { print "$tombmount"; continue }
2018-01-03 19:27:14 +00:00
_message "::1 tombname:: open on ::2 tombmount:: using ::3 tombfsopts::" \
2022-02-20 20:10:47 +00:00
$tombname "$tombmount" $tombfsopts
2018-01-03 19:27:14 +00:00
2024-08-05 13:26:08 +00:00
_verbose "::1 tombname:: attached to /dev/::2 tombloop:: device" $tombname $tombloop
2018-01-03 19:27:14 +00:00
_message "::1 tombname:: open since ::2 tombsince::" $tombname $tombsince
[[ -z "$tombtty" ]] || {
_message "::1 tombname:: open by ::2 tombuser:: from ::3 tombtty:: on ::4 tombhost::" \
$tombname $tombuser $tombtty $tombhost
}
_message "::1 tombname:: size ::2 tombtot:: of which ::3 tombused:: (::5 tombpercent::%) is used: ::4 tombavail:: free " \
$tombname $tombtot $tombused $tombavail $tombpercent
[[ ${tombp} -ge 90 ]] && {
_warning "::1 tombname:: warning: your tomb is almost full!" $tombname
}
# Now check hooks
2024-08-06 13:43:15 +00:00
mounted_hooks=(`list_tomb_binds "$mapper"`)
2018-01-03 19:27:14 +00:00
for h in ${mounted_hooks}; do
2020-11-25 13:47:43 +00:00
_message "::1 tombname:: hooks ::2 hookdest::" \
$tombname ${h[(ws:;:)2]}
2018-01-03 19:27:14 +00:00
done
done
2020-12-29 10:52:23 +00:00
return 0
2010-08-22 13:04:19 +00:00
}
2011-12-01 19:04:56 +00:00
2013-05-15 11:53:28 +00:00
2014-11-04 05:20:26 +00:00
# Print out an array of mounted tombs (internal use)
# Format is semi-colon separated list of attributes
2013-05-15 11:53:28 +00:00
# if 1st arg is supplied, then list only that tomb
2013-05-28 09:57:58 +00:00
#
# String positions in the semicolon separated array:
#
# 1. full mapper path
#
# 2. mountpoint
#
# 3. filesystem type
#
# 4. mount options
#
# 5. tomb name
2013-05-15 11:53:28 +00:00
list_tomb_mounts() {
2024-08-06 12:59:51 +00:00
# execute in subshell to avoid ZSH non-POSIX behaviour if globbing doesn't match something
( for dev in /dev/mapper/tomb*$1.*; do
findmnt --source ${dev} -rnvo SOURCE,TARGET,FSTYPE,OPTIONS,LABEL \
2018-01-03 19:27:14 +00:00
| awk '
2013-05-15 11:53:28 +00:00
BEGIN { main="" }
2024-08-06 12:59:51 +00:00
{
2013-05-15 11:53:28 +00:00
if(main==$1) next;
2017-08-16 20:54:08 +00:00
print $1 ";" $2 ";" $3 ";(" $4 ");[" $5 "]"
2013-05-15 11:53:28 +00:00
main=$1
}
'
2024-08-06 12:59:51 +00:00
done ) 2>/dev/null
2013-05-15 11:53:28 +00:00
}
# list_tomb_binds
# print out an array of mounted bind hooks (internal use)
# format is semi-colon separated list of attributes
2015-12-30 16:33:23 +00:00
# needs two arguments: name of tomb whose hooks belong
2018-01-03 19:27:14 +00:00
# mount tomb
2013-05-15 11:53:28 +00:00
list_tomb_binds() {
2024-08-06 13:43:15 +00:00
[[ -z "$1" ]] && {
2018-01-03 19:27:14 +00:00
_failure "Internal error: list_tomb_binds called without argument." }
2013-05-25 13:05:21 +00:00
2024-08-06 16:40:20 +00:00
# ignore the first line of the result for the respective source (mapper),
# as this will be the canonical first mount (aka main mount)
2024-08-06 13:43:15 +00:00
findmnt --source=/dev/mapper/"$1" -rno SOURCE,TARGET,FSTYPE,OPTIONS,LABEL \
| awk '
2024-08-06 16:40:20 +00:00
FNR==1 {next}
2017-08-16 20:54:08 +00:00
{
print $1 ";" $2 ";" $3 ";(" $4 ");[" $5 "]"
}
'
2013-05-15 11:53:28 +00:00
}
2013-05-28 09:57:58 +00:00
# }}} - Tomb list
2013-05-15 11:53:28 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Index and search
2010-08-22 13:04:19 +00:00
2013-05-28 09:57:58 +00:00
# index files in all tombs for search
# $1 is optional, to specify a tomb
index_tombs() {
2018-01-03 19:27:14 +00:00
mounted_tombs=(`list_tomb_mounts $1`)
[[ ${#mounted_tombs} == 0 ]] && {
# Considering one tomb
[[ -n "$1" ]] && {
_failure "There seems to be no open tomb engraved as [::1::]" $1 }
# Or more
_failure "I can't see any open tomb, may they all rest in peace." }
_success "Creating and updating search indexes."
2024-05-12 21:29:14 +00:00
# # start the LibreOffice document converter if installed
# { command -v unoconv 1>/dev/null 2>/dev/null } && {
# unoconv -l 2>/dev/null &
# _verbose "unoconv listener launched."
# sleep 1 }
2018-01-03 19:27:14 +00:00
for t in ${mounted_tombs}; do
mapper=`basename ${t[(ws:;:)1]}`
tombname=${t[(ws:;:)5]}
2022-02-20 20:10:47 +00:00
tombmount="${t[(ws:;:)2]}"
[[ -r "${tombmount}/.noindex" ]] && {
2018-01-03 19:27:14 +00:00
_message "Skipping ::1 tomb name:: (.noindex found)." $tombname
continue }
2024-05-12 21:29:14 +00:00
{ command -v updatedb 1>/dev/null 2>/dev/null } && {
updatedbver=`updatedb --version | grep '^updatedb'`
if [[ "$updatedbver" =~ "GNU findutils" ]]; then
_warning "Cannot use GNU findutils for index/search commands."
# elif [[ "$updatedbver" =~ "locate" ]]; then
# _warning "Index command needs 'mlocate/plocate' to be installed."
else
_message "Indexing ::1 tomb name:: filenames..." $tombname
_verbose "$updatedbver"
updatedb -l 0 -o "${tombmount}/.updatedb" -U "${tombmount}"
fi
}
# here we use recoll to index file contents
[[ $RECOLL == 1 ]] && {
2018-01-03 19:27:14 +00:00
_message "Indexing ::1 tomb name:: contents..." $tombname
2024-05-12 21:29:14 +00:00
rm -f "${tombmount}/recoll.conf"
_message "Generating a new search index configuration: ::1 recoll conf::" "${tombmount}/recoll.conf"
mkdir -p "${tombmount}/.recoll"
cat <<EOF > "${tombmount}/recoll.conf"
topdirs = ${tombmount}
cachedir = ${tombmount}/.recoll
2013-06-12 16:15:55 +00:00
EOF
2024-05-12 21:29:14 +00:00
recollindex -c "${tombmount}"
2018-01-03 19:27:14 +00:00
}
_message "Search index updated."
done
2020-12-29 10:52:23 +00:00
return 0
2010-08-22 13:04:19 +00:00
}
2015-07-06 11:03:32 +00:00
2013-05-28 09:57:58 +00:00
search_tombs() {
2018-01-03 19:27:14 +00:00
{ command -v locate 1>/dev/null 2>/dev/null } || {
2023-06-26 21:33:00 +00:00
_failure "Cannot index tombs on this system: updatedb (mlocate/plocate) not installed." }
2018-01-03 19:27:14 +00:00
updatedbver=`updatedb --version | grep '^updatedb'`
[[ "$updatedbver" =~ "GNU findutils" ]] && {
_warning "Cannot use GNU findutils for index/search commands." }
2023-06-26 21:33:00 +00:00
[[ "$updatedbver" =~ "locate" ]] || {
_failure "Index command needs 'mlocate/plocate' to be installed." }
2018-01-03 19:27:14 +00:00
_verbose "$updatedbver"
# list all open tombs
mounted_tombs=(`list_tomb_mounts`)
[[ ${#mounted_tombs} == 0 ]] && {
_failure "I can't see any open tomb, may they all rest in peace." }
_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]}
2022-02-20 20:10:47 +00:00
tombmount="${t[(ws:;:)2]}"
[[ -r "${tombmount}/.updatedb" ]] && {
2023-06-26 21:33:00 +00:00
# Use mlocate/plocate to search hits on filenames
2018-01-03 19:27:14 +00:00
_message "Searching filenames in tomb ::1 tomb name::" $tombname
2022-02-20 20:10:47 +00:00
locate -d "${tombmount}/.updatedb" -e -i "${(f)@}"
2018-01-03 19:27:14 +00:00
_message "Matches found: ::1 matches::" \
2022-02-20 20:10:47 +00:00
$(locate -d "${tombmount}/.updatedb" -e -i -c ${(f)@})
2018-01-03 19:27:14 +00:00
2024-05-12 21:29:14 +00:00
# Use recoll to search over contents
[[ $RECOLL == 1 && -r "$tombmount/recoll.conf" ]] && {
2018-01-03 19:27:14 +00:00
_message "Searching contents in tomb ::1 tomb name::" $tombname
2024-05-12 21:29:14 +00:00
recollq -c "${tombmount}" ${@} }
2018-01-03 19:27:14 +00:00
} || {
_warning "Skipping tomb ::1 tomb name::: not indexed." $tombname
_warning "Run 'tomb index' to create indexes." }
done
_message "Search completed."
2020-12-29 10:52:23 +00:00
return 0
2011-11-03 14:13:49 +00:00
}
2011-12-01 19:27:05 +00:00
2013-05-28 09:57:58 +00:00
# }}} - Index and search
# {{{ Resize
2012-01-07 23:23:49 +00:00
# resize tomb file size
resize_tomb() {
2018-01-03 19:27:14 +00:00
local tombpath="$1" # First argument is the path to the tomb
2014-10-23 05:10:24 +00:00
2018-01-03 19:27:14 +00:00
_message "Commanded to resize tomb ::1 tomb name:: to ::2 size:: mebibytes." $1 $OPTS[-s]
2014-10-23 05:10:24 +00:00
2020-11-16 22:35:03 +00:00
[[ -z "$1" ]] && _failure "No tomb name specified for resizing."
[[ ! -r "$1" ]] && _failure "Cannot find ::1::" $1
2012-01-07 23:23:49 +00:00
2018-01-03 19:27:14 +00:00
newtombsize="`option_value -s`"
[[ -z "$newtombsize" ]] && {
_failure "Aborting operations: new size was not specified, use -s" }
2014-01-12 23:09:37 +00:00
2018-01-03 19:27:14 +00:00
is_valid_tomb $tombpath
2012-01-07 23:23:49 +00:00
2018-01-03 19:27:14 +00:00
_load_key # Try loading new key from option -k and set TOMBKEYFILE
2012-01-07 23:23:49 +00:00
2020-11-16 12:28:37 +00:00
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
[[ $? == 0 ]] || _failure "No valid password supplied."
2018-01-03 19:27:14 +00:00
local oldtombsize=$(( `stat -c %s "$TOMBPATH" 2>/dev/null` / 1048576 ))
2012-01-07 23:23:49 +00:00
2018-01-03 19:27:14 +00:00
# New tomb size must be specified
[[ -n "$newtombsize" ]] || {
_failure "You must specify the new size of ::1 tomb name::" $TOMBNAME }
# New tomb size must be an integer
[[ $newtombsize == <-> ]] || _failure "Size is not an integer."
2013-05-25 13:05:21 +00:00
2018-01-03 19:27:14 +00:00
# Tombs can only grow in size
if [[ "$newtombsize" -gt "$oldtombsize" ]]; then
2015-11-07 13:20:43 +00:00
2018-01-03 19:27:14 +00:00
delta="$(( $newtombsize - $oldtombsize ))"
2015-11-07 13:20:43 +00:00
2018-01-03 19:27:14 +00:00
_message "Generating ::1 tomb file:: of ::2 size::MiB" $TOMBFILE $newtombsize
2015-12-30 13:35:58 +00:00
2018-01-03 19:27:14 +00:00
_verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]}
${=DD} if=/dev/urandom bs=1048576 count=${delta} >> $TOMBPATH
[[ $? == 0 ]] || {
_failure "Error creating the extra resize ::1 size::, operation aborted." \
$tmp_resize }
2015-11-07 13:20:43 +00:00
2018-01-03 19:27:14 +00:00
# If same size this allows to re-launch resize if pinentry expires
# so that it will continue resizing without appending more space.
# Resizing the partition to the file size cannot harm data anyway.
elif [[ "$newtombsize" = "$oldtombsize" ]]; then
_message "Tomb seems resized already, operating filesystem stretch"
else
_failure "The new size must be greater then old tomb size."
fi
2013-05-27 20:49:44 +00:00
2024-08-05 13:26:08 +00:00
lo_check "$TOMBPATH"
2013-05-25 13:05:21 +00:00
2018-01-03 19:27:14 +00:00
_message "opening tomb"
2024-08-05 13:26:08 +00:00
_cryptsetup luksOpen ${TOMBPATH} ${TOMBMAPPER} || {
2018-01-03 19:27:14 +00:00
_failure "Failure mounting the encrypted file." }
2012-01-07 23:23:49 +00:00
2020-11-16 22:35:03 +00:00
_sudo cryptsetup resize "${TOMBMAPPER}" || {
_failure "cryptsetup failed to resize ::1 mapper::" $TOMBMAPPER }
2012-01-07 23:23:49 +00:00
2020-12-29 12:50:04 +00:00
filesystem=`_detect_filesystem /dev/mapper/${TOMBMAPPER}`
_message "Filesystem detected: ::1 filesystem::" $filesystem
case $filesystem in
ext3|ext4)
_sudo e2fsck -p -f /dev/mapper/${TOMBMAPPER} || {
_sudo cryptsetup luksClose "${TOMBMAPPER}"
_failure "e2fsck failed to check ::1 mapper::" $TOMBMAPPER }
_sudo resize2fs /dev/mapper/${TOMBMAPPER} || {
_sudo cryptsetup luksClose "${TOMBMAPPER}"
_failure "resize2fs failed to resize ::1 mapper::" $TOMBMAPPER }
;;
btrfs)
_sudo btrfs check /dev/mapper/${TOMBMAPPER} || {
_sudo cryptsetup luksClose "${TOMBMAPPER}"
_failure "filesystem check failed on ::1 mapper::" $TOMBMAPPER }
# btrfs requires mounting before resize
local mp=${TOMBNAME}.tomb.resize
mkdir -p /tmp/${mp}
_sudo mount /dev/mapper/${TOMBMAPPER} /tmp/${mp}
_sudo btrfs filesystem resize max /tmp/${mp} || {
_sudo umount /tmp/${mp}
_sudo cryptsetup luksClose "${TOMBMAPPER}"
rmdir /tmp/${mp}
_failure "filesystem resize failed on ::1 mapper::" $TOMBMAPPER }
_sudo umount /tmp/${mp}
rmdir /tmp/${mp}
;;
# TODO: report error on unrecognized filesystem
esac
2012-01-07 23:23:49 +00:00
2018-01-03 19:27:14 +00:00
# close and free the loop device
2020-11-16 22:35:03 +00:00
_sudo cryptsetup luksClose "${TOMBMAPPER}"
2012-01-07 23:23:49 +00:00
2018-01-03 19:27:14 +00:00
return 0
2012-01-07 23:23:49 +00:00
}
2011-12-01 17:53:12 +00:00
# }}}
2013-03-30 16:29:51 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Close
2013-05-15 10:00:23 +00:00
2013-05-28 09:57:58 +00:00
umount_tomb() {
2018-01-03 19:27:14 +00:00
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
[[ ${#mounted_tombs} == 0 ]] && {
_failure "There is no open tomb to be closed." }
[[ ${#mounted_tombs} -gt 1 && -z "$1" ]] && {
_warning "Too many tombs mounted, please specify one (see tomb list)"
_warning "or issue the command 'tomb close all' to close them all."
_failure "Operation aborted." }
for t in ${mounted_tombs}; do
mapper=`basename ${t[(ws:;:)1]}`
# strip square parens from tombname
tombname=${t[(ws:;:)5]}
2022-02-20 20:10:47 +00:00
tombmount="${t[(ws:;:)2]}"
2018-01-03 19:27:14 +00:00
tombfs=${t[(ws:;:)3]}
tombfsopts=${t[(ws:;:)4]}
tombloop=${mapper[(ws:.:)4]}
_verbose "Name: ::1 tomb name::" $tombname
2022-02-20 20:10:47 +00:00
_verbose "Mount: ::1 mount point::" "$tombmount"
2017-04-16 10:00:26 +00:00
_verbose "Loop: ::1 mount loop::" $tombloop
2020-11-17 07:19:36 +00:00
_verbose "Mapper: ::1 mapper::" $mapper
2014-07-13 15:35:28 +00:00
2020-11-17 07:19:36 +00:00
[[ -e "$mapper" ]] && {
2018-01-03 19:27:14 +00:00
_warning "Tomb not found: ::1 tomb file::" $1
_warning "Please specify an existing tomb."
return 0 }
2014-07-13 15:35:28 +00:00
2017-06-06 14:30:48 +00:00
option_is_set -n || {
2017-06-06 10:45:29 +00:00
exec_safe_func_hooks \
2020-11-17 07:19:36 +00:00
close "$tombmount" "$tombname" "$tombloop" "$mapper"
2017-06-06 14:30:48 +00:00
exec_hook_res=$?
[[ $exec_hook_res = 0 ]] || {
_warning "close exec-hook returns a non-zero error code: ::1 error::" $exec_hook_res
_failure "Operation aborted"
}
}
2018-01-03 19:27:14 +00:00
_message "Closing tomb ::1 tomb name:: mounted on ::2 mount point::" \
2022-02-20 20:10:47 +00:00
$tombname "$tombmount"
2018-01-03 19:27:14 +00:00
2024-08-06 16:40:20 +00:00
# check if there are bind mounted dirs and close them first
# Can be due to bind-hooks or outside --bind mounts
2024-08-06 13:43:15 +00:00
bind_tombs=(`list_tomb_binds "$mapper"`)
2024-08-06 08:51:01 +00:00
for b in ${bind_tombs}; do
2018-01-03 19:27:14 +00:00
bind_mapper="${b[(ws:;:)1]}"
bind_mount="${b[(ws:;:)2]}"
2022-02-20 20:10:47 +00:00
_message "Closing tomb bind hook: ::1 hook::" "$bind_mount"
2023-12-16 07:56:55 +00:00
_sudo umount "$(echo "$bind_mount")" ||
2022-02-20 20:10:47 +00:00
_failure "Tomb bind hook ::1 hook:: is busy, cannot close tomb." "$bind_mount"
2018-01-03 19:27:14 +00:00
done
2024-08-06 16:40:20 +00:00
# umount the main mount
_verbose "Performing umount of ::1 mount point::" "$tombmount"
touch "${tombmount}"/.cleanexit
_sudo umount "${tombmount}"
[[ $? = 0 ]] || {
rm -f "${tombmount}"/.cleanexit
_failure "Tomb is busy, cannot umount!"
}
2018-01-03 19:27:14 +00:00
# If we used a default mountpoint and is now empty, delete it
tombname_regex=${tombname//\[/}
tombname_regex=${tombname_regex//\]/}
[[ "$tombmount" =~ "(/run)?/media(/$_USER)?/$tombname_regex" ]] && {
2022-02-20 20:10:47 +00:00
_sudo rmdir "$tombmount" }
2018-01-03 19:27:14 +00:00
2020-11-17 07:19:36 +00:00
_sudo cryptsetup luksClose $mapper ||
_failure "Error occurred in cryptsetup luksClose ::1 mapper::" $mapper
2018-01-03 19:27:14 +00:00
_success "Tomb ::1 tomb name:: closed: your bones will rest in peace." $tombname
2011-09-04 07:36:40 +00:00
2018-01-03 19:27:14 +00:00
done # loop across mounted tombs
2013-05-28 09:57:58 +00:00
2018-01-03 19:27:14 +00:00
return 0
2013-05-28 09:57:58 +00:00
}
2017-12-11 12:06:01 +00:00
list_processes() {
# $1 = (optional) name of tomb
2024-01-07 19:23:20 +00:00
# runs lsof on the mounted_tombs
2017-12-11 12:06:01 +00:00
local mounted_tombs i
mounted_tombs=(`list_tomb_mounts $1`)
if [[ "${#mounted_tombs}" -gt 0 ]]; then
2020-12-15 17:22:38 +00:00
if [[ -z $1 ]]; then
2017-12-11 12:06:01 +00:00
_success "Listing processes running inside all open tombs..."
else
_success "Listing processes running inside tomb '::1 tombname::'..." "$1"
fi
2018-01-03 19:27:14 +00:00
for i in ${mounted_tombs}; do
2017-12-11 12:06:01 +00:00
_verbose "scanning tomb: ::1 tombmount::" $i
2022-02-20 20:10:47 +00:00
tombmount="${i[(ws:;:)2]}"
2024-01-07 19:23:20 +00:00
_sudo lsof +D "${i[(ws:;:)2]}"
2017-12-11 12:06:01 +00:00
done
fi
2020-12-29 10:52:23 +00:00
return 0
2017-12-11 12:06:01 +00:00
}
2013-05-28 09:57:58 +00:00
# Kill all processes using the tomb
slam_tomb() {
2017-12-11 12:06:01 +00:00
# $1 = (optional) name of tomb to slam, or "all" if more mounted
2018-01-03 19:27:14 +00:00
if [ "$1" = "all" ]; then
mounted_tombs=(`list_tomb_mounts`)
else
mounted_tombs=(`list_tomb_mounts $1`)
fi
2017-12-11 12:06:01 +00:00
2018-01-03 19:27:14 +00:00
[[ ${#mounted_tombs} == 0 ]] && {
_failure "There is no open tomb to be closed." }
2017-12-11 12:06:01 +00:00
2018-01-03 19:27:14 +00:00
[[ ${#mounted_tombs} -gt 1 && -z "$1" ]] && {
_warning "Too many tombs mounted, please specify one (see tomb list)"
_warning "or issue the command 'tomb close all' to close them all."
_failure "Operation aborted." }
2017-12-11 12:06:01 +00:00
local pnum puid pcmd powner result
result=0
# iterate through all mounted tomb affected
2018-01-03 19:27:14 +00:00
for i in ${mounted_tombs}; do
2017-12-11 12:06:01 +00:00
tombname=${i[(ws:;:)5]}
2022-02-20 20:10:47 +00:00
tombmount="${i[(ws:;:)2]}"
2017-12-11 12:06:01 +00:00
_success "Slamming tomb ::1 tombname:: mounted on ::2 tombmount::" \
2022-02-20 20:10:47 +00:00
${tombname} "${tombmount}"
2017-12-11 12:06:01 +00:00
# iterate through all processes running in mounted tombs
2022-02-20 20:10:47 +00:00
for pnum in ${(f)"$(_sudo lsof -t +D "$tombmount")"}; do
2021-10-13 13:46:34 +00:00
puid=$(cat /proc/${pnum}/loginuid)
pcmd=$(cat /proc/${pnum}/cmdline)
2019-08-22 15:07:12 +00:00
powner=`_get_username $puid`
2017-12-11 12:29:54 +00:00
_verbose "process found: $pnum $pcmd ($powner)"
2017-12-11 12:06:01 +00:00
# iterate through 3 different signals to send, break on success
for s in TERM HUP KILL; do
_message "::1 tombname:: sending ::2 sig:: to ::3 cmd:: (::4 uid::)" \
${tombname} ${s} ${pcmd} ${powner}
2017-12-11 12:29:54 +00:00
_sudo kill -$s $pnum
# give some time to the process for a clean quit
sleep .5
2017-12-11 12:06:01 +00:00
# stop sending other signals if kill was succesfull
[[ -r /proc/$pnum ]] || break
done
# if process still running then signal failure
[[ -r /proc/$pnum ]] && {
2017-12-11 12:29:54 +00:00
_warning "Can't kill ::1 process:: ::2 pcmd:: (::3 powner::)" \
$pnum $pcmd $powner
2017-12-11 12:06:01 +00:00
result=1 }
done
2018-01-03 19:27:14 +00:00
# if it failed killing a process, report it
2024-08-06 18:42:05 +00:00
[[ $result = 0 ]] && umount_tomb "${tombname:1:-1}"
2017-12-11 12:06:01 +00:00
done
return $result
2011-09-04 07:36:40 +00:00
}
2011-01-12 16:02:19 +00:00
2013-05-28 09:57:58 +00:00
# }}} - Tomb close
# {{{ Main routine
2014-10-24 01:48:05 +00:00
[Optparsing] Support options in whatever position
However, it has a precondition that developers MUST respect:
An option CAN'T have differente meanings/behaviour in different subcommands.
For example, "-s" means "size" and accept an argument. If you are tempted to add
an option "-s" (that means, for example "silent", and doesn't accept an argument)
This, however, make sense even from an usability point of view.
Also, option with optional argument are prohibited.
The technique is a "double scan": first, we scan options passing
_every_ possible subcommand options to zparseopts.
This way, we can distinguish between option argument and parameters.
So, we recognize which is the subcommand.
Then, parse again
2011-07-24 23:00:25 +00:00
main() {
2014-08-14 07:58:15 +00:00
2018-01-03 19:27:14 +00:00
_ensure_dependencies # Check dependencies are present or bail out
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. The only exception is "-o" which means: "options
# passed to the local subcommand", and thus can bear a different
# meaning for different 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
#
2021-04-07 18:11:04 +00:00
main_opts=(q -quiet=q D -debug=D h -help=h v -version=v f -force=f -tmp: U: G: T: -no-color -unsafe g -gpgkey=g -sudo:)
2018-01-03 19:27:14 +00:00
subcommands_opts[__default]=""
# -o in open and mount is used to pass alternate mount options
2022-02-20 21:05:01 +00:00
subcommands_opts[open]="n -nohook=n k: -kdf: -kdftype: -kdfmem: o: -ignore-swap -tomb-pwd: r: R: -sphx-host: -sphx-user: p -preserve-ownership=p"
2018-01-03 19:27:14 +00:00
subcommands_opts[mount]=${subcommands_opts[open]}
subcommands_opts[create]="" # deprecated, will issue warning
# -o in forge and lock is used to pass an alternate cipher.
2022-02-20 21:05:01 +00:00
subcommands_opts[forge]="-ignore-swap k: -kdf: -kdftype: -kdfmem: o: -tomb-pwd: -use-random r: R: -sphx-host: -sphx-user: "
2018-01-03 19:27:14 +00:00
subcommands_opts[dig]="-ignore-swap s: -size=s "
2022-02-20 21:05:01 +00:00
subcommands_opts[lock]="-ignore-swap k: -kdf: -kdftype: -kdfmem: o: -tomb-pwd: r: R: -sphx-host: -sphx-user: -filesystem: "
subcommands_opts[setkey]="k: -ignore-swap -kdf: -kdftype: -kdfmem: -tomb-old-pwd: -tomb-pwd: r: R: -sphx-host: -sphx-user: "
2018-01-03 19:27:14 +00:00
subcommands_opts[engrave]="k: "
2022-02-20 21:05:01 +00:00
subcommands_opts[passwd]="k: -ignore-swap -kdf: -kdftype: -kdfmem: -tomb-old-pwd: -tomb-pwd: r: R: -sphx-host: -sphx-user: "
2018-01-03 19:27:14 +00:00
subcommands_opts[close]=""
subcommands_opts[help]=""
subcommands_opts[slam]=""
2017-12-11 12:06:01 +00:00
subcommands_opts[ps]=""
2018-01-03 19:27:14 +00:00
subcommands_opts[list]="-get-mountpoint "
subcommands_opts[index]=""
subcommands_opts[search]=""
2019-03-03 16:56:26 +00:00
subcommands_opts[bury]="k: -tomb-pwd: r: R: -sphx-host: -sphx-user: "
subcommands_opts[exhume]="k: -tomb-pwd: r: R: -sphx-host: -sphx-user: "
2019-02-21 09:28:21 +00:00
subcommands_opts[cloak]="k: "
subcommands_opts[uncloak]="k: "
2018-01-03 19:27:14 +00:00
# subcommands_opts[decompose]=""
# subcommands_opts[recompose]=""
# subcommands_opts[install]=""
subcommands_opts[askpass]=""
subcommands_opts[source]=""
2019-03-03 16:56:26 +00:00
subcommands_opts[resize]="-ignore-swap s: -size=s k: -tomb-pwd: r: R: -sphx-host: -sphx-user: "
2018-01-03 19:27:14 +00:00
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 --option-parsing
zparseopts -M -D -Adiscardme ${every_opts}
if [[ -n ${(k)discardme[--option-parsing]} ]]; then
print $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 shouldn't be appended to PARAM
2021-01-01 21:35:52 +00:00
elif [[ $arg[1] == '-' ]]; then
2018-01-03 19:27:14 +00:00
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
[[ $subcommand != '__default' ]] && { PARAM[1]=(); shift }
### End parsing command-specific options
# Use colors unless told not to
{ ! option_is_set --no-color } && { autoload -Uz colors && colors }
# Some options are only available during insecure mode
{ ! option_is_set --unsafe } && {
2019-05-22 07:55:02 +00:00
for opt in --tomb-pwd --tomb-old-pwd; do
2018-01-03 19:27:14 +00:00
{ option_is_set $opt } && {
exitv=127 _failure "You specified option ::1 option::, which is DANGEROUS and should only be used for testing\nIf you really want so, add --unsafe" $opt }
done
}
# read -t or --tmp flags to set a custom temporary directory
2021-01-01 20:58:23 +00:00
option_is_set --tmp && TMPDIR=$(option_value --tmp)
2018-01-03 19:27:14 +00:00
2021-10-20 14:27:27 +00:00
option_is_set --sudo && {
2022-02-20 20:57:05 +00:00
local _opt=`basename $(option_value --sudo)`
_message "Privilege escalation tool configured: ::1 exec::" $_opt
2021-10-20 14:27:27 +00:00
}
2018-01-03 19:27:14 +00:00
# When we run as root, we remember the original uid:gid to set
# permissions for the calling user and drop privileges
_whoami # Reset _UID, _GID, _TTY
2020-12-15 17:22:38 +00:00
[[ -z $PARAM ]] && {
2018-01-03 19:27:14 +00:00
_verbose "Tomb command: ::1 subcommand::" $subcommand
} || {
_verbose "Tomb command: ::1 subcommand:: ::2 param::" $subcommand $PARAM
}
[[ -z $_UID ]] || {
_verbose "Caller: uid[::1 uid::], gid[::2 gid::], tty[::3 tty::]." \
$_UID $_GID $_TTY
}
2021-01-01 20:58:23 +00:00
_verbose "Temporary directory: $TMPDIR"
2018-01-03 19:27:14 +00:00
# Process subcommand
case "$subcommand" in
# USAGE
help)
usage
;;
# DEPRECATION notice (leave here as 'create' is still present in old docs)
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)."
_failure "Operation aborted."
;;
# CREATE Step 1: dig -s NN file.tomb
dig)
dig_tomb $PARAM
;;
# CREATE Step 2: forge file.tomb.key
forge)
forge_key $PARAM
;;
2021-01-01 21:35:52 +00:00
# CREATE Step 3: lock -k file.tomb.key file.tomb
2018-01-03 19:27:14 +00:00
lock)
lock_tomb_with_key $PARAM
;;
# Open the tomb
mount|open)
mount_tomb $PARAM
;;
2014-11-04 05:45:10 +00:00
2017-12-11 12:06:01 +00:00
# List all processes using a tomb
ps)
list_processes $PARAM
;;
# Slam a tomb killing all processes running inside
slam)
2024-08-06 18:42:05 +00:00
slam_tomb $PARAM[1]
2017-12-11 12:06:01 +00:00
;;
2018-01-03 19:27:14 +00:00
# Close the tomb
# `slam` is used to force closing.
umount|close)
2021-01-01 21:35:52 +00:00
[[ "$subcommand" == "slam" ]] && {
2018-01-03 19:27:14 +00:00
SLAM=1
[[ $LSOF == 0 ]] && {
unset SLAM
_warning "lsof not installed: cannot slam tombs."
_warning "Trying a regular close." }}
umount_tomb $PARAM[1]
;;
# Grow tomb's size
resize)
[[ $RESIZER == 0 ]] && {
_failure "Resize2fs not installed: cannot resize tombs." }
resize_tomb $PARAM[1]
;;
## Contents manipulation
# Index tomb contents
index)
index_tombs $PARAM[1]
;;
# List tombs
list)
list_tombs $PARAM[1]
;;
# Search tomb contents
search)
search_tombs $PARAM
;;
## Locking operations
# Export key to QR Code
engrave)
[[ $QRENCODE == 0 ]] && {
_failure "QREncode not installed: cannot engrave keys on paper." }
engrave_key $PARAM
;;
# Change password on existing key
passwd)
change_passwd $PARAM[1]
;;
# Change tomb key
setkey)
change_tomb_key $PARAM
;;
# STEGANOGRAPHY: hide key inside an image
bury)
[[ $STEGHIDE == 0 ]] && {
_failure "Steghide not installed: cannot bury keys into images." }
bury_key $PARAM[1]
;;
# STEGANOGRAPHY: read key hidden in an image
exhume)
[[ $STEGHIDE == 0 ]] && {
_failure "Steghide not installed: cannot exhume keys from images." }
exhume_key $PARAM[1]
;;
2019-02-21 09:28:21 +00:00
# STEGANOGRAPHY: transform key into text using cipher
cloak)
[[ $CLOAKIFY == 0 ]] && {
_failure "Cloakify not installed: cannot cipher keys into texts" }
cloakify_key $PARAM
;;
# STEGANOGRAPHY: read key from text using cipher
uncloak)
[[ $DECLOAKIFY == 0 ]] && {
_failure "Decloakify not installed: cannot decipher keys from texts" }
decloakify_key $PARAM
;;
2018-01-03 19:27:14 +00:00
## Internal commands useful to developers
# Make tomb functions available to the calling shell or script
'source') return 0 ;;
# Ask user for a password interactively
askpass) ask_password $PARAM[1] $PARAM[2] ;;
# Default operation: presentation, or version information with -v
__default)
_print "Tomb ::1 version:: - a strong and gentle undertaker for your secrets" $VERSION
2018-11-01 01:43:49 +00:00
echo
2024-01-23 23:31:49 +00:00
_print " Copyright (C) 2007-2024 Dyne.org Foundation, License GNU GPL v3+"
2018-01-03 19:27:14 +00:00
_print " This is free software: you are free to change and redistribute it"
_print " For the latest sourcecode go to <http://dyne.org/software/tomb>"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
option_is_set -v && {
local langwas=$LANG
LANG=en
_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."
LANG=$langwas
_print " When in need please refer to <http://dyne.org/support>."
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print "System utils:"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
cat <<EOF
2020-12-29 07:58:14 +00:00
`zsh --version`
2014-11-16 10:34:35 +00:00
`sudo -V | head -n1`
`cryptsetup --version`
2018-01-07 19:03:04 +00:00
`pinentry --version | head -n1`
2018-01-02 12:27:42 +00:00
`findmnt -V`
2014-11-16 10:34:35 +00:00
`gpg --version | head -n1` - key forging algorithms (GnuPG symmetric ciphers):
`list_gnupg_ciphers`
2012-01-17 16:28:40 +00:00
EOF
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_print "Optional utils:"
2018-11-01 01:43:49 +00:00
echo
2018-01-03 19:27:14 +00:00
_list_optional_tools version
return 0
}
usage
;;
# Reject unknown command and suggest help
*)
_warning "Command \"::1 subcommand::\" not recognized." $subcommand
_message "Try -h for help."
return 1
;;
esac
return $?
2011-04-10 19:38:01 +00:00
}
2011-12-01 19:04:56 +00:00
2011-12-01 17:53:12 +00:00
# }}}
2013-03-29 11:51:43 +00:00
2013-05-28 09:57:58 +00:00
# {{{ Run
2013-03-29 11:51:43 +00:00
2015-02-20 10:40:41 +00:00
main "$@" || exit $? # Prevent `source tomb source` from exiting
2014-08-14 07:58:15 +00:00
2011-12-01 17:53:12 +00:00
# }}}