Part V: The Part of Tens All For Dummies books include The Part of Tens. In this part, we give you Python For Dum Beginning Python - 7chan. Pages·· MB·14, Downloads. ISBN (pbk.: alk. paper). 1. Python (Computer program language) 2. Object Programming in. Violent Python . The Python download site (ukraine-europe.info) provides a The following example depicts how to download and install the.
|Language:||English, Spanish, Dutch|
|ePub File Size:||15.36 MB|
|PDF File Size:||15.13 MB|
|Distribution:||Free* [*Free Regsitration Required]|
A collections of FREE ebooks. E-Books/Security/Violent Python a Cookbook for Hackers-Forensic Analysts-Penetration testers and Download History. Sorry . Read "Violent Python A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers" by TJ O'Connor available from Rakuten Kobo. Editorial Reviews. Review. "An information security specialist with the US Army, O'Connor ukraine-europe.info: Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers eBook: TJ Download.
Not in United States? Choose your country's store to see books available for purchase. See if you have enough points for this item. Sign in. Violent Python shows you how to move from a theoretical understanding of offensive computing concepts to a practical implementation. This book demonstrates how to write Python scripts to automate large-scale network attacks, extract metadata, and investigate forensic artifacts.
Software Testing using Visual Studio Satheesh Kumar. Chip Davis. Barzan 'Tony' Antal. Microsoft System Center Orchestrator Cookbook. Samuel Erskine MCT. We Are Anonymous. Parmy Olson. Jose Ugia Gonzalez. Fluent Python. Luciano Ramalho. Microsoft Azure. Marshall Copeland. Mastering Regular Expressions. Jeffrey E. Baya Dewald. Programming Scala. Dean Wampler. Understanding the Digital World.
Brian Kernighan. Jayaram Krishnaswamy. Learn PHP 7. Steve Prettyman. Hussein Nasser. Mobile Computing. Kurt W. WebRTC Blueprints. Andrii Sergiienko. Instant VMware vCloud Starter. Daniel Langenhan.
Mohammed Rasheed. The Hitchhiker's Guide to Python. Kenneth Reitz. Learning C by Programming Games. Arjan Egges. Drupal 5 Views Recipes. Marjorie Roswell. Logic Programming with Prolog. Max Bramer. Judi Doolittle. Java Cryptography. Jonathan Knudsen. Drupal 7 Webform Cookbook. Vernon Denny. Demed L'Her.
James Snell. Oracle BPM Suite 11g: Mark Nelson. Microsoft Log Parser Toolkit. Gabriele Giuseppini. Windows Registry Forensics. Harlan Carvey. Team Foundation Server Customization. Gordon Beeming. AutoIt v3: Your Quick Guide. Andy Flesner. Secrets Stolen, Fortunes Lost. Christopher Burgess.
Jeremy Kashel. Dynamic SQL. Edward Pollack. Joseph Albahari. Vandad Nahavandipoor. Secure and Resilient Software Development. Mark S. Perl Scripting for Windows Security. String Analysis for Software Verification and Security.
Tevfik Bultan. Instant Oracle GoldenGate. Tony Bruzzese. Programming Flex 3. Chafic Kazoun. How to write a great review. The review must be at least 50 characters long. The title should be at least 4 characters long. Your display name should be at least 2 characters long. At Kobo, we try to ensure that published reviews do not contain rude or profane language, spoilers, or any of our reviewer's personal information.
You submitted the following rating and review. We'll publish them on our site once we've reviewed them. Continue shopping. Item s unavailable for purchase. Please review your cart. You can remove the unavailable item s now or we'll automatically remove it at Checkout. Remove FREE. Unavailable for purchase. Continue shopping Checkout Continue shopping.
Chi ama i libri sceglie Kobo e inMondadori. Choose Store. Or, get it for Kobo Super Points! Skip this list. Ratings and Book Reviews 0 1 star ratings 0 reviews. Overall rating 1. Invalid user ucl a from Invalid user oxford from Invalid user matrix from Because SSH clients require user interaction, our script must be able to wait and match for an expected output before sending further input commands. Consider the following scenario.
In this case, we must answer, "yes" before continuing. Next, the application asks us to enter a password before granting us a com- mand prompt. Finally, we execute our command uname -v to determine the kernel version running on our target. RSA key fingerprint is 5b: Permanently added ' Mon Oct 17 Tue Aug 9 Pexpect has the ability to interact with programs, watch for expected outputs, and then respond based on expected outputs. This makes it an excellent tool of choice for automating the process of brute forcing SSH user credentials.
This function takes a username, hostname, and password and returns an SSH connection resulting in an SSH spawned connection. Utilizing the pexpect library, it then waits for an expected output. Three possible expected outputs can occur — a timeout, a message indicating that the host has a new public key, or a password prompt.
If a timeout occurs, then the session. The following selection statement notices this and prints an error message before returning. If the child. This forces the function to send a message 'yes' to accept the new key. Follow- ing this, the function waits for the password prompt before sending the SSH password. Penetration Testing with Python and command string as input. It then sends the command string to the session and waits for the command prompt.
After catching the command prompt, it prints this output from the SSH session. Try starting the SSH server and connecting to it with the script. Brute Forcing SSH Passwords with Pxssh While writing the last script really gave us a deep understanding of the capabili- ties of pexpect, we can really simplify the previous script using pxssh.
Pxssh is a specialized script included the pexpect library. It contains the ability to directly interact with SSH sessions with pre-defined methods for loginQ, logout , prompt. Using pxssh, we can reduce our previous script to the following.
Penetration Testing with Python return s except: We only have a few minor modifications to get the script to automate the task of brute forcing SSH credentials.
Other than adding some option parsing to read in the hostname, username, and password file, the only thing we need to do is slightly modify the connect function. If the login function succeeds without exception, we will print a message indicating that the password is found and update a global Boolean indicating so. Otherwise, we will catch the exception. If the exception indi- cates that the password was ' refused', we know the password failed and we just return.
Additionally, if the exception indicates that pxssh is hav- ing difficulty obtaining a command prompt, we will sleep for a second to allow it to do so. Note that we include a Boolean release included in the connect function arguments. It is interesting to note the password found is 'alpine'. This is the default root password on iPhone devices. In late , a SSH worm attacked jail-bro- ken iPhones.
While this proved extremely useful for some, several users were unaware of this new capability. The worm iKee took advantage this new capability by trying the default password against devices. The authors of the worm did not intend any harm with the worm.
Rather, they changed the background image of the phone to a picture of Rick Astley with the words "ikee never gonna give you up. Additionally, SSH provides the means to authenticate using public key cryptography. In this scenario, the server knows the public key and the user knows the private key. Typically, this provides an excellent method for authentication. With the ability to generate bit, bit, or Building an SSH BotNet with Python bit keys, this authentication process makes it difficult to use brute force as we did with weak passwords.
However, in something interesting happened with the Debian Linux Dis- tribution. A developer commented on a line of code found by an automated software analysis toolkit. The particular line of code ensured entropy in the cre- ation of SSH keys. By commenting on the particular line of code, the size of the searchable key space dropped to bits of entropy Ahmad, Without only bits of entropy, this meant only 32, keys existed for each algorithm and size.
Moreover, he made them available for download at: You can download the bit keys to begin. After downloading and extracting the keys, go ahead and delete the public keys, since we will only need the private keys to test our connection. If H1TP request sent, awaiting response Penetration Testing with Python bl68ba54c7c9ca22d9ebcad6f- As a result, it is accurate to state that quite a few servers were built with a weakened SSH service.
It would be nice if we could build a tool to exploit this vulnerability. However, with access to the key space, it is possible to write a small Python script to brute force through each of the 32, keys in order to authenticate to a passwordless SSH server that relies upon a public-key crypto- graph. In fact, the Warcat Team wrote such a script and posted it to milwOrm within days of the vulnerability discovery.
Exploit-DB archived the Warcat Team script at: However, lets write our own script utilizing the same pexpect library we used to brute force through password authentication. The script to test weak keys proves nearly very similar to our brute force pass- word authentication.
To authenticate to SSH with a key, we need to type ssh user host -i keyfile -o PasswordAuthentication—no. For the following script, we loop through the set of generated keys and attempt a connection. If the con- nection succeeds, we print the name of the keyfile to the screen. Additionally, we will use two global variables Stop and Fails.
Fails will keep count of the number of failed connection we have had due to the remote host closing the connection. If this number is greater than 5, we will terminate our script. If our scan has triggered a remote IPS that prevents our connection, there is no sense continuing.
Our Stop global variable is a Boolean that lets us known that we have a found a key and the main function does not need to start any new connection threads. Penetration Testing with Python print parser. Key Found. If the bit keys do not work, try downloading the keys as well and using them. Attackers often use collections of compromised computers for malicious purposes.
Violent Python - 1st Edition
We call this a botnet because the compromised computers act like bots to carry out instructions. In order to construct our botnet, we will have to introduce a new concept — a class. The concept of a class serves as the basis for a programming model named, object oriented programming.
In this system, we instantiate individual objects with associated methods. For our botnet, each individual bot or client will require the ability to connect, and issue a command. To build the client requires the hostname, username, and password or key. Notice that when we reference a variable belonging to a class, we call it self-followed by the variable name.
To construct the botnet, we build a global array named botnet and this array contains the individual client objects. Next, we build a function named addClientQ that takes a host, user, 5.
As a collective, the members of Anonymous launch a distributed botnet attack against sites they deem adversaries. While arguably illegal, the acts of the Anony- mous group have had some notable and morally victorious successes. In a recent operation, Operation Darknet, Anonymous used its voluntary botnet to overwhelm the hosting resources of a site dedicated to distributing child pornography. Next, the botnetCommand function takes an argument of a command.
This function iterates through the entire array and sends the command to each client in the botnet array. This proves an excellent method for mass controlling targets. To test, we make three cop- ies of our current Backtrack 5 virtual machine and assign. We see we can the script iterate through these three hosts and issue simultaneous commands to each of the victims. While the SSH Botnet creation script attacked servers directly, the next section will focus on an indirect attack vector to target cli- ents through vulnerable servers and an alternate approach to building a mass infection.
The kytv attack proved to be a resounding success. In the following section, we will recreate this attack in Python.
Examining the FTP logs of the infected servers, we can see exactly what hap- pened. An automated script connected to the target host in order to deter- mine if it contained a default page named index. Next the attacker uploaded a new index. The infected server then exploited any vulnerable clients that visited its pages. Typically, users authenticate to FTP servers using a combination of a username and password.
However, some sites provide the ability to authenticate anonymously. In this scenario, a user enters the username "anonymous" and submits an email address in lieu of a password. However, many sites surprisingly provide legitimate rea- sons for this kind of FTP access such as promoting the idea that this enables a more enhanced means of accessing software updates.
We can utilize the ftplib library in Python in order to build a small script to determine if a server offers anonymous logins.
The function anonLogin takes a hostname and returns a Boolean that describes the availability of anonymous logins. In order to deter- mine this Boolean, the function attempts to create an FTP connection with anon- ymous credentials. If it succeeds, it returns the value "True". If, in the process of creating a connection, the function throws an exception it returns it as "False". FTP hostname f tp. Using Ftplib to Brute Force FTP User Credentials While anonymous access grants one way to enter into systems, attackers also have been quite successful with using stolen credentials to gain access to legiti- mate FTP servers.
Storing passwords in cleartext in a default location allows custom malware to quickly steal credentials. Security experts have found FTP stealing credentials as recent malware. Penetration Testing with Python release allowing users to quickly scan for FTP credentials after exploiting a tar- get. This function will take a host and password file as input and return the credentials that allow access to the host. Notice the function iterates through each line of the file, splitting each line at the colon.
The function then takes the username and password and attempts to login to the FTP server. If it succeeds, it returns a tuple of a username, password. If it fails, it passes through the exception and continues to the next line. If the function exhausted all lines and failed to successfully login, it returns a tuple of None,None.
In order to test this, we will first list the contents of the FTP server's directory and search for default web pages. The function returnDefault takes an FTP connection as the input and returns an array of default pages it finds. It does this by issuing the command NLST, which lists the directory contents. The function checks each file returned by NLST against default web page file names.
It also appends any discovered default pages to an array called retList. After completing the iteration of these files, the function returns this array. Penetration Testing with Python f tp. We'll know move on to infecting these pages with our client side attack vector. We will use the Metasploit framework in order to quickly create a malicious server and page hosted at http: The page at From the command shell, we can now execute commands as the administrator of the infected victim.
Microsoft Windows XP [Version 5. To do this, we can download the default pages found on the benign server, inject an iframe, and upload the malicious pages back to the benign server.
Look at the injectPage. The function injectPage takes an FTP connection, a page name, and a redirect iframe string as the input. It then downloads a temporary copy of that page. Next, it appends the iframe redirect to our malicious server to that temporary file. Finally, the function uploads the infected page back to the benign server.
FTP host ftp. Penetration Testing with Python Running our code, we see it download the index. The attack func- tion takes a username, password, hostname, and redirect location as input. The function first logs onto the FTP server with the credentials. Next, we have the script search for default web pages. For each of these pages, the script down- loads a copy and adds a malicious redirection.
The script then uploads the infected page back to the FTP server, which will then infect any future victims that visit that web server. FTP tgtHost f tp. You'll notice we first try to gain anonymous access to the FTP server. If this fails, we then brute force credentials and run our attack against the discovered credentials. While this represents only a hundred lines of code, this attack fully replicates the original attack vector of the kytv infection.
FTP hostname ftp. Soon enough, We get a command shell on a client victim by infecting the webserver by way of the FTP server. Overall, Fake Antivirus captured the credit cards of over 43 million people by and continues to grow. Not bad for one hundred lines of Python code. In the next section, we rec- reate an attack that compromised over 5 million workstations in countries.
The Conficker or W32Downandllp Worm spread so rapidly that it infected five million computers in more than countries Markoff, While some of the advanced methods digital signatures, encrypted payloads, and alternative propagation schemes aided in the attack, Conficker at its very heart, holds some similarities in attack vectors to the Morris Worm of Nahorney, In the following pages, we will recreate the primary attack vectors for Conficker.
At its base infection routine, Conficker utilized two separate attack vectors. The Morris Worm used a password list of passwords.
These two very successful attacks share 1 1 com- mon passwords on the list. When building your attack list, it is definitely worth including these eleven passwords. While the activities resulting in these password attempts are undoubtedly illegal, these passwords dumps have proven interesting research for security experts. DARPA Cyber Fast Track Project Manager, Peiter Zatko aka Mudge made an entire room full of Army Brass blush when he asked them if they constructed their passwords using a combination of two capitalized words following by two special character and two numbers.
Additionally, the hacker group LulzSec released 26, passwords and personal information about users in a dump in early June In a coordinated strike, several of these passwords were reused to attack the social networking sites of the same individuals. However, the most prolific attack was the release of over 1 million usemames and passwords for Gawker, a popular news and gossip blog. First, it utilized a zero-day exploit for the Windows server service vulnerability.
Tak- ing advantage of this vulnerability allowed the worm to cause a stack corruption that executed shellcode and downloaded a copy of it to the infected host.
The open source com- puter security project, Metasploit, has risen to quick popularity to become the de facto exploitation toolkit over the last eight years. Championed and devel- oped by the legendary exploit writer, HD Moore, Metasploit allows penetration testers to launch thousands of different computer exploits from a standard- ized and scriptable environment.
While attacks can be interactively driven using Metasploit, it also has the capability to read in a resource batch file. Metasploit sequentially processes the commands for the batch file in order to execute an attack. Consider, for instance, if we want to attack a target at our victim host Finally, we told Metasploit to exploit the system. Saving the configuration file to the filename conficker. This command will tell Metasploit to launch with the conficker.
When successful, our attack returns a Windows command shell to control the machine. Windows XP - Service Pack 2 - 1 ang: Channel 1 created. We built a configuration file, exploited a machine and gained a shell. Repeating this process for hosts might take us quite a bit of time in order to type out a configuration file, but if we use Python again, we can generate a quick script to scan for hosts that have TCP port open and then build a Metasploit resource file to attack all the vulnerable hosts.
First, lets use the Nmap-Python module from our previous portscanner exam- ple. Here, the function findTgts, takes an input of potential target hosts and returns all the hosts that have TCP port open. By filtering only the hosts that have a TCP port open, our attack script can now target only valid ones. This will eliminate hosts that would ordinarily block our connection attempt. The function iterates through all hosts in the scan.
If the function finds a host with a TCP open, it appends that host to an array. After completing the itera- tion, the function returns this array, containing all the hosts with TCP port open. This listener, or com- mand and control channel, will allow us to remotely interact with our tar- get hosts once they are exploited.
Metasploit provides an advanced and dynamic payload known as the Meterpreter. Running on a remote machine, the Metasploit Meterpreter, calls back to our command and control host and provides a wealth of functionality to analyze and control the infected target.
Penetration Testing with Python commands, route traffic through the infected host, install a key-logger, or dump the password hashes. Additionally, we will set a global configura- tion DisablePayloadHandler to indicate that all future hosts do not need to set up a handler since we already have one listening.
This function will input a Metasploit configuration file, a target, and the local address and ports for the exploit. The function will write the particular exploit settings to the configuration file.
Finally, it sends an instruction to exploit the machine under the context of a job -j and to not interact with the job immediately -z. The script requires these particular options since it will exploit several targets and therefore cannot interact with all of them simultaneously.
Thus, the script will require the second attack vector used in the Conficker Worm. The function smbBrute takes the Metasploit configura- tion file, the target host, a second file containing a list of passwords, and the local address and port for the listener. It sets the username as the default win- dows Administrator and then opens the password file. For each password in the file, the function builds a Metasploit resource configuration in order to use the remote process execution psexec exploit.
Finally, we will add some option parsing back to the main function of the script and then call the previous written functions as required to wrap up the entire script.
The complete script follows. Penetration Testing with Python import nmap def findTgts subNet: However, what happens when you encounter a target with no known exploit? Penetration Testing with Python you build your own zero-day attack? In the following section, we will construct our own zero-day attack. While the Metasploit Framework contains over eight hun- dred unique exploits in its arsenal, you may encounter a time when you have to write your own remote code execution exploit.
This section explains how Python can help simplify that process. In order to do so, lets begin by under- standing stack-based buffer overflows.
The Morris Worm succeeded in part because of a stack-based buffer overflow against the Finger service US v. This class of exploits suc- ceeds because a program fails to sanitize or validate a user input. TAlthough the Morris Worm made use of a stack-based buffer overflow attack in , it was not until that Elias Levy a. If you feel unfamiliar with how stack-based buffer overflow attacks work or would like to learn more, consider reading Elias's paper. For our purposes, we Writing Your Own Zero-Day Proof of Concept Code '5 will take the time to illustrate only the key concepts behind a stack-based buf- fer overflow attack.
Stack-Based Buffer Overflow Attacks In the case of a stack-based buffer overflow, unchecked user data overwrites the next instruction pointer [EIP] to take control of a program's flow. The exploit directs the EIP register to point to a location containing shellcode inserted by the attacker.
A series of machine code instructions, shellcode, can allow the exploit to add an additional user on to the target system, make a network connection with the attacker, or download a stand-alone executable. Endless shellcode pos- sibilities exist, solely depending on the size of available space in memory.
While many methods for writing exploits exist today, stack-based buffer over- flows provided the original exploit vector. However, an abundance of these exploits exist today and continue to grow. In July of , an acquaintance of mine posted an exploit for a vulnerable FTP server to packetstorm Freyman, Although the development of the exploit may appear to be a complex task, the actual attack contains less than eighty lines of code including about thirty lines of shell code.
Adding the Key Elements of the Attack Let's begin by building the key elements of our exploit. First we set our shell- code variable to contain the hexadecimal encoding for a payload we created with the Metasploit Framework. Our return address variable points to an address location in kernel Our padding variable contains a series of NOP instructions.
This builds our NOP-sled. Finally, we assemble all of these variables together into a variable we call crash. Essential elements of stack-based buffer overflow exploit Overflow: Return Address: The 4-byte address used to jump directly to the top of the stack.
A series of NOP no operation instructions that precedes the shellcode, allowing an attacker to guestimate the address location to jump directly to.
If an attacker lands anywhere in the NOP-sled, he slides directly into the shellcode. A small piece of code written in assembly machine code. In the following example, we generated shellcode using the Metasploit framework. If this connection succeeds, we will then authenticate to the host by sending an anonymous username and password. Since the affected program does not properly sanitize user input, this will result in a stack-based Writing Your Own Zero-Day Proof of Concept Code buffer overflow that overwrites the EIP register allowing the program to jump directly into and execute our shellcode.
Freefloat FTP 1. Craig Freyman cdlzz Date: Penetration Testing with Python.
Notice he used shellcode that binds a TCP port on the vulnerable target. So we will run our exploit script and use the netcat utility to connect to port on the target host.
If everything succeeds, we now have access to a command prompt on the vulner- able target. We have written our own tools that can be used during a pen- etration test.
We started by building our own port scanner. Hopefully, you will write code an endless amount of times during a penetra- tion test. We have demonstrated some of the basics behind building Python scripts with the intention of advancing our penetration tests.
Penetration Testing with Python a better understanding of the capabilities of Python, let's examine how we can write some scripts to aid us in Forensic investigations.
References Ahmad, D. Debian's dress rehearsal for a global PKI compro- mise. Albright, D. Eichin, M. With Microscope and Tweezers: Elmer-Dewitt, P. Time Magazine, October Freyman, C. FreeFloat FTP 1. Huang, W. Armorize Malware Blog: Armorize Malware Blog, August Markoff, J. Defying experts, rogue computer code still lurks. Moore, H. Digital Offense. Nahorney B. The Downadup Codex a comprehensive guide to the threat's mechanics.
One, A. Smashing the stack for fun and profit. Phrack Magazine, August Morris Google Scholar. Vaskovich, F. The Art of Port Scanning. Phrack Magazine, September 1. The further you progress, the fewer teachings there are. Randy Stone unraveled the final clues of a year-old mystery. Responsible for at least 10 murders from to , the BTK Killer eluded capture while repeatedly taunting the police and his victims. Among these instructions, the disk contained a file named Test.
Regan, While the file contained instructions from the BTK Killer, it also contained something else: Embedded in the Microsoft proprietary Introduction: Stone verified that a man named Denis Rader served as a church officer at the Lutheran Church Regan, With this information, police requested a warrant for a DNA sample from the medical records of Denis Rader's daughter Shapiro, The DNA sample confirmed what Mr.
A year inves- tigation that had exhausted , man hours ended with Mr. Stone's exami- nation of metadata Regan, Computer forensic investigations prove only as good as the investigator and the tools in his or her arsenal. All too often an investigator may have a nagging question but does not have the tool to answer his question. Enter Python. As we have seen in previous chapters, solving complex problems with minimal code proves a strength of the Python programming language.
As we will see in the following sections, we can answer questions some pretty complex ques- tions with minimal lines of Python code. Let's begin by using some unique Windows Registry keys to physically track a user. With the advent of wireless networking, the Windows Registry stores information related to the wireless connection.
Understanding the location and meaning of these registry keys can provide us with geo-location information about where a laptop has been. From the Windows command prompt, we can list each of the networks, show- ing the profile Guid, network description, network name, and gateway MAC address.
Knowing the MAC address of the wireless network can prove useful, as we will see later. After connecting to the registry, we can open the key with the OpenKeyQ function and loop through the network profiles under this key.
For each profile, it contains the following sub-keys: The regis- try key indexes the network name and DefaultGatewayMAC as fourth and fifth values in the array. We can now enumerate each of these keys and print them to the screen. When testing the script, ensure you are running from inside an Administrator console or you will be unable to read the keys. With the MAC address of a wireless access point, we can now also print out the physical location of the access point as well.
Quite a few databases, both open-source and proprietary, con- tain enormous listings of wireless access points correlated to their physical locations. Proprietary products such as cell phones use these databases to geo- locate without the use of GPS.
The SkyHook database, available at http: An open-source project developed by Ian McCracken provided access to this database for several years at http: Google also maintained a similarly large database for the purpose of correlating access-point MAC addresses to physical locations.
Microsoft locked down a similar Wi-Fi geo-location database shortly afterwards, citing privacy concerns Bright, A remaining database and open-source project, wigle. After reg- istering for an account, a user can interact with wigle. Let us quickly examine how to build a script to interact with wigle.
Using wigle. First, he must open the wigle. Notice the use of the mechanize library. Available from http: This means that once we correctly log on to the Wigle service, it will store and reuse the authentication cookie for us. The script may appear complex, but let's quickly walk through it together. First, we create an instance of a mechanize browser. Next, we open the initial wigle. We then encode our username and password as parameters and request a login at the Wigle login page.
Once found, we return these coordinates as a tuple. Browsert browser. Forensic Investigations with Python browser. With the knowledge of where a computer has been, let's now use the next section to examine the trash.
When a user deletes files via Windows Explorer, the oper- ating system places the files in this special folder, marking them for deletion but not actually removing them. Windows Vista and 7 store the directory at C: Forensic Investigations with Python Using the OS Module to Find Deleted Items To allow our script to remain independent of the operating system, let's write a function to test each of the possible candidate directories and return the first one that exists on the system.
Notice the two subdirectories. They both contain the string S-l and terminate with or This string represents the user SID, corresponding to a unique user account on the machine. In the following figure, we see that this allows us to Using Python to Recover Deleted Items in the Recycle Bin translate the SID S-l directly to the username "alex".
This will allow us to print some more useful output when we recover deleted items in the Recycle Bin. This function will open the registry to examine the ProfilelmagePath Key, find the value and return the name located after the last backward slash in the userpath. It lists the files contained in the Recycle Bin of each user. In the next section, we will examine a method for examining some of the content inside of those files that may prove useful in an investigation.
A not clearly visible object of files, metadata can exist in documents, spread- sheets, images, audio and video file types.
The authoring application may store details such as the file's authors, creation and modification times, potential revisions, and comments. For example, a camera-phone may imprint the GPS location of a photo, or a Microsoft Word application may store the author of a Word document. While checking every individual file appears an arduous task, we can automate this using Python. We can start by downloading the document using the wget utility. The hacker posted the press release unsigned and without attribution.
In addition to the program used to create the document, the PDF metadata contained the name of the author, Mr Alex Tapanaris. Within days, Greek police arrested Mr Tapanaris Leyden, Forensic Investigations with Python It offers the abil- ity to extract document information, split, merge, crop, encrypt and decrypt documents. To extract metadata, we utilize the method. This method returns an array of tuples.
Each tuple contains a description of the metadata element and its value.
Violent Python - 7chan
Iterating through this array prints out the entire metadata of the PDF document. Similarly, we can modify our script to test for specific metadata, such as a specific user. Certainly, it might be helpful for Greek law enforcement officials to search for files that also list Alex Tapanaris as the author.
Devices such as digital cameras, smartphones, and scanners use this standard to save audio or image files. The Exif standard contains several useful tags for a forensic investigation. Phil Harvey wrote a tool aptly named exiftool available from http: Examining all the Exif tags in a photo could result in several pages of information, so let's examine a snipped version of some infor- mation tags.
Notice that the Exif tags contain the camera model name iPhone 4S as well as the GPS latitude and longitude coordinates of the actual image. Such information can prove helpful in organizing images. For example, the Mac OS X application iPhoto uses the location information to neatly arrange photos on a world map.
However, this information also has plenty of malicious uses. Imagine a soldier placing Exif-tagged photos on a blog or a Web site: In the following section, we will build a script to connect to a Web site, download all the images on the site, and then check them for Exif metadata. Leonard Richard- son released the latest version of Beautiful Soup on May 29, Notice that we are using the urllib2 library to open the contents of a document and read it.
In that object, we will extract all the image tags by searching using the method. This method returns an array of all the image tags, which we will return. To download an image, we will use the functionality included in the urllib2, urlparse, and os libraries. First, we will extract the source address from the image tag. Next, we will read the binary contents of the image into a variable. Finally, we will open a file in write-binary mode and write the contents of the image to the file.
PIL, available from http: Next, we parse the Exif data into an array, indexed by the metadata type. Notice that in the main function, we first fetch a list of all the images on the site. Then, for each image in the array, we will download the file and test it for GPS metadata.
Forensic Investigations with Python Testing the newly created script against a target address, we see that one of the images on the target contains GPS metadata information. While this can be used in an offensive reconnaissance sense to target individuals, we can also use the script in a completely benign way — to identify our own vulnerabilities before attackers. Originally created by Dr. Understanding how to parse SQLite databases and automating the process using Python is invalu- able during forensic investigations.
The next section begins by examining the SQLite database format used in the popular Skype voice-over-ip, chat client. Understanding the Skype Sqlite3 Database As of version 4. Under Windows, Skype stores a data- base named main. But what does the Skype application store in this database? To better understand the information schema of the Skype SQLite database, let's quickly connect to the database using the sqlite3 command line tool.
After connecting, we execute the command: We can now see that this database holds tables contain- ing information about contacts, calls, accounts, messages, and even SMS messages.
It contains columns that include information about the user's name, Skype profile name, the location of the user, and the creation date of irm CHAPTER 3: Forensic Investigations with Python the account. Notice that the database stores the date in unixepoch time and requires conversion to a more user-friendly format. Unixepoch time provides a simple measurement for time. It records the date as a simple inte- ger that represents the number of seconds since January 1st, The SQL method datetimeQ can convert this value into an easily readable format.
Let's write a small Python program that utilizes the sqlite3 library to do this. Notice our function printProfile. It creates a connection to the database main. For each result returned, it contains indexed columns for the user, skype username, location, and profile date. We interpret these results and then pretty print them to the screen. Notice that the table Contacts stores information such as the displayname, skype username, location, mobile phone, and even birthday for each contact stored in the database.
All of this personally identifiable informa- tion can prove useful as we investigate or attack a target, so let's gather it. Notice that several of these fields, such as birthday, could be null. In these cases, we utilize a con- ditional IF statement to only print results not equal to "None. However, what happens when two tables contain information that we want to output together?
In this case, we will have to join the database tables with values that uniquely identify the results. Forensic Investigations with Python how to output the call log stored in the skype database. To output a detailed Skype call log, we will need to use both the Calls table and the Conversations table.
The Conversations table maintains the identity of callers and indexes each call made with a column named id. The result of this statement returns results containing the times and identities of all Skype calls made and stored in the target's Skype database. Forensically rich, the Skype profile database actually contains all the messages sent and received by a user by default.
The database stores this in a table named Messages. Our script can print the profile information, address contacts, call log, and even the messages stored in the database. We can add some option parsing in the main function and use some of the functionality in the os library to ensure the profile file exists before executing each of the func- tions to investigate the database.
The script prints out the account profile, contacts, calls, and messages stored on the target. In the next section, we will use our knowledge of sqlite3 to examine the artifacts stored by the popular Firefox browser. Basking Ridge, NJ. Other Useful Skype Queries If interested, take the time to examine the Skype database further and make new scripts.
Con- sider the following other queries that may prove helpful: Want to print out only the contacts with birthdays in the contact list? Have you made plane reservations yets? Working on it Continental does not have any flights available tonight. Parsing Firefox Sqlite3 Databases with Python In the last section, we examined a single application database stored by the Skype application.
The database provided a great deal of forensically rich data for investigation. In this section, we will examine what the Firefox application stores in a series of databases. Firefox stores these databases in a default direc- tory located at C: Let's list the SQlite databases stored in a directory.
But where should an investigator begin? Let's start Investigating Application Artifacts with Python with the downloads. The file downloads. Notice that Firefox does something interesting with the Unix epoch time we previously learned about. To store the Unix epoch time in the database, it multiplies by the number of seconds since January 1st, by 1,, Thus, to properly format our time, we need to divide by 1 million.
In fact, we down- loaded this file in one of the previous sections to learn more about metadata. We now know when a user downloaded specific files using Firefox. However, what if an investigator wants to log back onto sites that use authentication? For example, what if a police investigator determined a user downloaded images that depicted harmful actions towards children from a web-based email site?
The police investigator lawfully would want to log back onto the web-based email, but most likely lacks the password or authen- tication to the user's web-based email. Enter cookies. Because the HTTP pro- tocol lacks a stateful design, origin Web sites utilize cookies to maintain state.
The default installation of Sqlite3 is Sqlite3. Attempting to open the file with an older version of Sqlite3 or the older Python- Sqlite3 libraries will report an error. To avoid our script crashing on this unhandled error, with the cooki es.
To avoid receiving this error, upgrade your Python-Sql ite3 library or use the older Firefox cooki es. Consider, for example, when a user logs onto a web-based email: Firefox stores these cookies in a database named cook- ies. If an investigator can extract cookies and reuse them, it provides the opportunity to log on to resources that require authentication.
Let's write a quick Python script to extract cookies from a user under inves- tigation. Firefox stores this data in a database named places, sqlite. While browser history is infinitely valuable, it would be useful to look deeper into some of the specific URLs visited. Google search queries contain the search terms right inside of the URL, for example. In the wireless section, we will expand on this in great depth. However, right now, let's just extract the search terms right out of the URL.
This specific sequence of characters indicates a Google search. If we do find this term, we will clean up the output by replacing some of the characters used in URLs to pad whitespace with actual whitespace. Finally, we will print out the corrected output to the screen.
Now we have a function that can search the places, scjlite file for and print out Google search queries. Investigating Application Artifacts with Python The option parsing should look very similar to our script to investigate the Skype profile database, from the previous section. You may notice the use of the function os. Windows uses a path file of C: The slashes that indicate directories go in opposite directions under each operating system, and we would have to account for that when creating the entire path to our filename.
The os library allows us to create an operating- system-independent script that will work on Windows, Linux and Mac OS. With that sidebar aside, we have a complete working script to do some seri- ous investigations into a Firefox profile. For practice, try adding some addition functions to this script and modify it for your own investigations.
Forensic Investigations with Python for row in c: Forensic Investigations with Python Running our script against a Firefox user profile under investigation, we see the results. In the next section, we will use the skills learned in the two previous sections, but expand our knowledge of SQLite by searching through a haystack of databases to find a needle.
The meaning of life? How did Lost end? After a significant investigation, Mr. Warden revealed proof that the Apple iOS operating system actually tracked and recorded the GPS coordinates of the device and stored them in a database on the phone called consolidated, db Warden, The device deter- mined the location information by triangulating off the nearest cell-phone towers in order to provide the best service for the device user.
However, as Mr. Furthermore, the process used to backup and store a copy of the mobile device to a computer also recorded this informa- tion. While the location-recording information has been removed from the Apple iOS operating system functionality, the process Mr.
Warden used to dis- cover the data remains. In this section, we will repeat this process to extract Investigating iTunes Mobile Backups with Python information from iOS mobile device backups. Specifically, we will extract all the text messages out of an iOS backup using a Python script. When a user performs a backup of his iPhone or iPad device, it stores files in a special directory on his or her machine. For the Windows operating system, the iTunes application stores that mobile device backup directory under the user's profile directory at C: The iTunes application that backs up mobile devices stores all device backups in these directories.
Let's examine a recent backup of my Apple iPhone. Examining the directory that stores our mobile directory backup, we see it con- tains over unhelpfully named files.
Each file contains a unique sequence of 40 characters that provide absolutely no description of the material stored in the specific file. This command uses the first iden- tifying bytes of a file header and footer to determine the file type.
SQLite 3. JPEG image data 68dfe03f7fef5f4bal5afe38db: JPEG image data cb27b4af77bldlee34bc JPEG image data af02c64b0ae68d2a2cff Forensic Investigations with Python ba63dfde: JPEG image data 6ad6e84dcf44ac62d: We will use a Python script to quickly enumerate all the tables in each database found in the entire mobile backup directory. Notice that we will again utilize the sqlite3 Python bindings in our example script. Our script lists the contents of the working directory and then attempts to make a database connection to each file.
The previous command allows us to enumerate out the database schema. While the script does find several databases, we have snipped the output to show a specific database of concern.
- A GUIDE TO THE PROJECT MANAGEMENT BODY OF KNOWLEDGE FREE EBOOK DOWNLOAD
- RALPH WALDO EMERSON FREE EBOOK DOWNLOAD
- ROMANCE EBOOK DOWNLOAD MOBILE9
- THE GIRL YOU LEFT BEHIND EPUB FREE DOWNLOAD
- A SPOT OF BOTHER EBOOK DOWNLOAD
- HOW TO DOWNLOAD EPUB ON IPAD
- CECIL EBOOK FREE DOWNLOAD
- DOWNLOAD EBOOK ONTO KINDLE