#! /bin/sh
# vim: set tabstop=4 syntax=sh :
#######################################################################################################
#                                                                                                     #
# decode a single encrypted value, which was encoded by AVM's cipher algorithm                        #
#                                                                                                     #
###################################################################################################VER#
#                                                                                                     #
# decode_secret, version 0.3, from decoder                                                            #
#                                                                                                     #
# This script is a part of the project from https://github.com/PeterPawn/decoder.                     #
#                                                                                                     #
###################################################################################################CPY#
#                                                                                                     #
# Copyright (C) 2014-2018 P.Haemmerlein (peterpawn@yourfritz.de)                                      #
#                                                                                                     #
###################################################################################################LIC#
#                                                                                                     #
# This project is free software, you can redistribute it and/or modify it under the terms of the GNU  #
# General Public License as published by the Free Software Foundation; either version 2 of the        #
# License, or (at your option) any later version.                                                     #
#                                                                                                     #
# This project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;           #
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           #
# See the GNU General Public License under http://www.gnu.org/licenses/gpl-2.0.html for more          #
# details.                                                                                            #
#                                                                                                     #
#######################################################################################################
#                                                                                                     #
# The script takes the string value (without the leading dollar signs) for an encoded secret value    #
# and the password to decode it (as a hexadecimal string) and processes the encrypted data. Because   #
# the encrypted value contains an additional (partial) hash value built from the clear-text data, the #
# decoded data may be validated.                                                                      #
# If decoding was successful, the decoded value is written to STDOUT. If it contains a C-style string #
# value (the last byte is NUL), the end-of-string character is cut off.                               #
#                                                                                                     #
#######################################################################################################
usage_text()
{
	__purpose_hdr
	__nl "This script takes a Base32 encoded value and a hexadecimal key and tries to decrypt the"
	__nl "value. If decryption was possible, the clear-text data will be written to STDOUT."
	__usage_hdr
	__usage_opt "options"; __usage_opt_end; __usage_arg "cipher-text"; __usage_arg "key"
	__usage_end
	__options_hdr
	__nl; __option_show_opt 18 "-x" "--hex-output"; __option_show_desc "output data will be encoded as hexadecimal string"
	__nl; __option_show_opt 18 "-D" "--debug-only"; __option_show_desc "no data will be written to STDOUT, only debug info to STDERR"
	__option_debug 18
	__option_help 18
	__option_version 18
	__options_end
	__nl "The "; __undl "cipher-text"; printf " parameter must be a Base32 encoded value (using AVM's 'digits', but"
	__nl "without the leading dollar-signs); its size is verified and has to be a multiple of"
	__nl "eight.\n"
	__nl "The "; __undl "key"; printf " argument is a hexadecimal string for the decryption key to use and it has to"
	__nl "contain 64 or 32 characters; values with 32 characters are padded with zeros to a 256-bit"
	__nl "key.\n"
	__nl "If the decoded data doesn't look like a C-string (that means, the last byte isn't NUL),"
	__nl "the decoded data will be output as a hexadecimal string, prefixed with '0x' to mark this"
	__nl "format. If hexadecimal output was requested with options '-x' or '--hex-output', this"
	__nl "marker is omitted. There's no way to distinguish between the forced output as hexadecimal"
	__nl "string and a value, which really starts with '0x'. If hexadecimal output is used, any NUL"
	__nl "character at the end isn't removed from the data."
}
#######################################################################################################
#                                                                                                     #
# usage and display helpers from YourFritz framework                                                  #
#                                                                                                     #
#######################################################################################################
__bold__="$(printf "\033[1m")"
__undl__="$(printf "\033[4m")"
__rset__="$(printf "\033[0m")"
__bold() { printf "$__bold__"; printf -- "$@"; printf "$__rset__"; }
__undl() { printf "$__undl__"; printf -- "$@"; printf "$__rset__"; }
__show_script_name()
{
	printf "\033[1m\033[31m${0#*/}\033[0m: "
}
__get_script_lines()
{
	sed -n -e "/^#*${1}#\$/,/^#\{20\}.*#\$/p" "$0" | \
	sed -e '1d;$d' | \
	sed -e 's|# \(.*\) *#$|\1|' | \
	sed -e 's|^#*#$|--|p' | \
	sed -e '$d'
}
__license()
{
	__get_script_lines "LIC"
}
__version()
{
	__get_script_lines "VER" | sed -e "1,2s|^\([^,]*\),\(.*\)\$|$__bold__\1$__rset__,\2|"
}
__copyright()
{
	__get_script_lines "CPY"
}
__emsg()
{
	__show_script_name 1>&2
	mask="$1"
	shift
	printf "${__bold__}${mask}${__rset__}\a\n" "$@" 1>&2
}
__check_option()
{
	o="$1"
	shift
	for v in $*; do
		[ "$o" = "$v" ] && printf 1 && return 0
	done
	printf 0
	return 1
}
__is_option()
{
	[ "$(expr -- "$1" : "\(.\).*")" = "-" ] && return 0 || return 1
}
__is_last_option()
{
	[ "$1" = "--" ] && return 0 || return 1
}
__options_end__="eval while __is_option \"\$1\"; do __is_last_option \"\$1\" && shift && break;\
	__emsg \"Unknown option '%s'.\" \"\$1\"; exit 1; done;"
__version_option()
{
	if __check_option "$1" "-V" "--version" >/dev/null; then
		__version
		__copyright
		__license
		printf "\n"
		exit 1
	fi
	return 1
}
__version_option__="eval __version_option \$@ && exit 0"
__help_option()
{
	if __check_option "$1" "-h" "--help" >/dev/null; then
		__usage
		exit 1
	fi
}
__help_option__="eval __help_option \$@"
__debug_option()
{
	__check_option "$1" "-d" "--debug" && return 0
	return 1
}
__debug_option__="eval __debug_set__=\$(__debug_option \$1) && __debug_text__=\"\$1\" && shift"
__debug_on__="eval __debug_set__=1; __debug_text__=\"-d\";"
__is_debug() { [ $__debug_set__ -eq 1 ] && return 0 || return 1; }
__debug()
{
	[ $__debug_set__ -eq 1 ] || return;
	mask="$1"
	shift
	printf "$mask" "$@" 1>&2
}
__usage()
(
	indent=0
	__indent_on() { indent=$(( indent + 4 )); }
	__indent_off() { indent=$(( indent - 4 )); }
	__indent() { [ $indent -gt 0 ] && printf "%0${indent}s" " "; };
	__nl() { printf "\n%s" "$(__indent)"; printf -- "$1"; }
	__purpose_hdr() { __nl; __bold "Purpose:"; printf "\n"; }
	__usage_name() { __bold "${0#*/}"; }
	__usage_hdr() { printf "\n"; __nl; __bold "Usage:\n"; __indent_on; __nl "$(__usage_name)"; }
	__usage_end() { __indent_off; printf "\n"; }
	__usage_opt_int() { v="$1"; shift; [ $# ] && m="$@"; printf -- "[ %s%s ]" "$(__undl "$v")" "$m"; unset m v; };
	__usage_opt_end() { printf -- " [ -- ]"; }
	__usage_opt() { printf -- " %s" "$(__usage_opt_int "$@")"; }
	__usage_arg() { printf -- " %s" "$(__undl "$1")"; }
	__options_hdr() { __nl "Supported "; __undl "options"; printf " are:\n"; }
	__options_end() { printf "\n"; }
	__option_show_opt() {
		printf -- "%s, %s" "$2" "$3"
		__l4__=${#4}
		[ $__l4__ -gt 0 ] && printf " %s%s%s" "$__undl__" "$4" "$__rset__" && __l4__=$(( __l4__ + 1 ))
		printf "%0$(( $1 - ${#2} - ${#3} - __l4__ - 3 ))s" " "
		unset __l4__
	}
	__option_show_desc() { printf -- "- %s" "$@"; }
	__option_debug() { __nl; __option_show_opt ${1:-15} "-d" "--debug"; __option_show_desc "display debug info on STDERR; must prefix all other options, if used"; }
	__option_help()	{ __nl; __option_show_opt ${1:-15} "-h" "--help"; __option_show_desc "show this information (must be the first option)"; }
	__option_version()	{ __nl; __option_show_opt ${1:-15} "-V" "--version"; __option_show_desc "show version and exit (must be the first option)"; }
	__end() { printf "\n%s\n" "$__rset__"; }

	__version
	__copyright
	__license
	usage_text
	__end
)
__set_base_dir__="eval [ \"\$(expr \"\$0\" : \".*\(/\).*\")\" = \"/\" ] && __base_dir__=\"\${0%/*}\" || __base_dir__=\".\""
__set_base_dir() { __set_base_dir__="$1"; }
__check_required_scripts()
{
	d="$1"
	shift
	for n in $@; do
		eval $n="$d/$n"
		eval f="\$$n"
		if ! [ -x "$f" ]; then
			__emsg "Missing another needed executable: %s." "$n"
			return 1
		fi
		printf "$n=%s\n" $f
	done
	return 0
}
__check_required_scripts__="eval __scripts__=\"\$(__check_required_scripts \"\$__base_dir__\" \"\$__required_scripts\")\" && \
	eval \$__scripts__ || exit 1"
__check_required_commands()
{
	for n in $@; do
		command -v $n 2>/dev/null 1>&2 && continue
		__emsg "Missing a required command: %s." "$n"
		return 1
	done
	return 0
}
__check_required_commands__="eval __check_required_commands \"\$__required_commands\" || exit 1"
__check_terminal()
{
	[ -t $1 ] || return 1
	if [ $1 -eq 0 ]; then
		fd="STDIN"
	elif [ $1 -eq 1 ]; then
		fd="STDOUT"
	else
		fd="FILE ($1)"
	fi
	shift
	__emsg "%s is a terminal device. %s" "$fd" "$@"
}

__required_scripts="crypto"
#######################################################################################################
#                                                                                                     #
# check parameters                                                                                    #
#                                                                                                     #
#######################################################################################################
$__help_option__
$__version_option__
$__debug_option__
nooutput=$(__check_option "$1" "-D" "--debug-only") && shift
[ $nooutput -eq 1 ] && $__debug_on__
o="$1"
hexoutput=$(__check_option "$1" "-x" "--hex-output") && shift
if [ $hexoutput -eq 1 ] && [ $nooutput -eq 1 ]; then
	__emsg "Option '%s' is useless here, output was suppressed by another option." "$o"
	exit 1
fi
$__options_end__
if [ $# -lt 2 ]; then
	__emsg "Missing at least one argument, we need the cipher text (Base32) and a key."
	exit 1
fi
base32="$1"
if [ $(( ${#base32} % 8 )) -ne 0 ]; then
	__emsg "The specified encoded value has a wrong length."
	exit 1
fi
key="$2"
if [ ${#key} -ne 32 ] && [ ${#key} -ne 64 ]; then
	__emsg "The specified key '%s' looks bad. It should contain exactly 32 or 64 hexadecimal digits and will be padded with zeros to 32 bytes." "$key"
	exit 1
fi
if [ ${#3} -gt 0 ]; then
	__emsg "Too much parameters specified (%s)." "$3"
	exit 1
fi
#######################################################################################################
#                                                                                                     #
# check environment                                                                                   #
#                                                                                                     #
#######################################################################################################
$__set_base_dir__
$__check_required_scripts__
#######################################################################################################
#                                                                                                     #
# try to decrypt the value                                                                            #
#                                                                                                     #
#######################################################################################################
__debug "key\t: (%03u) 0x%s\n" $(( ${#key} / 2 )) "$key"
__debug "base32\t: (%03u) %s\n" ${#base32} "$base32"
encoded="$(printf "%s\n" "$base32" | "$crypto" b32dec)"
__debug "input\t: (%03u) 0x%s\n" $(( ${#encoded} / 2 )) "$encoded"
iv="$(expr "$encoded" : "\(.\{32\}\).*")"
encoded="$(expr "$encoded" : ".\{32\}\(.*\)")"
__debug "iv\t: (%03u) 0x%s\n" $(( ${#iv} / 2 )) "$iv"
__debug "enc'd\t: (%03u) 0x%s\n" $(( ${#encoded} / 2 )) "$encoded"
encoded="${encoded}00"
decoded="$(printf "%s" "$encoded" | "$crypto" aes_decrypt "$key" "$iv")"
__debug "dec'd\t: (%03u) 0x%s\n" $(( ${#decoded} / 2 )) "$decoded"
hash="$(expr "$decoded" : "\(.\{8\}\).*")"
# __debug "hash\t: (%03u) 0x%s\n" ${#hash} "$hash"
hexsize="$(expr "$decoded" : ".\{8\}\(.\{8\}\).*")"
value="$(expr "$decoded" : ".\{16\}\(.*\)")"
size=$(printf "%s\n" "$hexsize" | "$crypto" hex2dec)
__debug "size\t: %u\n" $size
if [ $size -le $(( ${#value} / 2 )) ]; then
	vhash="$(printf "%s%s\n" "$hexsize" "$value" | "$crypto" digest -x)"
	verify="$(expr "$vhash" : "\(.\{8\}\).*")"
	if [ "$hash" = "$verify" ]; then
		hexforced=$hexoutput
		if [ $hexoutput -eq 0 ]; then
			if [ "$(expr "$value" : ".\{$(( ( size - 1 ) * 2 ))\}\(..\).*")" = "00" ]; then
				size=$(( size - 1 ))
				__debug "string\t: yes\n"
			else
				hexforced=1
			fi
		fi
		value="$(expr "$value" : "\(.\{$(( size * 2 ))\}\).*")"
		[ $hexforced -eq 0 ] && value="$(printf "%s\n" "$value" | "$crypto" hexdec)"
		[ $hexforced -eq 1 ] && __debug "string\t: no\n"
		__debug "value\t: (%03u) " $size
		[ $hexforced -eq 1 ] && __debug "0x"
		__debug "%s\n" $value
		if [ $nooutput -ne 1 ]; then
			[ $hexforced -eq 1 ] && [ $hexoutput -eq 0 ] && printf "0x"
			printf "%s\n" "$value"
		fi
		exit 0
	else
		__debug "to hash\t: (%03u) 0x%s %s\n" $(( ( ${#hexsize} + ${#value} ) / 2 )) "$hexsize" "$value"
		__debug "hash\t: (%03u) 0x%s\n" $(( ${#vhash} / 2 )) "$vhash"
	fi
fi
__emsg "Error decoding value with the specified key."
exit 1
#######################################################################################################
#                                                                                                     #
# end of script                                                                                       #
#                                                                                                     #
#######################################################################################################
