Python black hat pdf +free download






















HookKeyboard pythoncom. Whenever the target presses a key on the keyboard, our KeyStroke function is called with an event object as its only parameter.

We then look at the keystroke that was issued v and if it falls within the ASCII-printable range, we simply print it out. We also check if the user is performing a paste operation w, and if so we dump the contents of the clipboard. The callback function wraps up by returning True to allow the next hook in the chain—if there is one—to process the event. Simply run it, and then start using Windows normally. Try using your web browser, calculator, or any other application, and view the results in your terminal.

The output below is going to look a little off, which is only due to the formatting in the book. I then fired up Internet Explorer, browsed to www. We can now safely say that our keylogger can be added to our bag of trojaning tricks! Taking Screenshots Most pieces of malware and penetration testing frameworks include the capability to take screenshots against the remote target.

This can help capture images, video frames, or other sensitive data that you might not see with a packet capture or keylogger. A screenshot grabber will use the Windows Graphics Device Interface GDI to determine necessary properties such as the total screen size, and to grab the image.

Some screenshot software will only grab a picture of the currently active window or application, but in our case we want the entire screen. Crack open screenshotter. GetSystemMetrics win32con. CreateBitmap screenshot. DeleteDC win32gui. DeleteObject screenshot. First we acquire a handle to the entire desktop u, which includes the entire viewable area across multiple monitors. We then determine the size of the screen s v so that we know the dimensions required for the screenshot.

We create a device context2 using the GetWindowDC w function call and pass in a handle to our desktop. Next we need to create a memory-based device context x where we will store our image capture until we store the bitmap bytes to a file. We then create a bitmap object y that is set to the device context of our desktop. Think of this as a memcpy call for GDI objects. Pythonic Shellcode Execution There might come a time when you want to be able to interact with one of your target machines, or use a juicy new exploit module from your favor- ite penetration testing or exploit framework.

This typically—though not always—requires some form of shellcode execution. In order to execute raw shellcode, we simply need to create a buffer in memory, and using the ctypes module, create a function pointer to that memory and call the func- tion. We kick it off by retrieving our baseencoded shellcode from our web server u. The ctypes cast function allows us to cast the buffer to act like a function pointer w so that we can call our shell- code like we would call any normal Python function.

We finish it up by call- ing our function pointer, which then causes the shellcode to execute x. Store the raw shellcode not the string buffer! We simply baseencoded the shellcode using the standard Linux command line. Any requests for files will be served automatically for you. You should see the following in your Linux terminal: Sandbox Detection Increasingly, antivirus solutions employ some form of sandboxing to determine the behavior of suspicious specimens.

We can use a few indica- tors to try to determine whether our trojan is executing within a sandbox. Our script will also try to determine if the sand- box operator is sending input repeatedly i. A typi- cal machine has many interactions at some point during a day since it has been booted, whereas a sandbox environment usually has no user interac- tion because sandboxes are typically used as an automated malware analysis technique. We can then make a determination as to whether we would like to con- tinue executing or not.

GetLastInputInfo ctypes. Do note that you have to initialize the cbSize u variable to the size of the struc- ture before making the call. The next step is to determine how long the system has been running by using the GetTickCount w function call.

The last little snippet of code x is simple test code where you can run the script and then move the mouse, or hit a key on the keyboard and see this new piece of code in action.

This means that within the last minute or two, you would see user input. If for some reason you see that the machine has been running for 10 minutes and the last detected input was 10 minutes ago, then you are likely inside a sandbox that has not processed any user input. These judg- ment calls are all part of having a good trojan that works consistently. You could also, for example, model a user over time to determine what days and hours they are typically online.

You can easily use PyHook for this purpose as well, but having a couple of different tricks in your tool- box always helps as each antivirus and sandboxing technology has its own ways of spotting these tricks. This works by iterating over the range of valid input keys u; for each key, we check whether the key has been pressed using the GetAsyncKeyState v function call. If the key is detected as being pressed, we check if it is 0x1 w, which is the virtual key code for a left mouse-button click.

We increment the total number of mouse-clicks and return the current timestamp so that we can perform timing calculations later on. We also check if there are ASCII keypresses on the keyboard x and if so, we simply increment the total number of keystrokes detected. Be mindful of the indentation in the code blocks above!

We randomize these thresholds with each run, but you can of course set thresholds of your own based on your own testing. Instead of dying here, you could also choose to do some innocuous activity such as reading random registry keys or checking files.

After we pass this initial check, we move on to our primary keystroke and mouse-click detection loop. We first check for keypresses or mouse-clicks w and we know that if the function returns a value, it is the timestamp of when the mouse-click occurred. Next we calculate the time elapsed between mouse-clicks x and then compare it to our threshold y to determine whether it was a double- click.

For example, it would be rather odd to see double-clicks in a row during typical computer usage. I encourage you to tweak and play with the settings, and to add addi- tional features such as virtual machine detection.

It might be worthwhile to track typical usage in terms of mouse-clicks, double-clicks, and keystrokes across a few computers that you own I mean possess—not ones that you hacked into! Depending on your target, you may want more paranoid settings or you may not be concerned with sandbox detection at all. Using the tools that you developed in this chapter can act as a base layer of features to roll out in your trojan, and due to the modularity of our trojaning framework, you can choose to deploy any one of them.

The last step will use Internet Explorer as a means to exfiltrate data from a target system. Internet Explorer, you say? Even though other browsers like Google Chrome and Mozilla Firefox are more popular these days, most corporate environments still use Internet Explorer as their default browser.

They are a variation on the classic man-in-the-middle attack. Most of these malware strains typically called Browser Helper Objects insert themselves into the browser or otherwise inject code so that they can manipulate the browser process itself. As browser developers become wise to these techniques and antivirus vendors increasingly look for this behavior, we have to get a bit sneakier. By leveraging the native COM interface to Internet Explorer, we can control any IE session in order to get credentials for social networking sites or email logins.

Depending on your target, you can also use this technique in conjunction with your keylogger module in order to force them to re-authenticate to a site while you capture the keystrokes. Our HTTP server will then simply redirect them back to the real login page. We are picking on Facebook and Gmail because corporate users have a nasty habit of both reusing passwords and using these services for business particularly, for- warding work mail to Gmail, using Facebook chat with coworkers, and so on.

Dispatch clsid These are the makings of our man- kind-of -in-the-browser attack. This method is riskier in that a wily user might see the redirect happen, so as a future homework project you could think of ways of pulling cookies or pushing the stored credentials through the DOM via an image tag or other means that look less suspicious.

We then set up a dictionary of target sites v that our attack will support. LocationUrl v if url. We start by iterating through all currently running Internet Explorer u objects; this includes active tabs in modern IE. If we discover that the target is visiting one of our predefined sites v we can begin the main logic of our attack.

We then test to see if the target site has a simple logout URL that we can redirect to x and if so, we force the browser to do so. This is so our HTTP server knows what site to redirect the browser to after collecting the credentials.

We are just looking for the DOM to be fully loaded before allowing the rest of our script to keep executing. This allows us to carefully time any DOM modifications or parsing operations. TCPServer '0. We then parse out the originating site Facebook, Gmail, etc. Kicking the Tires Fire up a new IE instance and run your mitb.

Now browse to Facebook or Gmail and attempt to log in. To make use of your access, you want to be able to exfiltrate documents, spreadsheets, or other bits of data off the target system. Depending on the defense mecha- nisms in place, this last part of your attack can prove to be tricky. There might be local or remote systems or a combination of both that work to validate processes opening remote connections, as well as whether those processes should be able to send information or initiate connections out- side of the internal network.

When a document is encountered, the script will encrypt it using public key cryptography. This will enable us to dead-drop the document and retrieve it when we want to without anyone else being able to decrypt it. We then begin looping through the file contents w and encrypting it in byte chunks, which is the maximum size for RSA encryption using PyCrypto.

When we encounter the last chunk of the file x, if it is not bytes long, we pad it with spaces to ensure that we can successfully encrypt it and decrypt it on the other side. After we build our entire ciphertext string, we baseencode it y before returning it. We use base64 encoding so that we can post it to our Tumblr blog without problems or weird encoding issues.

Unfortunately, there is no quick and easy way of finding UI elements on the Web: I simply spent 30 minutes using Google Chrome and its devel- oper tools to inspect each HTML element that I needed to interact with.

If you wish to use a different service, then you too will have to figure out the precise timing, DOM interactions, and HTML elements that are required—luckily, Python makes the automation piece very easy. It also makes the browser appear to be a bit more human.

Tumblr can present a slightly different login screen with each visit, so the next bit of code x simply tries to find the login form and submit it accordingly. After this code executes, we should now be logged into the Tumblr dashboard and ready to post some information. We are simply hunting through the DOM to find where to post the title and body of the blog posting. These subtle little tricks are important to jot down as you apply this technique to other sites.

Dispatch "InternetExplorer. Application" v ie. It first creates a new instance of the Internet Explorer COM object u—and the neat thing is that you can set the process to be visible or not v. For debugging, leave it set to 1, but for maximum stealth you definitely want to set it to 0.

This is really useful if, for example, your trojan detects other activity going on; in that case, you can start exfil- trating documents, which might help to further blend your activities in with that of the user. After we call all of our helper functions, we simply kill our IE instance w and return. Each time a file is found, we simply pass the full path of the file off to our exfiltrate function. Now that we have our main code ready to go, we need to create a quick and dirty RSA key generation script, as well as a decryption script that we can use to paste in a chunk of encrypted Tumblr text and retrieve the plain- text.

This block of code outputs both a private and public key pair. Then open a new Python file called decryptor. We simply instantiate our RSA class with the private key u and then shortly thereafter we basedecode v our encoded blob from Tumblr. Much like our encoding loop, we simply grab byte chunks w and decrypt them, slowly building up our original plaintext string. The final step x is to decompress the payload, because we previously com- pressed it on the other side.

Kicking the Tires There are a lot of moving parts to this piece of code, but it is quite easy to use. If you left Internet Explorer visible, you should have been able to watch the whole process. If you scroll down, you will clearly see that the title ends where the font is no longer bold.

If you copy and paste the title into your decryptor. Now of course to do the entire con- tents of the file, you would want to automate it using the tricks I showed you in Chapter 5 using urllib2 and HTMLParser , which I will leave as a homework assignment for you.

Another idea for extending the project is to encrypt a length field at the beginning of the blog post contents that tells you the original size of the document before you padded it. You can then read in this length after decrypting the blog post contents and trim the file to that exact size.

Maybe you leveraged a remote heap overflow, or you phished your way into the network. System administrators in large enterprises commonly have sched- uled tasks or services that will execute child processes or run VBScript or PowerShell scripts to automate tasks. Vendors, too, often have automated, built-in tasks that behave the same way.

There are countless ways for you to try to escalate privileges on Windows, and we are only going to cover a few. However, when you understand these core concepts, you can expand your scripts to begin exploring other dark, musty corners of your Windows targets.

We harvest useful data such as the file paths, the user that created the pro- cess, and enabled privileges. Our process monitoring then hands off all file paths to a file-monitoring script that continuously keeps track of any new files created and what is written to them. The final step is to intercept the file-creation process so that we can inject scripting code and have the high-privilege process execute a command shell.

Installing the Prerequisites We need to install a few libraries in order to write the tooling in this chap- ter. Execute the following in a cmd. Make sure you are running as Administrator when doing so. The tool is designed to be used by people on the defense side of security to track process creation and the installation of malware. This would give us insight into potentially insecure file handling or child process creation. It worked, and we walked away with numerous privilege escalation bugs that gave us the keys to the kingdom.

The major drawback of the original El Jefe is that it used a DLL that was injected into every process to intercept calls to all forms of the native CreateProcess function.

It then used a named pipe to communicate to the collection client, which then forwarded the details of the process creation to the logging server. The problem with this is that most antivirus software also hooks the CreateProcess calls, so either they view you as malware or you have system instability issues when El Jefe runs side-by-side with antivirus software. This should make our monitoring portable and give us the ability to run with antivirus software activated without issue.

This will show us any pro- cesses that are created by higher-privilege accounts, and in particular, any processes that are calling external files such as VBScript or batch scripts. Note that in order to capture information about 1. By reading the Python WMI documenta- tion, we learn that you can monitor process creation or deletion events.

One of the class functions is GetOwner, which we call x to determine who spawned the process and from there we collect all of the process informa- tion we are looking for, output it to the screen, and log it to a file. You can see the information being output correctly, and notice that both processes had the Parent PID set to , which is the process ID of explorer.

You could now take an extended break and let this script run for a day and see all of the processes, scheduled tasks, and various software updaters run- ning. The developer uses the native Windows API function 2. What the developer is not thinking about is the fact that if you can climb inside that system tray application, you too now have the ability to load or unload any driver you want, which means you can drop a kernel mode rootkit—and that means game over.

A process running as your user with the wrong privileges is a fantastic way to get to SYSTEM or run code in the kernel. Interesting privileges that I always look out for are listed in Table SeDebugPrivilege This enables the user process to debug other processes.

This also includes obtaining process handles to inject DLLs or code into running processes. SeLoadDriver This enables a user process to load or unload drivers. OpenProcess win32con. OpenProcessToken hproc,win32con. GetTokenInformation htok, win32security. Next, we crack open the process token v and then request the token information for that process w. By sending the win32security. TokenPrivileges structure, we are instructing the API call to hand back all of the privilege informa- tion for that process.

The function call returns a list of tuples, where the first member of the tuple is the privilege and the second member describes whether the privilege is enabled or not. Because we are only concerned with the privileges that are enabled, we first check for the enabled bits x and then we look up the human-readable name for that privilege y. We could easily put some intelligence into the script to log only processes that run as an unprivileged user but have interesting privi- leges enabled.

We will see how this use of process monitoring will let us find processes that are utilizing external files insecurely. Their purpose can vary from continually registering to a central inventory service to forcing updates of software from their own repositories. One common problem is the lack of proper ACLs on these scripting files. If you run your process monitor long enough in an enterprise or you simply install the example service provided in the beginning of this chapter , you might see process records that look like this: The example service provided should generate these events once per minute.

If you do a directory listing, you will not see this file present. What is happening is that the service is creating a random filename, pushing VBScript into the file, and then executing that VBScript. In order to exploit this condition, we have to effectively win a race against the executing code.

When the software or scheduled task creates the file, we need to be able to inject our own code into the file before the process executes it and then ultimately deletes it.

The trick to this is the handy Windows API called ReadDirectoryChangesW, which enables us to moni- tor a directory for any changes to files or subdirectories. Keep in mind that there could be other places you want to keep an eye on, so edit this list as you see fit.

The first task of this function is to acquire a handle to the directory we wish to monitor v. We then call the ReadDirectoryChangesW function w, which notifies us when a change occurs.

We receive the filename of the target file that changed and the type of event that happened x. Kicking the Tires Open a cmd. You may be surprised or not to see files being created, executed, and deleted. You can also use your process-monitoring script to try to find interesting file paths to moni- tor as well. Software updates could be of particular interest. The reason we use a marker is because we can get into an infinite loop whereby we see a file modification, we insert our code which causes a subsequent file modification event , and so forth.

This continues until the file gets gigantic and the hard drive begins to cry. We do a quick split of the file extension u and then check it against our dictionary of known file types v. Kicking the Tires If you installed the example vulnerable service at the beginning of this chapter, you can easily test your fancy new code injector. Eventually, you should see output indicating that a. Includes Valuable Basic Networking Concepts.

Edition - Richard P. Download Bloodline Cradle, 9 - Will Wight. Download Calculus for Dummies - Mark Ryan. Download English in Action 1 - Barbara H. Download Japanese From Zero! Download Lala Pipo - Hideo Okuda. Download Managing to Learn - John Shook. Mizner Jr. Download Pedagogy of the Oppressed - Paulo Freire. Download Playing from the Heart - Peter H.

Download The Stand - Stephen King. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc.

By the end of this chapter, you should be ready to tackle the exercises and code examples in the remainder of the book. We also recommend that you have a Windows 10 VM at the ready. You will use Kali as your guest virtual machine.

The projects in this book use Python 3. At the time of this writing, the default version of Python on the current Kali installation is Python 2. If yours is lower than 3. The virtual environment is among the most essential tools for a Python developer.

Using one, you can separate projects that have different needs. For example, you might use one virtual environment for projects involving packet inspection and a different one for projects on binary analysis.

By having separate environments, you keep your projects simple and clean. This ensures that each environment can have its own set of dependencies and modules without disrupting any of your other projects. We create a new virtual environment by calling the venv package with the -m switch and the name you want the new environment to have.

The scripts, packages, and Python executable for the environment will live in that directory. Next, we activate the environment by running the activate script. Notice that the prompt changes once the environment is activated. The name of the environment is prepended to your usual prompt venv3 in our case.

Now you have Python set up and have activated a virtual environment. Since we set up the environment to use Python 3, when you invoke Python, you no longer have to specify python3—just python is fine, since that is what we installed into the virtual environment. In other words, after activation, every Python command will be relative to your virtual environment.

Please note that using a different version of Python might break some of the code examples in this book. We can use the pip executable to install Python packages into the virtual environment. This is much like the apt package manager because it enables you to directly install Python libraries into your virtual environment without having to manually download, unpack, and install them. I encourage you to expand and modify as necessary.

The main goal is to develop a firm grasp of using Python networking to create tools that you can use during penetration tests, post-exploitation, or while bug-hunting. Chapter 3. The Network: Raw Sockets and Sniffing Network sniffers allow you to see packets entering and exiting a target machine. As a result, they have many practical uses before and after exploitation. Writing a tool like this will also give you a deep appreciation for the mature tools that can painlessly take care of the finer points with little effort on your part.

You will also likely pick up some new Python techniques and perhaps a better understanding of how the low-level networking bits work. In the previous chapter, we covered how to send and receive data using TCP and UDP, and arguably this is how you will interact with most network services.

But underneath these higher-level protocols are the fundamental building blocks of how network packets are sent and received. Of course, if you intend to perform any low-level attacks such as ARP poisoning or you are developing wireless assessment tools, you need to become intimately familiar with Ethernet frames and their use.

Attackers want to be able to see all of the potential targets on a network so that they can focus their reconnaissance and exploitation attempts.

When you send a UDP datagram to a closed port on a host, that host typically sends back an ICMP message indicating that the port is unreachable. Why UDP?

This is quite a simple scanner to build with most of the work going into decoding and analyzing the various network protocol headers. We will implement this host scanner for both Windows and Linux to maximize the likelihood of being able to use it inside an enterprise environment. We could also build additional logic into our scanner to kick off full Nmap port scans on any hosts we discover to determine if they have a viable network attack surface.

These are exercises left for the reader, and I look forward to hearing some of the creative ways you can expand this core concept. Packet Sniffing on Windows and Linux Accessing raw sockets in Windows is slightly different than on its Linux brethren, but we want to have the flexibility to deploy the same sniffer to multiple platforms.

We will create our socket object and then determine which platform we are running on. In our first example, we simply set up our raw socket sniffer, read in a single packet, and then quit. The difference between Windows and Linux is that Windows will allow us to sniff all incoming packets regardless of protocol, whereas Linux forces us to specify that we are sniffing ICMP.

Note that we are using promiscuous mode, which requires administrative privileges on Windows or root on Linux.

Promiscuous mode allows us to sniff all packets that the network card sees, even those not destined for your specific host. This is just to test to make sure we have the core of our sniffing code working. Kicking the Tires Open up a fresh terminal or cmd. If you are running this example on Linux, then you would receive the response from nostarch. The information is packed into binary form, and as shown above, is quite difficult to understand.

This will be the foundation for you to start creating further protocol parsing later on. If we examine what an actual packet looks like on the network, you will have an understanding of how we need to decode the incoming packets. Refer to Figure for the makeup of an IP header. Typical IPv4 header structure We will decode the entire IP header except the Options field and extract the protocol type, source, and destination IP address.

Using the Python ctypes module to create a C-like structure will allow us to have a friendly format for handling the IP header and its member fields. Using C code as a reference when translating to Python objects can be useful because it makes it seamless to convert them to pure Python. This indicates that these are bit fields, and they are 4 bits wide. We will use a pure Python solution to make sure these fields map correctly so we can avoid having to do any bit manipulation.

As you can see, all of the fields that we identified and the preceding C structure match up nicely. With our freshly minted IP structure, we now put in the logic to continually read in packets and parse their information. If you are confined to Linux, then perform the previous ping test to see it in action. I tested this script by opening Internet Explorer and going to www. To perform the same test on Linux, we can ping google. But because we are purposefully building a host discovery scanner, this is completely acceptable.

ICMP messages can vary greatly in their contents, but each message contains three elements that stay consistent: the type, code, and checksum fields.

The type and code fields tell the receiving host what type of ICMP message is arriving, which then dictates how to decode it properly. For the purpose of our scanner, we are looking for a type value of 3 and a code value of 3. This corresponds to the Destination Unreachable class of ICMP messages, and the code value of 3 indicates that the Port Unreachable error has been caused.

One interesting thing to note is that when a host sends one of these ICMP messages, it actually includes the IP header of the originating message that generated the response. We can also see that we will double- check against 8 bytes of the original datagram that was sent in order to make sure our scanner generated the ICMP response. To do so, we simply slice off the last 8 bytes of the received buffer to pull out the magic string that our scanner sends.

The length calculation is based on the IP header ihl field, which indicates the number of bit words 4-byte chunks contained in the IP header. So by multiplying this field by 4, we know the size of the IP header and thus when the next network layer — ICMP in this case — begins. If we quickly run this code with our typical ping test, our output should now be slightly different, as shown below: Protocol: ICMP We are now ready to implement the last bit of logic to send out the UDP datagrams, and to interpret their results.

You can use Linux or Windows for this as the results will be the same. In my case, the IP address of the local machine I was on was If the output is too noisy when you run your scanner, simply comment out all print statements except for the last one that tells you what hosts are responding. This scanner is also useful for the trojan framework we will begin building in Chapter 7.

This would allow a deployed trojan to scan the local network looking for additional targets. Chapter 4. Philippe Biondi has created such a library in the packet manipulation library Scapy. You just might finish this chapter and realize that I made you do a lot of work in the previous two chapters that you could have done with just one or two lines of Scapy. Scapy is powerful and flexible, and the possibilities are almost infinite. I recommend that you use Scapy under a Linux system, as it was designed to work with Linux in mind.

The newest version of Scapy does support Windows,[8] but for the purpose of this chapter I will assume you are using your Kali VM that has a fully functioning Scapy installation. Stealing Email Credentials You have already spent some time getting into the nuts and bolts of sniffing in Python. This technique can of course be applied to any protocol or to simply suck in all traffic and store it in a PCAP file for analysis, which we will also demonstrate.

The iface parameter tells the sniffer which network interface to sniff on; if left blank, Scapy will sniff on all interfaces. The prn parameter specifies a callback function to be called for every packet that matches the filter, and the callback function receives the packet object as its single parameter. The count parameter specifies how many packets you want to sniff; if left blank, Scapy will sniff indefinitely. We can see that when the first packet was received on the network, our callback function used the built-in function packet.

Using show is a great way to debug scripts as you are going along to make sure you are capturing the output you want. This is a really simple example of how you can take a Scapy sniffing script and turn it into a useful tool during penetration tests. Quite simply, we will convince a target machine that we have become its gateway, and we will also convince the gateway that in order to reach the target machine, all traffic has to go through us. Every computer on a network maintains an ARP cache that stores the most recent MAC addresses that match to IP addresses on the local network, and we are going to poison this cache with entries that we control to achieve this attack.

I have also tested this code against various mobile devices connected to a wireless access point and it worked great. Open a new Python file, call it arper. By poisoning both the gateway and the target IP address, we can see traffic flowing in and out of the target. Kicking the Tires Before we begin, we need to first tell our local host machine that we can forward packets along to both the gateway and the target IP address. No errors or other weirdness.

When the attack is finished capturing packets, you should see an arper. You can of course do things such as force the target computer to proxy all of its traffic through a local instance of Burp or do any number of other nasty things. Some great use cases are generating fuzzing test cases based on captured network traffic or even something as simple as replaying traffic that you have previously captured.

We are going to take a slightly different spin on this and attempt to carve out image files from HTTP traffic. With these image files in hand, we will use OpenCV,[9] a computer vision tool, to attempt to detect images that contain human faces so that we can narrow down images that might be interesting.

We can use our previous ARP poisoning script to generate the PCAP files or you could extend the ARP poisoning sniffer to do on-thefly facial detection of images while the target is browsing.

If we detect that the Content-Type header does indeed contain the image MIME type, we split out the type of image; and if there is compression applied to the image in transit, we attempt to decompress it before returning the image type and the raw image buffer. There are classifiers for profile sideways face detection, hands, fruit, and a whole host of other objects that you can try out for yourself. After the detection has been run, it will return rectangle coordinates that correspond to where the face was detected in the image.

If you crack open your faces directory, you should see a number of files with faces and magic green boxes drawn around them.

This technique can be used to determine what types of content your target is looking at, as well as to discover likely approaches via social engineering. You can of course extend this example beyond using it against carved images from PCAPs and use it in conjunction with web crawling and parsing techniques described in later chapters.

Chapter 5. Web Hackery Analyzing web applications is absolutely critical for an attacker or penetration tester. In most modern networks, web applications present the largest attack surface and so are also the most common avenue for gaining access. There are a number of excellent web application tools that have been written in Python, including w3af, sqlmap, and others. The idea is to create a few different tools to give you the fundamental skills you need to build any type of web application assessment tool that your particular attack scenario calls for.

Be mindful that we are just fetching the raw page from the No Starch website, and that no JavaScript or other client-side languages will execute. In most cases, however, you are going to want more finely grained control over how you make these requests, including being able to define specific headers, handle cookies, and create POST requests. This returns a normal file-like object that we can use to read in the data from the remote website.

All systems have their own challenges in terms of installation, configuration, and patch management, and these CMS suites are no exception. Because we can download any open source web application and locally determine its file and directory structure, we can create a purpose-built scanner that can hunt for all files that are reachable on the remote target.

This can root out leftover installation files, directories that should be protected by. This project also introduces you to using Python Queue objects, which allow us to build a large, thread-safe stack of items and have multiple threads pick items for processing.

This will allow our scanner to run very rapidly. We also create a simple list of file extensions that we are not interested in fingerprinting. This list can be different depending on the target application. We then use the os. If the file is not found or is protected by an. Kicking the Tires For testing purposes, I installed Joomla 3. Brute-Forcing Directories and File Locations The previous example assumed a lot of knowledge about your target.

However, in a lot of cases there are configuration files, leftover development files, debugging scripts, and other security breadcrumbs that can provide sensitive information or expose functionality that the software developer did not intend. The only way to discover this content is to use a brute-forcing tool to hunt down common filenames and directories.

We have some built-in functionality that allows us to resume a brute- forcing session if our network connectivity is interrupted or the target site goes down. This can be achieved by simply setting the resume variable to the last path that the brute forcer tried. We will reuse this function later in this chapter. We want some basic functionality to be available to our brute-forcing script. The first is the ability to apply a list of extensions to test for when making requests. URLError,e: if hasattr e, 'code' and e.

It can be useful here to think of using extensions like. We get our list of words to brute-force, create a simple list of file extensions to test for, and then spin up a bunch of threads to do the brute-forcing. In this case, the URL that is referenced in the source code points to an intentionally buggy web application hosted by Acunetix. The cool thing is that it shows you how effective brute-forcing a web application can be.

I cannot stress enough the importance to perform content brute-forcing against all of your web application targets. In order to brute-force Joomla, we have two requirements that need to be met: retrieve the login token from the login form before submitting the password attempt and ensure that we accept cookies in our urllib2 session. This will also be a good whirlwind tour of some additional features of urllib2 that you can employ when building tooling for your own targets.

The next are all of the fields required in order for the form submission to be successful. That randomized string is checked against your current user session, stored in a cookie, and even if you are passing the correct credentials into the login processing script, if the randomized token is not present, the authentication will fail. This means we have to use the following request flow in our brute forcer in order to be successful against Joomla: 1.

Retrieve the login page, and accept all cookies that are returned. Parse out all of the form elements from the HTML. Test to see if we have successfully logged in to the web application. You can see that we are going to be utilizing some new and valuable techniques in this script. Next we initialize our urllib2 opener, passing in the initialized cookie jar, which tells urllib2 to pass off any cookies to it. We then make the initial request to retrieve the login form.

After you have the basics of using the HTMLParser class, you can adapt it to extract information from any web application that you might be attacking. After the HTML has been processed, our brute- forcing class can then replace the username and password fields while leaving the remainder of the fields intact. We simply pass in the username and our wordlist to our Bruter class and watch the magic happen. My target VM is at I have already preset the username to admin and the password to justin in the Joomla installation so that I can make sure it works.

I then added justin to the cain. Trying: admin : left Trying: admin : 2welcome left You can see that it successfully brute-forces and logs in to the Joomla administrator console. To verify, you of course would manually log in and make sure. Recent versions of Burp Suite include the ability to add your own tooling, called Extensions, to Burp. The first extension will enable us to utilize an intercepted HTTP request from Burp Proxy as a seed for creating a mutation fuzzer that can be run in Burp Intruder.

The second extension will interface with the Microsoft Bing API to show us all virtual hosts located on the same IP address as our target site, as well as any subdomains detected for the target domain.

I have to admit that when I first started exploring the Burp Extender API, it took me a few attempts to understand how it worked. But I found a number of extensions on the Burp website that let me see how other folks had developed extensions, and I used that prior art to help me understand how to begin implementing my own code.

As sad as it makes me to admit this, you will require a modern Java installation, which all operating systems either have packages or installers for. Save the JAR file to an easy-to-remember location, such as your Desktop.

Click the Extender tab, and then click the Options tab. You can leave the rest of the options alone, and we should be ready to start coding our first extension. Whether working with a binary protocol wrapped inside HTTP traffic or complex JSON requests, it is critical that you are able to test for traditional web application bugs. I have also been guilty of running standard tools that are not designed to deal with strange protocols or even JSON in a lot of cases.

This is where it is useful to be able to leverage Burp to establish a solid baseline of HTTP traffic, including authentication cookies, while passing off the body of the request to a custom fuzzer that can then manipulate the payload in any way you choose.

A common technique I use is to send them to the Repeater tool, which lets me replay web traffic, as well as manually modify any interesting spots. To perform more automated attacks in query parameters, you will send a request to the Intruder tool, which attempts to automatically figure out which areas of the web traffic should be modified, and then allows you to use a variety of attacks to try to elicit error messages or tease out vulnerabilities.

My first natural instinct is to take a look at the Burp API documentation to determine what Burp classes I need to extend in order to write my custom extension. You can access this documentation by clicking the Extender tab and then the APIs tab. This can look a little daunting because it looks and is very Java-y. Next we see that Burp is expecting two functions to be present in our main class. We follow this up by importing our necessary classes for creating an Intruder payload generator.

So we need to implement the base class and it needs to expose three functions. Or, if you have selected multiple payload areas in the HTTP request, you will only receive the bytes that you requested to be fuzzed more on this later. This function allows us to fuzz the original test case and then return it so that Burp sends the new fuzzed value.



0コメント

  • 1000 / 1000