#! /bin/sh
# vim: set tabstop=4 syntax=sh :
#######################################################################################################
#                                                                                                     #
# decode the encrypted binary data from STDIN                                                         #
#                                                                                                     #
###################################################################################################VER#
#                                                                                                     #
# decode_cryptedbinfile, 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 hexadecimal content of an encrypted binary file from an settings export file   #
# and tries to decrypt it with the specified key.                                                     #
#                                                                                                     #
#######################################################################################################
usage_text()
{
	__purpose_hdr
	__nl "This script expects the hexadecimal encoded content of a CRYPTEDBINFILE entry from an export"
	__nl "file and tries to decrypt it. If decryption was possible, the clear-text data will be written"
	__nl "to STDOUT."
	__usage_hdr
	__usage_opt "options"; __usage_opt_end; __usage_opt "password" "$( printf " | "; __undl "serial"; printf " "; \
		__undl "maca")"
	__usage_end
	__options_hdr
	__nl; __option_show_opt 24 "-a" "--alt-env" "filename"; __option_show_desc "use an alternative source for the 'urlader environment'"
	__option_debug 24
	__option_help 24
	__option_version 24
	__options_end
	__nl "The input data has to be extracted from the body of a CRYPTEDBINFILE entry - that means, the lines"
	__nl "(starting with asterisks) around the hexadecimal lines have to be removed.\n"
	__nl "If the export file was created with a password, this password must be specified as the only"
	__nl "parameter. If no password was used to export the settings, there are two alternatives to specify"
	__nl "the two needed properties of the source device. You can use the second form of parameters with"
	__nl; __undl "serial"; printf " and "; __undl "maca"; printf " set to the correct values or you can use an alternative file for the 'urlader"
	__nl "environment' (using the '-a' option from above) and the script will extract the values there.\n"
	__nl "If the content can not be decrypted (decrypted raw data contain 16 bytes at the end, where we"
	__nl "can check a successful decryption), nothing is written to STDOUT."
}
#######################################################################################################
#                                                                                                     #
# 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_commands="sed dd"
__required_scripts="crypto user_password device_password password_from_device"
#######################################################################################################
#                                                                                                     #
# check parameters                                                                                    #
#                                                                                                     #
#######################################################################################################
$__help_option__
$__version_option__
$__debug_option__
while [ $# -gt 0 ]; do
	__is_option "$1" || break
	if __check_option "$1" "-a" "--alt-env" >/dev/null; then
		if [ ${#2} -eq 0 ] || __is_option "$2"; then
			__emsg "Missing file name after option '%s'." "$1"
			exit 1
		else
			altenv="$2"
			shift 2
			continue
		fi
	fi
	__is_last_option "$1" && shift && break
	__emsg "Unknown option '%s'." "$1" && exit 1
done
#######################################################################################################
#                                                                                                     #
# check environment                                                                                   #
#                                                                                                     #
#######################################################################################################
$__set_base_dir__
$__check_required_commands__
$__check_required_scripts__
#######################################################################################################
#                                                                                                     #
# create temporary directory                                                                          #
#                                                                                                     #
#######################################################################################################
td="$("$crypto" mktemp -d)"
if [ ${#td} -eq 0 ]; then
	__emsg "Error creating a temporary directory."
	exit 1
fi
trap "exit 1" INT HUP
trap "rm -r $td 2>/dev/null" EXIT
#######################################################################################################
#                                                                                                     #
# check parameters                                                                                    #
#                                                                                                     #
#######################################################################################################
[ $# -eq 0 ] && device=1 || device=0
[ $# -eq 1 ] && password=1 || password=0
[ $# -eq 2 ] && mimicry=1 || mimicry=0
if [ $# -gt 2 ]; then
	__emsg "Unexpected number of parameters."
	exit 1
fi
#######################################################################################################
#                                                                                                     #
# check input file                                                                                    #
#                                                                                                     #
#######################################################################################################
__check_terminal 0 "You should provide the content of a CRYPTEDBINFILE entry there." && exit 1
#######################################################################################################
#                                                                                                     #
# get the password to decipher the random key entry                                                   #
#                                                                                                     #
#######################################################################################################
if [ $device -eq 1 ]; then
	key="$("$password_from_device" --export ${altenv:+-a "$altenv"} 2>/dev/null)"
	if [ ${#key} -eq 0 ]; then
		__emsg "Error reading device variables, are we really on a FRITZ!Box device?"
		exit 1
	fi
elif [ $password -eq 1 ]; then
	key="$($user_password "$1")"
	if [ ${#key} -eq 0 ]; then
		__emsg "Error creating password hash as decipher key."
		exit 1
	fi
else
	key="$($device_password "$1" "$2")"
	if [ ${#key} -eq 0 ]; then
		__emsg "Error creating the device value based password hash as decipher key."
		exit 1
	fi
fi
__debug "computed/specified key value is '%s'\n" "$key"
#######################################################################################################
#                                                                                                     #
# try to decrypt the file                                                                             #
#                                                                                                     #
#######################################################################################################
while read line; do
	printf "%s\n" "$line" | "$crypto" hexdec >>"$td/encryptedbinfile"
done
"$crypto" aes_decrypt -x "$key" 00000000000000000000000000000000 -aes-256-ecb >"$td/decryptedbinfile" <"$td/encryptedbinfile"
#######################################################################################################
#                                                                                                     #
# check size                                                                                          #
#                                                                                                     #
#######################################################################################################
fileSize=$(stat -c %s "$td/decryptedbinfile")
__debug "size of decrypted raw file: %u\n" $fileSize
[ $fileSize -eq 0 ] && exit 1
#######################################################################################################
#                                                                                                     #
# check 32 bytes at the end                                                                           #
#                                                                                                     #
#######################################################################################################
data="$(dd if="$td/decryptedbinfile" bs=16 skip=$(( ( fileSize / 16 ) - 1)) 2>/dev/null | "$crypto" hexenc)"
hdr="$(expr "$data" : "\(.\{24\}\).*")"
size="$(expr "$data" : ".\{24\}\(.\{8\}\).*")"
if ! [ "$hdr" = "41564d000000000000000000" ]; then
	__debug "decrypted data at end of file: %s\n" "$data"
	__emsg "Error decrpyting file, please check the password."
	exit 1
fi
dataSize="$(printf "%s\n" "$size" | "$crypto" hex2dec)"
dd if="$td/decryptedbinfile" bs=1 skip=4 count=$dataSize 2>/dev/null
#######################################################################################################
#                                                                                                     #
# no housekeeping needed, temporary data will be cleaned up by our trap command above                 #
#                                                                                                     #
#######################################################################################################
exit $?
#######################################################################################################
#                                                                                                     #
# end of script                                                                                       #
#                                                                                                     #
#######################################################################################################
