Windows registry forensics

While forensic investigations, windows registry values are treasures. Although registry values can be accessed both through “regedit” UI and through “reg query” command, the power of a script to query and perform Windows registry forensic in code is much more. Python provides access to Windows registry through _winreg library. In this article I am going to review code snippets from “Violent Python: a Cookbook for Hackers” book to read registry values by a python script.

Data about previously connected wireless networks are stored in "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged" key. You can access windows registry either through registry editor (Run -> regedit) or by typing “reg query [key]” in command prompt.

The script for querying the mentioned key and printing name and Mac Address of the connected wireless networks is as follows:

#Windows registry forensic

from winreg import *

def val2addr(val): #Convert the binary value to Mac-Address format

                addr = ''

                for ch in val:

                                addr += '%02x '% ch

                                addr = addr.strip(' ').replace(' ', ':')[0:17]

                return addr

def printNets():

                net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"+\


                key = OpenKey(HKEY_LOCAL_MACHINE, net)

                print('\n[*] Networks You have Joined.')

                for i in range(100): #printing up to 100 networks


                                                guid = EnumKey(key, i)

                                                netKey = OpenKey(key, str(guid))

                                                (n, addr, t) = EnumValue(netKey, 5) #5th value is the Mac address

                                                (n, name, t) = EnumValue(netKey, 4) #4th value is the network’s name


                                                macAddr = val2addr(addr)

                                                netName = str(name)

                                                print('[+] ' + netName + ' ' + macAddr)




def main():


if __name__ == "__main__":



This is not the original Windows registry analysis script from the aforementioned book, because that script was written for Python 2.6 and on 64 bits Windows it was not working at all. To run the script first install python3 for 64 bits windows and then add the Python folder to your PATH environment vaiable(you can do that from Advanced system settings -> Advanced tab -> Environment variables -> Edit PATH variable). After that open command prompt with administrator privilege and type:

'python [Path-to-this-script]\[script-name].py'

Convert SSID to username

EnumValue function is not the only way of retrieving a key value. For example to convert SSIDs, if you’re curious how you can retrieve SSIDs have a look at hidden folders in C:\[RECYCLER]|[Recycled]|[ $Recycle.Bin], to a username you can query "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\[SID]" key from HKEY_LOCAL_MACHINE using QueryValueEx function:

# Windows registry analysis script


"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"

+ '\\' + sid)

(value, type) = QueryValueEx(key, 'ProfileImagePath') # the value is like %SystemDrive%\Documents and Settings\sina

user = value.split('\\')[-1] # to get the ‘sina’ from value we read the text after last \

return user



Published in Forensic

Python Hacking scripts | Hacking with python

Both professional penetration testers and hackers need to learn hacking with python. Years ago hackers used to use Linux-Shell scripts a lot. A couple of years later Perl and PHP were the popular scripting language for hacking. Now Python is the leading scripting language for hacking. Most of recent attacks can be constructed by Python and if you want to learn all the bits and bobs you can read this book “Violent Python: a Cookbook for Hackers”

In this article I intend to introduce libraries for hacking with python, most of which are taken from the aforementioned book and for a detailed discussion you can refer to that book.

Python language

Python is an interpreter-based language. This means to run python scripts you need python interpreter to be installed. Python support object oriented programming but it also can be used as a modular language. This means Python does not need neither Class structures nor a main method to be run. A Python script can begin by a line that does the purpose and just finishes. This tutorial is not going to be a python programming guide but just a complement for those already knows the python language. But again if you feel, you need some backgrounds you can read the aforementioned book. 

Python hacking script for socket Communication

Hackers often attack from a remote place using a network connection. There are numerous exploits and attacks that circumvent the typical communication scenario (between Client and Server) and communicate with the victim in an unusual way. For example, clients use internet browser applications to connect to a website and servers are supposed to serve with a typical Apache, IIS or etc. server. If everyone had followed this convention there were probably no security vulnerability reported for browsers. The vulnerability shows itself when you bypass all the standard behaviors and implement a custom TCP communication e.g. communicating from the server’s side by a small python script to leverage a vulnerability with the client Internet Explorer browser. This way you can exploit a buffer overflow vulnerability in client’s application such as Internet Explorer.

To implement a custom TCP connection you can use Python’s Socket library which is really easy to use. Writing a python hacking script for opening a connection, reading and sending data is as easy as:

from socket import *

connSkt = socket(AF_INET, SOCK_STREAM)

connSkt.connect(targetHost, targetPort)

connSkt.send('Data you want to send such as an exploit\r\n') #Sending data

results = connSkt.recv(100)  # Data to be read from the victim


Python hacking script for Port Scanning

Before any successful attack there should be a detailed footprinting phase. In an ordinary manual hacking scenario you do the footprining or enumeration phase using Nmap. But when you’re designing your own automated attack scenario and you want to perform an automatic hacking with python you cannot lean on a manual enumeration phase to combine with a python hacking script for exploit development. The best examples are worms; worms are pieces of codes that spread automatically. These Malware first scan their environment, find vulnerable hosts and then exploit them.

Good news is that you can use Nmap in your python hacking script. Install Nmap library for python from this address and then you can acquire Nmap in your codes like this:

nmScan = nmap.PortScanner()

nmScan.scan(targetHost, targetPort)

There are tons of options and results that you can read in your python script but for a simple result to see the status of scanned port you can use this line:



Interacting with other programs in python

There are times that you need the result of another program to perform your hacking with python. This result may be from ssh, a Torrent program (for a botnet scenario) or other commands. In Linux python scripts you can interact with other programs using Pexpect. Using Pexpect you can send your commands to other programs and check the results in order to take the next action. For example to interact with ssh, the following python snippet can be used:

import pexpect

comandString = 'ssh ' + user + '@' + host

child = pexpect.spawn(comandString)

result = child.expect([pexpect.TIMEOUT, 'Are you sure you want to continue connecting', '[P|p]assword:'])


In this example we first sent the command to OS ('ssh ’) and then defined the expected results:

  • Time out
  • Are you sure you want to continue connecting
  • [P|p]assword:

Depending on the results we defined, Pexpect returns a value and we can decide what to do next:

if result == 0: #TimeOut

   print '[-] Error Connecting'


if result == 1: # Are you sure you want to continue connecting


   result = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])

if ret == 0:

   print '[-] Error Connecting' #TimeOut



child.expect(['# ', '>>> ', '> ', '\$ '])

return child.before


If the returned result is not “TimeOut” and is “Are you sure you want to continue connecting” we send “yes” and then expect '[P|p]assword:' to be returned. If everything is OK we then send the password for authentication and then expect these texts '# ', '>>> ', '> ', '\$ ' which show a successful authentication. child.before shows the last result from the ssh program.

While above python hacking script show the functionality of Pexpect, I recommend to interact with SSH, use pxssh library which has login(), logout() and prompt() methods.

Also pay attention that we use Pexpect when we need to interact with the program. If we want to just run a command we just use os.system. For example to run a Metasploit exploit in your python script, having that commands are stored in a file (meta.rc), we use:

import os

import sys

os.system('msfconsole -r meta.rc')



Automating FTP attacks

FTP servers are good candidates for attack, however finding a vulnerable FTP server manually is a very exhausting task. By a python hacking script you can automate FTP attacks. The Python library for FTP interaction is ftplib. This snippet shows the functionality:

import ftplib


   ftp = ftplib.FTP(hostname)

   ftp.login('Password', 'User')

   print '\n[*] ' + str(hostname) + ' FTP Anonymous Logon Succeeded.'

except Exception as e:

   print '\n[-] ' + str(hostname) + ' FTP Anonymous Logon Failed.'


dirList = ftp.nlst() # listing directories


f = open('FileName to write the result of a FTP Download', 'w')

ftp.retrlines('RETR ' +  'PageName to Download', f.write) # reading a FTP page to a file

ftp.storlines('STOR ' +  'PageName to Upload', open('FileName to upload')) # writing a File to a FTP page




Communicating with a web page in your python script | Parse a webpage | Stateful Programming

Either to attack a website automatically or parsing the data in a webpage you need Stateful Programming which in simple words is the process of communicating with a website by an identity that the website is aware of. For example a website may need a login before granting access to a webpage. A library like mechanize in Python provide a mechanism to login by the script and continue requesting protected webpages using the authenticated state. There are also other python libraries that help you to parse a webpage. Re, urllib, and urlparse are some of those. Following scripts show some functionality of these libraries:

import mechanize

import urllib

import re

import urlparse

browser = mechanize.Browser()'Url of the website you want to communicate with’) # Simple communication without GET or POST parameter

reqData = urllib.urlencode({'Post or GET parameter name': ‘Parameter value’, 'Post or GET parameter name': ‘Parameter value’}) # Preparing parameters to pass to the requested page'Url of the website you want to communicate with’, reqData) # Communication with GET or POST parameter

params = {}

params['ParameterName'] = ‘ParameterValue’

reqParams = urllib.urlencode(params) #Another way of preparing parameters

resp ='Url of the website you want to communicate with', reqParams).read() #Communicating the website and reading the response

ParsedValue = re.findall(r'regular expression', resp) # Parsing to find a value



To just read files or pages (regardless of the state) from a website you can use urllib2 library:

import urllib2

Contents = urllib2.urlopen(url).read()


A better library to parse html pages is Beautiful Soup. Finding all the image tags in a page is as easy as:

import urllib2

from bs4 import BeautifulSoup

urlContent = urllib2.urlopen(url).read()

soup = BeautifulSoup(urlContent)

imgTags = soup.findAll('img')

Other Useful methods for hacking with python

gethostbyname(targetHost) # Retrieve host name from dns name

gethostbyaddr(tgtIP) # Retrieve host name from IP address




Published in General Hacking
Advanced Programming Concepts
News Letter

Subscribe our Email News Letter to get Instant Update at anytime