#!/usr/bin/env bash

# This script takes a payload and disguises it as an image.

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
CURRENT=$(pwd)

PAYLOAD="$1"
IMAGETYPE="${2:-jpg}"
# Make sure the image type is lower case
IMAGETYPE=$(echo "$IMAGETYPE" | tr '[:lower:]' '[:upper:]')

# Hex encoded versions of the magic bytes of images
MAGIC_GIF='47494638396140004000e7ff0002050101070a0d'
MAGIC_JPG='ffd8ffe000104a46494600010101012c012c0000'
MAGIC_PNG='89504e470d0a1a0a0000000d49484452000000400a'
# This function prints the usage
function printUsage(){
	echo "Usage: $(basename "$0") PAYLOAD TYPE"
	echo ""
	echo "Disguises a payload as an image"
	echo ""
	echo -e "PAYLOAD\t\tThe payload to use, currently only supports a file in CWD (Required)"
	echo -e "TYPE\t\tThe type of image (jpg, png, gif) (default: jpg)"
}

function getPayload(){
	local payload="$CURRENT/$PAYLOAD"
	echo "$payload"
	if [ -f "$payload" ]; then
		exit 0
	else
		# Add stuff here if we want to look in another folder for payloads at some point
		exit 1
	fi
}

function getDestination(){
	local ext=$(echo "$IMAGETYPE" | tr '[:upper:]' '[:lower:]')
	echo "$CURRENT/$PAYLOAD.$ext"
	exit 0
}

eval template="\$MAGIC_$IMAGETYPE"

if [ -n "$template" ]; then
	if payload=$(getPayload); then
		# Do copy stuff
		destination=$(getDestination)
		echo "$template" | xxd -r -p > "$destination"
		cat "$payload" >> $destination
	else
		"No such payload $payload"
		echo ""
		printUsage
	fi
else
	echo "No such template $template"
	echo ""
	printUsage
	exit 1
fi
