#!/bin/sh

if [ $# -lt 1 ]; then
        echo "Usage $0 malware.exe timeout"
        exit 1
fi

echo "Cleaning previous tests ... "
rm -fr ~/.wine/*
cd $HOME/.wine
tar -xvzf $HOME/backup/backup.tar.gz

echo "Launching wine $1 > $2"

export DUMP_PATH=$3
export WINEDEBUG=+relay,+dll,+loaddll,+file,+network,+wininet,+winsock,+ole,+msgbox,+ntdll

if [ $# -gt 1 ]; then
        timeout=$2
else
        timeout=5
fi

echo "Timeout set to $timeout"
wine $1 2>&1 | egrep -v 'CriticalSec|SysLevel|Tls.etVal|window proc|CallWindowProc|ntdll.Rtl|Heap|user32.IsDialogMessage|KERNEL32.CreateEvent|KERNEL32.ResetEvent|KERNEL32.DisableThreadLibraryCalls|user32.GetMessage|user32.SendMessage|Ret  dialog proc|Call dialog proc|gdi32.SetBkMode|user32.DispatchMessage|user32.DefWindowProc|user32.BeginPaint|user32.EndPaint|gdi32.Delete|gdi32.Create|user32.CharNext|KERNEL32.lstrcpy|gdi32|KERNEL32.lstr|KERNEL32.Local|KERNEL32.Multibyte|user32.GetWindowLong|:Ret  |WindowLongA\(|KERNEL32.Global|KERNEL32.TlsAlloc|KERNEL32.CloseHandle|KERNEL32.WaitForMultipleObjects|user32.GetSysColor|user32.LoadCursor|user32.Register|user32.Char|KERNEL32.GetTickCount|KERNEL32.WriteFile\(00|KERNEL32.ReadFile\(00|Call KERNEL32.GetProcAddress\(|user32.InvalidateRect|rpcrt4.RpcString|KERNEL32.MultiByte|KERNEL32.WideChar|ole32.CoTaskMem|user32.GetDlgItem\(00|user32.RedrawWindow|user32.UpdateWindow|user32.PeekMessage|imm32.ImmProcessKey|user32.GetKeyboard|user32.PostMessage|Call KERNEL32.__wine|Call user32.LoadString|KERNEL32.SetLastError|KERNEL32.GetLastError|KERNEL32.FlsGetValue|Call KERNEL32._lread\(00|Call KERNEL32._llseek\(00|KERNEL32.SetFilePointer|rpcrt4.Ndr|rpcrt4.I_RpcGet|rpcrt4.NDR|rpcrt4.Ndr|ntdll.mem|msvcrt.malloc|ntdll.atoi|msvcrt.calloc|ntdll.str|ntdll._str|msvcrtl.realloc|msvcrt.free|winealsa.drv|msacm32.drv|Call KERNEL32.WaitFor|Call KERNEL32.ReleaseMutex|Call KERNEL32._lwrite\(00|^warn:' &

sleep $timeout
ps -edf | grep .exe
if [ "$4" == "1" ]; then
	echo "Dumping the process memory for child processes..."
	ps -edf
	for proc in `ps -edf | grep ".exe" | grep -v grep | grep -v "C:\\\\\\\\windows\\\\\\\\system32\\\\\\\\explorer.exe" | grep -v "C:\\\\\\\\windows\\\\\\\\system32\\\\\\\\services.exe" | awk '{ print $2 }'`;
	do
		echo Dumping proc $proc
		dump_process.py $proc $3-$proc
	done

	if [ `ps -edf | grep malware.exe | grep -v sh | grep -v grep | wc -l` -gt 0 ]; then
		proc=`ps -edf | grep malware.exe | grep -v sh | grep -v grep | awk '{ print $2 }'`
		dump_process.py $proc $3-malware.exe-$proc
	fi
fi

ps -edf | grep ^$USER | grep exe | grep -v grep | awk '{ print $2 }' | xargs kill -9 && echo "Killed, timeout"




