#! /bin/sh
# vim: set tabstop=4 syntax=sh :
#######################################################################################################
#                                                                                                     #
# decode every occurence of an encoded secret value from an export file                               #
#                                                                                                     #
###################################################################################################VER#
#                                                                                                     #
# decode_export, 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 input file from STDIN, extracts the random cipher key from the 'Password'      #
# entry in its header and calls the 'decode_secrets' script with this random key.                     #
#                                                                                                     #
#######################################################################################################
usage_text()
{
	__purpose_hdr
	__nl "This script decrypts all occurrences of encrypted data on STDIN (if decryption is possible) and"
	__nl "writes the data to STDOUT, while replacing cipher-text with the corresponding clear-text values."
	__usage_hdr
	__usage_opt "options"; __usage_opt_end; __usage_opt "password" "$( printf " | "; __undl "serial"; printf " "; \
		__undl "maca")"; printf " < "; __undl "input-file"
	__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 "; __undl "input-file"; printf " has to be a saved-settings file, which was exported from FRITZ!OS.\n"
	__nl "These files use a two-stage encryption, where a random value will be chosen and encrypted with a"
	__nl "key for the first stage. Then it will be stored in an entry with the name 'Password' in the file"
	__nl "header. All further data inside the file will be encrypted with this random key. The first key's"
	__nl "value is derived from device properties (see "; __bold "password_from_device"; printf " for details), if an export file"
	__nl "is created without an user-specified "; __undl "password"; printf ". Otherwise this "; __undl "password"; \
		printf " will be used to compute"
	__nl "the first key and you must specify the same "; __undl "password"; printf " to decrypt the file.\n"
	__nl "If a file was created without a "; __undl "password"; printf ", there are two alternatives to specify the two needed"
	__nl "properties of the source device. You can use the second form of parameters with "; __undl "serial"; printf " and "; \
		__undl "maca"
	__nl "set to the correct values or you can use an alternative file for the 'urlader environment'"
	__nl "(using the '-a' option from above) and the script will extract the values there.\n"
	__nl "If the key value for the second stage can not be decrypted, further processing will be aborted.\n"
	__nl "The encrypted value of the '$password_entry' field in the header will remain unchanged. Its value isn't"
	__nl "usable for other cases and as long as it's kept intact, the file may be later imported again by"
	__nl "a FRITZ!OS device (with the right properties or with a password) even if all encrypted values are"
	__nl "replaced by their corresponding cleartext. Only the CRC32 checksum at the end of the file has to"
	__nl "be re-computed."
}
#######################################################################################################
#                                                                                                     #
# 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="password_from_device device_password user_password decode_secret decode_secrets crypto"
__required_commands="sed"
#######################################################################################################
#                                                                                                     #
# constants                                                                                           #
#                                                                                                     #
#######################################################################################################
password_entry="Password"
#######################################################################################################
#                                                                                                     #
# check environment                                                                                   #
#                                                                                                     #
#######################################################################################################
$__set_base_dir__
$__check_required_commands__
$__check_required_scripts__
#######################################################################################################
#                                                                                                     #
# 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 an export file there." && exit 1
cat - >"$td/input"
if ! [ -s "$td/input" ]; then
	__debug "Input file is empty.\n"
	exit 0
fi
#######################################################################################################
#                                                                                                     #
# get the password to decipher the random key entry                                                   #
#                                                                                                     #
#######################################################################################################
if [ $device -eq 1 ]; then
	export_key="$("$password_from_device" --export ${altenv:+-a "$altenv"} 2>/dev/null)"
	if [ ${#export_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
	export_key="$($user_password "$1")"
	if [ ${#export_key} -eq 0 ]; then
		__emsg "Error creating password hash as decipher key."
		exit 1
	fi
else
	export_key="$($device_password "$1" "$2")"
	if [ ${#export_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" "$export_key"
#######################################################################################################
#                                                                                                     #
# extract the 'Password' value from the header of our file and try to decode it                       #
#                                                                                                     #
#######################################################################################################
rnd_pw="$(sed -n -e "s|^[ \t]*$password_entry=\$\$\$\$\([A-Z1-6]*\).*|\1|p" <"$td/input" 2>/dev/null)"
if [ ${#rnd_pw} -eq 0 ]; then
	__emsg "Unable to locate the '%s' entry in the file header, is this really an export file from a FRITZ!Box device?" "$password_entry"
	exit 1
fi
__debug "random key Base32 value is '%s'\n" "$rnd_pw"
export_rnd="$("$decode_secret" $__debug_text__ -x "$rnd_pw" "$export_key" 2>/dev/null)"
if [ ${#export_rnd} -eq 0 ]; then
	__emsg "Unable to decrypt the random cipher key with the specified export key or device data."
	exit 1
fi
random_key="$(expr "$export_rnd" : "\(.\{$(( ${#export_rnd} / 2 ))\}\).*")"
__debug "random key value is '%s'\n" "$random_key"
#######################################################################################################
#                                                                                                     #
# write the header and the decoded data to STDOUT                                                     #
#                                                                                                     #
#######################################################################################################
sed -n -e "1,/^[ \t]*$password_entry=\$\$\$\$[A-Z1-6]*\$/p" "$td/input"
sed -e "1,/^[ \t]*$password_entry=\$\$\$\$[A-Z1-6]*\$/d" "$td/input" | "$decode_secrets" $__debug_text__ "$random_key"
#######################################################################################################
#                                                                                                     #
# no housekeeping needed, temporary data will be cleaned up by our trap command above                 #
#                                                                                                     #
#######################################################################################################
exit 0
#######################################################################################################
#                                                                                                     #
# end of script                                                                                       #
#                                                                                                     #
#######################################################################################################
