#!/usr/bin/python

import sys
import cgi
import time

from config import *
from libutils import *
from libmalware import (analyzeMalware, getStrings, getHeaders, analyzeCalls, showMemoryDumps,
						showVMDetectionTricks, showDebuggingTricks)

form = cgi.FieldStorage()
if not form:
    dieError("location: /index.html")
    print """
<form action="/cgi-bin/upload.py" method="POST" 
enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit">
</form>
  """
else:

	printHeader()

	if not form.has_key("filename"):
		dieError("Bad arguments")

	item = form["filename"]

	if not item.file or item.filename == "" or not item.filename:
		dieError("Empty file given")

	if not form.has_key("timeout"):
		timeout = DEFAULT_TIMEOUT
		showWarning("No timeout specified, using default %d" % timeout)
	else:
		try:
			timeout = int(form.getvalue("timeout"))
		except:
			dieError("Invalid timeout: %s" % str(sys.exc_info()[1]))
			sys.exit(0)

	if timeout > MAX_TIMEOUT:
		timeout = MAX_TIMEOUT # Do not allow too big timeouts

	if not form.has_key("memory"):
		memory = False
	else:
		memory = True

	printBodyHeader()

	print
	print "<h1>Malware analysis</h1>" 
	print "Analyzing file: <b>%s</b>. " % cgi.escape(item.filename)
	print "<br/>"

	msg, strMd5, filename = analyzeMalware(item, timeout, memory)
	idx = -1
	for line in msg:
		idx += 1
		if line.find("Starting process") > -1 and line.find(strMd5) > -1:
			lines = msg[idx:]
			break

	print "<br/>"
	print "<div align='center'>"
	print "General information:<br/><br/><table border='0'><tr><td align='center'>"
	print """<a href="javascript:toggleShowReport()"><img src="/img/report.png" height="16" width="16"> Report</a>"""
	print "</td>"

	print "<td align='center'>"
	print """<a href="javascript:toggleShowStrings()"><img src="/img/strings.png" height="16" width="16"> Strings</a>"""
	print "</td>"

	print "<td align='center'>"
	print """<a href="javascript:toggleShowHeaders()"><img src="/img/headers.png" height="16" width="16"> File headers</a>"""
	print "</td>"

	print "<td align='center'>"
	print """<a href="javascript:toggleShowSignature()"><img src="/img/signature.png" height="16" width="16"> Signature</a>"""
	print "</td></tr><tr><td colspan='4' align='center'><br/>"

	#print "<img src='/img/analyzing.jpg'/>"
	print "</td></tr>"
	print "<tr><td colspan='4'>"

	# Report
	print """<div id='divData' style="visibility:hidden;display:none;float: center; width: 50%;">"""
	print "<textarea cols='100' rows='30'>"
	print cgi.escape("".join(msg[idx:]))
	print "</textarea><br/>"
	print "</div>"

	# Strings
	print """<div id='divStrings' style="visibility:hidden;display:none;float: center; width: 50%;">"""
	print """<textarea cols='100' rows='30'>"""
	print cgi.escape("".join(getStrings(filename)))
	print "</textarea>"
	print "</div>"

	# Headers
	print """<div id='divHeaders' style="visibility:hidden;display:none;float: center; width: 50%;">"""
	print """<textarea cols='100' rows='30'>"""
	print cgi.escape(getHeaders(filename))
	print "</textarea>"
	print "</div>"
	
	# Signatures
	print """<div id='divSignatures' style="visibility:hidden;display:none;float: center; width: 50%;">"""
	print """<textarea cols='100' rows='30'>"""
	analyzeCalls(msg[idx:])
	print "</textarea>"
	print "</div>"
	
	print "</td></tr>"

	# Memory dumps
	print """<tr><td colspan='4' align='left'>"""
	print """<div align='left'><br/>Memory dumps:<br/><br/></div>"""
	print """</td></tr>"""
	print """<tr><td colspan='4'>"""
	showMemoryDumps(filename, strMd5)
	print "</td></tr>"

	# Debugger detection tricks
	print """<tr><td colspan='4' align='left'>"""
	print """<div align='left'><br/>Debugger detection tricks:<br/><br/></div>"""
	print """</td></tr>"""
	print """<tr><td colspan='4'>"""
	showDebuggingTricks(filename, strMd5, msg)
	print """</td></tr>"""

	# Virtual Machine detection tricks	
	print """<tr><td colspan='4' align='left'>"""
	print """<div align='left'><br/>Virtual Machine detection tricks:<br/><br/></div>"""
	print """</td></tr>"""
	print """<tr><td colspan='4'>"""
	
	showVMDetectionTricks(filename, strMd5)
	
	print """</td></tr></table>"""
	print """</div>"""
	
	print "<br/>"
	print "<br/><div align='center'>Analysis finished at %s</div>" % time.ctime()
	
	printBodyFooter()
	
