Showing posts with label Shell code Injection. Show all posts
Showing posts with label Shell code Injection. Show all posts

31/08/2012

Over The Flow (Part 4)

Intro

In this post is the final and last post from the Over The Flow Series (you have to read and understand all previous 3 posts to figure out what is going on here). I will finally insert and execute a shell-code in our vulnerable application. But in this article we will also do further analysis on the SEH exploitation and I will try to fully describe exactly what happened in order to gain a remote shell. But first we should be the appropriate music: 


Note: Paranoia niiiiiiiiice music FYI.

Prerequisites

To understand all the shit I’ll try to explain you, you should fulfill the following requisites:
  1. Basic X86 assembly.
  2. Debugging with ollydebug.
  3. Basic knowledge of exploitation basics in structured exception handling.
Note: Of course you would also have to read the previous three parts

Again a little about Structured Exception Handling  (as a reminder)

The Structured Exception Handler (SEH) is used to handle exceptions within Windows programs. Every process that an Operating System (OS) has is provided with a SEH capability, and when a Windows program generate an exception that it cannot handle itself, control is passed to a SEH address which contains the code that can be used to show a dialog box explaining that the program has crashed or to pass control to a debugger if one is running. When control from our original exception was passed from the debugger back to vulnerable server , the windows exception handler was actually involved in mediating the process. The fact that the windows exception handler become involved in this process allows some additional protections against SEH exploitation to be added, which we have to learn to work around when performing SEH overwrites on certain versions of Windows. 

SEH is an exception handler (from famous Corelan Team)

An exception handler is a piece of code that is written inside an application, with the purpose of dealing with the fact that the application throws an exception.  A typical exception handler looks like this :

try { //run program }
catch { //catch exception } 

Note: The syntax is very easy to understand, it is like any other exception handling.

I quick conceptual representation looks like that:


Note: "Address of exception handler" is just one part of a SEH record – the image above is an abstract representation, merely showing the various components

Windows has a default SEH (Structured Exception Handler) which will catch exceptions. If Windows catches an exception, you’ll see a “xxx has encountered a problem and needs to close” popup. This is often the result of the default handler kicking in.  It is obvious that, in order to write stable software, one should try to use development language specific exception handlers, and only rely on the windows default SEH as a last resort.

When using language EH’s, the necessary links and calls to the exception handling code are generated in accordance with the underlying OS and when no exception handlers are used, or when the available exception handlers cannot process the exception, the Windows SEH will be used (UnhandledExceptionFilter).  So in the event an error or illegal instruction occurs, the application will get a chance to catch the exception and do something with it. If no exception handler is defined in the application, the OS takes over, catches the exception, shows the popup (asking you to Send Error Report to MS).

In order for the application to be able to go to the catch code, the pointer to the exception handler code is saved on the stack (for each code block). Each code block has its own stack frame, and the pointer to the exception handler is part of this stack frame. In other words : Each function/procedure gets a fixed stack frame. If an exception handler is implemented in this function/procedure, the exception handler gets its own stack frame.  Information about the frame-based exception handler is stored in an exception_registration structure on the stack.

This structure (also called a SEH record) is 8 bytes and has 2 (4 byte) elements :
  1. A pointer to the next exception_registration structure (in essence, to the next SEH record, in case the current handler is unable the handle the exception).
  2. A pointer,  the address of the actual code of the exception handler. (SE Handler). 
Simple stack view on the SEH chain components :


Note: At the top of the main data block (the data block of the application’s “main” function, or TEB (Thread Environment Block) / TIB (Thread Information Block)), a pointer to the top of the SEH chain is placed. The bottom of the SEH chain is indicated by 0xFFFFFFFF. If the bottom of the SEH is reached then improper termination of the program will be triggered (and the OS handler will kick in).

More on SEH exploitation 

In the previous tutorial post, I have explained the basics of SEH based exploits. I have mentioned that in the most simple case of an SEH based exploit, the payload is structured like this :

[Junk] [next SEH] [SEH] [Shellcode]

I have indicated that SEH needs to be overwritten by a pointer to “pop pop ret” and that next SEH needs to be overwritten with 6 bytes to jump over SEH. You have to look to all registers, work with breakpoints, etc, to see where your payload / shellcode resides… look at your stack and then build the payload structure accordingly.

The vulnerable program stack

Initially when the stack of the program we are trying exploit (the Qualcomm WorldMail v3.0 stack) looks like that: 



Note: The stack of the program before we try to exploit it. No malicious string insertion is applied in the stack displayed above.

Normally, the pointer to the next SEH record contains an address. But in order to build an exploit, we need to overwrite it with small jumpcode to the shellcode (which should sit in the buffer right after overwriting the SE Handler).  The pop pop ret sequence will make sure this code gets executed.

In other words, the payload must do the following things:
  1. Cause an exception. Without an exception, the SEH handler (the one you have overwritten/control) won’t kick in.
  2. Overwrite the pointer to the next SEH record with some jumpcode (so it can jump to the shellcode).
  3. Overwrite the SE handler with a pointer to an instruction that will bring you back to next SEH and execute the jumpcode.
  4. The shellcode should be directly after the overwritten SE Handler. Some small jumpcode contained in the overwritten “pointer to next SEH record” will jump to it).

Using Metasploit and Olly to overwrite SEH and Next SEH

In order to overwrite the Wordlmail v3.0 SEH and Next SEH I am going to use the very well known tools found in metasploit the pattern_create.rb and pattern_offset.rb and an OllyDebug plugin that can identify binaries with no Safe SEH enabled found here. After we carefully examine the binary for our good luck we can see that the executable of the server is unprotected and therefore can be used to identify a PPR jump and a SEH address. But first lets check how can we overwrite the SEH and NextSEH addresses.

Step 1:First we run ./pattern_create.rb 1500

Note: The length of the buffer was identified in previous posts.

The generated pattern is this:

Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0
Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1
Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2
Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3
Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4
Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5
Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6
Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7B
g8Bg9Bh0Bh1Bh2Bh3Bh4Bh5Bh6Bh7Bh8Bh9Bi0Bi1Bi2Bi3Bi4Bi5Bi6Bi7Bi8Bi9Bj0Bj1Bj2Bj3Bj4Bj5Bj6Bj7Bj8Bj9Bk0Bk1Bk2Bk3Bk4Bk5Bk6Bk7Bk8Bk
9Bl0Bl1Bl2Bl3Bl4Bl5Bl6Bl7Bl8Bl9Bm0Bm1Bm2Bm3Bm4Bm5Bm6Bm7Bm8Bm9Bn0Bn1Bn2Bn3Bn4Bn5Bn6Bn7Bn8Bn9Bo0Bo1Bo2Bo3Bo4Bo5Bo6Bo7Bo8Bo9Bp0
Bp1Bp2Bp3Bp4Bp5Bp6Bp7Bp8Bp9Bq0Bq1Bq2Bq3Bq4Bq5Bq6Bq7Bq8Bq9Br0Br1Br2Br3Br4Br5Br6Br7Br8Br9Bs0Bs1Bs2Bs3Bs4Bs5Bs6Bs7Bs8Bs9Bt0Bt1B
t2Bt3Bt4Bt5Bt6Bt7Bt8Bt9Bu0Bu1Bu2Bu3Bu4Bu5Bu6Bu7Bu8Bu9Bv0Bv1Bv2Bv3Bv4Bv5Bv6Bv7Bv8Bv9Bw0Bw1Bw2Bw3Bw4Bw5Bw6Bw7Bw8Bw9Bx0Bx1Bx2Bx
3Bx4Bx5Bx6Bx7Bx8Bx9



Step 2: We then insert that to our python code and inject that to the  running application:



Note: Take note that the in the buffer I added at the end the } character (which translate to \x7d in hex), so as to trigger the exception.  

Step 3: Start thew IMAP server from the services:


 Step 4: Now we launch the app, attach to OllyDebuger and run the python script:


Step 5: Execute the python script and crush the server, then go View -> SafeSEH:


Note: In this OllyDebugger windows we see that the address was overwritten by the value 41387a41.

Step 6: After we do that, I copy in the clipboard the file, open a bash shell and paste the value to the bash to find the offset using this command ./pattern_offset.rb 41387a41, the repsonse we get back is:
[*] Exact match at offset 774.

Note: We should point out at this stage that the value is written in the NextSEH and not the SEH pointer. Also that the tool patten_create when used always generates the same pattern (e.g. a generated pattern of 1500 long would be always be the same). And that the pattern_offset due to the fact that the stack will always have the same start address 0x00000000 and same ending address 0xFFFFFFFF (see windows memory management) would be able to easily translate the position of the desired value always. 


Step 7: We modify the python script show as to mark with B's the NextSEH and verify our assumption using the following script:


This is the outcome of our python script:


Note: And voila, a quick view to the stack dump shows us that the Next SEH pointer was overwritten with the B's.

Positioning the shell 

Based on the explanations given previously the buffer should have the following format:

 [Junk] [next SEH] [SEH] [Shellcode]

Note: Further investigation will make see that there not enough space for the shell after the SEH. This means that we would have to find space in a different part of the stack. In our example the Shellcode is placed directly after the SEH, but the Wordmail situation we would have to make some memory manipulation and jump back in the stack.

The following OllyDebug picture shows the space left after the SEH pointer:

 
Note: The address we are looking for is 01b9ffac.

And the address end of the stack is:

  
Note: The address we are looking for is 01b9fff4. This is going to give us roughly the size of the space left to inject out shellcode.

Approximate size to insert our shell: 01b9fff4 - 01b9ffac = 48 bytes

So the final buffer would look like this:

  [Junk][Shellcode][Junk][next SEH] [SEH] [BackJump][Junk]

Note: In our situation the junk section of the buffer are nops (\x90).

The reason we do that is because:
  1. The final shellcode will be encoded for avoiding bad characters (e.g. \x00, \xff, \x0a, \x0d etc.) so when it executes it would need to unfold itself and expand within the stack. So surrounding the shell with nops (No Operation Hex = \x90) is always a good idea because it will give space for our shellcode to breath.
  2. When the shellcode is surrounded with nops, even if we make mistakes as far as jump address is concerned or we cannot jump directly to the beginning of the shell the nops are going to help us slide to the beginning of our shellcode.
  3. Back jumping will give us flexibility as far as the space available to for our shell is. 
Now the only think left to do is generate a shellcode using msfpayload, appropriate for our reasons, and then identify the size of the desired shellcode simulate the shellcode with breaks points (break = \xcc) inject that to the IMAP server and see if the break points occupy a continuous space in the stack.

So based on what just described this is how our new buffer should look like:

[ \x90's ][\xCC's][ \x90's ][next SEH] [SEH] [BackJump][ \x90's ]

After we do that in a similar way we calculate the the space, which is 700 bytes (plenty of space) and we create a Reverse Backward  Jump for 700 bites which is this one \xe9\x44\xfd\xff\xff. Our back jump does not have to be very accurate because we placed the nops to slide to our shell.

Finding the proper addresses

Step 1: The next step would be to find the POP POP RET sequence. In order to do that we relaunch the application, attach the application to the debugger select the CPU area and do right click do a Search for -> Sequence of Commands.


Note: The identified address is 7c901d6d, of course we can also use other tools to search for a ppr. Another way would be to use msfpescan from metasploit toolkit.

Step 2: The last step would be to insert after SEH address back jump and voila our exploit is ready to go.

Note:  I am not going to explain how the payload is generated, this is covered in previous post.

And the final exploit is:


Note: Important lessons learned from this exploit. During my effort to reproduce the exploit I learned the hard way that using poor old ollyDebug or IdaPro without other complementary tools is going to be very stressful and time consuming process. The same process if mona.py tools or other appropriate tools were used would have taken me a lot less.

Reference:
  1. http://www.exploit-db.com/wp-content/themes/exploit/docs/17971.pdf 
  2. https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/
  3. https://www.corelan.be/index.php/2009/07/28/seh-based-exploit-writing-tutorial-continued-just-another-example-part-3b/
  4. http://grey-corner.blogspot.com/2010/01/seh-stack-based-windows-buffer-overflow.html
  5. http://www.exploit-db.com/wp-content/themes/exploit/docs/40.pdf  
  6. The Shellcoder's Handbook SECOND EDITION by Chris Anley, Felix FX, Gerardo Richarte and John Heasman
  7. http://bap.ece.cmu.edu/ 
  8. http://www.immunityinc.com/products-immdbg.shtml 
  9. http://www.openrce.org/downloads/details/244/OllySSEH 
  10. http://www.offensive-security.com/metasploit-unleashed/Writing_An_Exploit 
  11. http://thestarman.pcministry.com/asm/2bytejumps.htm 

30/05/2012

Ask and you shall receive (Part 1)

Intro

It is really annoying not being able to learn basic information about penetration testing without struggling to locate the proper information.  This post is about delivering the payload the proper way, the bible is says ask and you shall receive (again this is basic hacking methodology that most penetration testers don't use). So the question I am going to answer in this post is how can someone deliver his or her exploit payload in order to:

A. Bypass:
  1. Network Based Intrusion Prevention (IPS).
  2. Network Based Intrusion Detection  (IDS).
  3. Host Based Intrusion Prevention (IPS).
  4. Host Based Intrusion Detection (IDS).
  5. Network Firewall Device.
  6. Web Application Firewalls.
  7. Deep Content Inspection Devices. 
B. Deliver in short amount of time to: 
  1. Large scale networks
  2. Low bandwidth networks (happening not so often).      
So imagine that your client says to you that you have to test 100 IP's in lets say three days (how can you test for conficker vulnerability) or that you have an internal penetration test and all hosts have host based Intrusion Prevention software, how do you try to bypass the network filtering? Well it is very simple you treat the delivery in a different way. You have to take into consideration the network stack as a separate entity from the vulnerable process. For the sake of this post I am going to use an exploit developed in a previous post. But first a little about the stack and IPS/IDS, on how it works.

A little about data Encapsulation and the TCP/IP Protocol Stack

The packet is the basic unit of information that is transferred across a network. The packet consists, at a minimum, of a header with the sending and receiving hosts' addresses, and a body with the data to be transferred. As the packet travels through the TCP/IP protocol stack, the protocols at each layer either add or remove fields from the basic header. When a protocol on the sending host adds data to the packet header, the process is called data encapsulation. Moreover, each layer has a different term for the altered packet, in our example we are going to use rlogin program and as shown in the following figure that is how data are treated.


Note: As you can see the data (in our case the exploit payload) are broken in packets, segments, datagram, frames and then reassembled again in frames, datagrams, segment and packets and finally into data in it's pure original form.

A little about how IPS/IDS works

Intrusion prevention systems (IPS), also known as intrusion detection and prevention systems (IDPS), are network security appliances that monitor network and/or system activities for malicious activity. The main functions of intrusion prevention systems are to identify malicious activity, log information about said activity, attempt to block/stop activity, and report activity.

Intrusion prevention systems are considered extensions of intrusion detection systems because they both monitor network traffic and/or system activities for malicious activity. The main differences are, unlike intrusion detection systems, intrusion prevention systems are placed in-line and are able to actively prevent/block intrusions that are detected.

More specifically, IPS can take such actions as sending an alarm, dropping the malicious packets, resetting the connection and/or blocking the traffic from the offending IP address. An IPS can also correct Cyclic Redundancy Check (CRC) errors, unfragment packet streams, prevent TCP sequencing issues, and clean up unwanted transport and network layer options.

Intrusion prevention systems classification  types

Intrusion prevention systems are classified in 4 major categories: 
  1. Network-based intrusion prevention system (NIPS): monitors the entire network for suspicious traffic by analyzing protocol activity.
  2. Wireless intrusion prevention systems (WIPS): monitors a wireless network for suspicious traffic by analyzing wireless networking protocols.
  3. Network behavior analysis (NBA): examines network traffic to identify threats that generate unusual traffic flows, such as distributed denial of service (DDoS) attacks, certain forms of malware, and policy violations.
  4. Host-based intrusion prevention system (HIPS): an installed software package which monitors a single host for suspicious activity by analyzing events occurring within that host.
IPS/IDS detection methods

The majority of intrusion prevention systems utilize one of three detection methods: signature-based, statistical anomaly-based, and stateful protocol analysis.
  1. Signature-Based Detection: This method of detection utilizes signatures, which are attack patterns that are preconfigured and predetermined. A signature-based intrusion prevention system monitors the network traffic for matches to these signatures. Once a match is found the intrusion prevention system takes the appropriate action. Signatures can be exploit-based or vulnerability-based. Exploit-based signatures analyze patterns appearing in exploits being protected against, while vulnerability-based signatures analyze vulnerabilities in a program, its execution, and conditions needed to exploit said vulnerability. 
  2. Statistical anomaly-based detection: This method of detection baselines performance of average network traffic conditions. After a baseline is created, the system intermittently samples network traffic, using statistical analysis to compare the sample to the set baseline. If the activity is outside the baseline parameters, the intrusion prevention system takes the appropriate action.
  3. Stateful Protocol Analysis Detection: This method identifies deviations of protocol states by comparing observed events with “predetermined profiles of generally accepted definitions of benign activity.”

Yes but how how?

All this information is pretty cute but how am I going to use this knowledge to exploit my target. Well all this information is not so useless if you have the proper tool kit and right mindset. You have to think and it will all become clear to you it is like matrix. But first lets analyze our exploit scenario, we have an attacker machine, a victim machine with lets say a network filtering entity. The following figure explains conceptually the attack scenario:


Note: See how the Network filter is placed in the victim machine and reassembles all the packets before getting injected to the vulnerable process, which in our example is Free Float FTP Server v1.0. Check out that the Network filter in our example is set in the Transport and Internet Layer. I am placing the bind shell box to the attackers TCP/IP stack because conceptually the payload is going to be sent through the attacker stack, meaning that what you see as a port is behind your stack. 

Redefining buffer overflow  concept (it is all in your mind)

Well if someone asks you what is a buffer overflow you tell him the process of injecting a string, just a string nothing else, when you do an SQL injection you sent a string from your browser to a vulnerable Web Application database, buffer overflows is the same thing, just a set of characters and you can own the world. Now the string that you sent gains (the buffer overflow) a different meaning when injected to the vulnerable process. So lets revisit the exploit developed in previous post called Over The Flow the simple way:



Note: What we do in the exploit shown above is we open a raw socket using Python to sent our exploit to the vulnerable process then connect to the target and sent the exploit.

Converting the buffer to a simple file

Instead of opening a socket to sent the file we will use another delivery method such as the Netcat tool, but first we export the buffer overflow to a file:


Note: See how easy it was to convert the buffer overflow to a file. You should also take into consideration the fact that the file is a single line starting with the ftp USER variable and ending with a CRLLF sequence which designates the end of the file.

So the final file format is:

USER + buffer overflow + CRLF sequence

Note: Simplistically speaking this is a generic form of how all buffer overflows look like when reassembled and before injected to the vulnerable process. This can get you a feeling now how IPS signatures are created.

Netcat as a payload launcher

The rest of the post is easy to describe. Now we can sent our payload using the proper command syntax of Netcat to transfer the payload to the target machine. We just have to issue the following command:

nc 127.0.0.1 21 > mybuffer.txt

Note: And boom you got your shell back, that easy (the command syntax is based in unix-like systems such as Linux). This exploit attempt was reproduced in numerous penetration test so you better be sure that is works because it is a real threat. Image what are the possibilities in real world hacks.

Rapid payload delivery

Now that we know how to deliver a payload with Netcat and we can build a Python server component that launches multiple thread connections waiting for reverse shells to initiate a connection to your attacking machine. A conceptual representation is shown below in this figure.


Note: See how the vulnerable process lances the reverse shell and the multi threaded Python listener accepts the remote connections amazing is not? Again imagine the possibilities of exploitation when using a stable exploit that does not crush the service and remains undetected or how can someone write a costume IPS signature to identify the reverse shell connection. By the way this is a good way to test your IPS heuristics behavior. This type of IPS counter measure can be easily defeated using an IP list randomizer (within your shellcode) and a bot net from compromised machines with a seemingly random IP list as reverse shell receivers (you should understand by now that this is a very realistic scenario already used from conflikor). 

Delivering the payload the right way

A better approach would be to use unicornscan instead of netcat, hping2, sbd, nmap or hping3. With unicornscan you cam easily fool host based signature network filters.Unicornscan is an attempt at a User-land Distributed TCP/IP stack for information gathering and correlation. It is intended to provide a researcher a interface for introducing a stimulus into and measuring a response from a TCP/IP enabled device or network.

Some of its features include asynchronous stateless TCP scanning with all variations of TCP flags, asynchronous stateless TCP banner grabbing, and active/passive remote OS, application, and component identification by analyzing responses. It allows you to specify more information, such as source port, packets per second sent, and randomization of source IP information, if needed. For this reason, it may not be the best choice for initial port scans; rather, it is more suited for later “fuzzing” or experimental packet generation and detection. A much more interesting tool for this job would be fragroute.

Fragroute was created by Dug Song (@dugsong on twitter.) It has the ability to take traffic destined for a particular host and do all sorts of things with it. It can delay, duplicate, drop, fragment, overlap, reorder, etc. It was created primarily to test network based intrusion detection systems, firewalls, and IP stack behavior.

More specifically fragroute intercepts, modifies, and rewrites egress traffic destined for a specified host, implementing most of the attacks described in the Secure Networks "Insertion, Evasion, and Denial of Service: Eluding Network Intrusion Detection" paper of January 1998.

It features a simple rule set language to delay, duplicate, drop, fragment, overlap, print, reorder, segment, source-route, or otherwise monkey with all outbound packets destined for a target host, with minimal support for randomized or probabilistic behavior.This tool was written in good faith to aid in the testing of network intrusion detection systems, firewalls, and basic TCP/IP stack behavior.

Examples of using other tools

Below you can see multiple examples and get multiple ideas on how to by pass network and host based IPS/IDS.


hping3 –file mybuffer.txt –data 127.0.0.1 21 

Note: You can use hping3  to transfer the buffer over flow over TCP/IP stack and play wth the.

fragroute -f frag-3 127.0.0.1 

Note: You can use fragroute to transfer the buffer over flow over and test your IPS signatures.

sbd 127.0.0.1 21 < mybuffer.txt 

Note: You can use sbd to transfer the buffer over flow over an encrypted connection and bypass reverse SSL proxies.

nc 127.0.0.1 21 > mybuffer.txt

Note: You can use nc to transfer the buffer over flow over TCP/IP stack in a simple penetration test without any filtering. 

netcat6 127.0.0.1 21 > mybuffer.txt

Note: You can use netcat6 to transfer the buffer over flow over IPv6 forgotten services that system administrators don't think that can be done anything.  

cryptcat 127.0.0.1 21 < mybuffer.txt 

Note: You can use sbd to transfer the buffer over flow over an encrypted connection and bypass reverse SSL proxies.

Epilogue 

In this post we redefined what a buffer overflow is and we showed alternative ways to deliver the payload.

Reference:
  1. http://docs.oracle.com/cd/E19http://docs.oracle.com/cd/E19683-01/806-4075/ipov-32/index.html
  2. http://www.nask.pl/run/n/IDS_IPS_work
  3. http://en.wikipedia.org/wiki/Intrusion_prevention_system
  4. http://oreilly.com/pub/h/1058 
  5. http://www.downloadnetcat.com/ 
  6. http://www.compsec.org/security/index.php/port-scanners/93-port-scanners-unicorn-scan.html
  7. http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet 
  8. http://linux.softpedia.com/get/System/Networking/sbd-14900.shtml 
  9. http://www.radarhack.com/tutorial/shadowinteger_backdoor.pdf 
  10. http://www.dest-unreach.org/socat/doc/socat.html#FILES 
  11. http://www.dest-unreach.org/socat/ 
  12. http://www.hellboundhackers.org/articles/634-cryptcat:-advanced-usage.html 

21/04/2012

Malware Analysis of MSFPayload

Intro

Nowadays the only people that can actually do a decent Mal-ware analysis are ONLY antivirus research vendors such as Symantec and McAfee. The only thing a Security administrator or an Information Security Consultant can do is Mal-ware behavior analysis. That it is the initial stage of lets say a high profile Mal-ware analysis, but that might not be enough. There are no more than 1000 human beings in this planet that can properly reverse engineer a worm such as Confliker and start writing disinfection tools from scratch (or maybe there are, who knows) or they cannot do it in a reasonable amount if time.

So the next best think from fully reverse engineering a Trojan horse is to do a behavioral analysis and try to confine or mitigate the malicious software. But to me it seems that it is not clear to many people on how to do that or what disinfection really means. For me disinfection means to completely identify how a virus behaves and use proprietary tools to restrain it in such a manner that is going to be no risk.

Lately I was doing some Mal-ware analysis on behalf of a client and  I decided to write a mini guide on how to perform a disinfection strartegy. So for the purposes of this article I am going to do a Mal-ware analysis of  an MSFPayload executable, why? Because is free, open source point and "single point and click" hacking tool. As already demonstrated in a previous article found here someone can embed a MSFPayload in practically any executable by using free Windows tools that come with default windows installations. So what are the techniques of Mal-ware is using?

Occupy Memory Residency

Memory-resident programs are those that can be placed in, and remain in, an affected system's main memory space after execution. Memory residency enables a piece of malware to be readily available whenever needed, ensuring that the malware is easily accessible or can monitor every event on an affected system. This is a malware's way of controlling every activity on an affected system when a condition is satisfied. To find out if a malware is resident in the memory, you may need to invoke system tools like the Task Manager in Windows NT-based systems. On Windows 95- or 98-based systems, you can press CTRL-ALT-DEL, which displays a window containing all the running processes in memory. Once you have full view of the things that are currently in memory, check if a malware is there or not. This is tricky and at the same time risky. Terminating a memory-resident program that is critical to a system may cause some undesirable results, such as displaying the Blue Screen of Death or even triggering the system to restart. It is advisable to check if a specific memory-resident program is indeed alien to the system, which is not an easy task.

Spoof Process Names

Contemporary malware tends to use process names that look strikingly similar to common process names. For example, WSOCK32.DLL, a common process in memory handling the library of socket functions, can be spoofed as WSOCK33.DLL. Another is KERNE132.dll (notice that the L in KERNEL is actually the number 1) can be mistaken for the real KERNEL32.DLL. Sometimes the names are actually valid but the path is different. The KERNEL32.DLL is always found in the \Windows\System32 directory but some malware puts it in \Windows\System (in the example displayed below you can see how MSFPayload is using mswinsoc.dll). 

Alter Start Up locations

Other areas where AutoStart entries can be found are in the files, System.ini and Win.ini. A malware often modifies these with links to itself added to the "run=" or "load=" sections of the files. These files are located at the Windows Directory (typically C:\Windows). Following the same approach that you followed with the registry entries, you can remove them from the AutoStart entries after you have verified that they are malicious. Again, back up these files before making any modification just in case the entries are not malicious and you have to restore the files to their original form. All the necessary system configuration files can be accessed, viewed and edited with the Sysedit program. To invoke the program, click "Start", and then "Run", and then type "Sysedit" in the "Open:" box. Another place where you can find autostart entries are in the Start > (All) Programs > Startup folder. The entries here are also referenced and are executed immediately after system startup. Similarly, you may need to back up these files before tinkering with them. You can also have a look at msconfig wizard to see all services and programs executed from OS.

Malicious Macros

Applications like word processing, spreadsheets or PowerPoint presentations are often vulnerable to macro viruses. You can check for malicious activities by checking for macros within these files. To do this, access the macros organizer (you may refer to your applications help file) and check if there are any unknown macros inside, press the ALT-F11 keys in the more recent offerings of Microsoft Office Family (beginning in Office 97 and up). However, some macro viruses tend to hide themselves from users by changing the foreground/background of the macro font display or by adding multiple tabs to make the text invisible to the default view pane. The following is an explanation of procedures readers can use for two different applications that use macros: MS Word and Excel. 

Infected MS Excel Documents

Search your hard drive for any folder name XLStart. For Excel, this folder contains all the things necessary for customization and this includes macros as well. You can transfer the contents of this folder to a temporary directory. Open Excel and turn on the Macro Virus Protection. After doing so, you can now open the Excel file that may be infected and then the Macro Virus Protection should be able to figure that out for you. 

What Mal-ware is and how?

Once executed, Mal-ware can perform its intended malicious function on a system. Unfortunately, it may not always be apparent to users that their system is indeed infected. Mal-ware is an ordinary program doing things that should not be doing, nothing more nothing less. I am going to use the same payload I used to do the demo on a previous articles, yep the one called ClickMe.exe. So what happens if we generate an MSFPayload that spawns a Shell and then listens for a connection, what tools should someone use? Well I am using the following tools:
  1. Process Monitor v3.01 (from SysInternals)
  2. Fport v2.0 (from McAfee)
  3. Wireshark v1.6.7 (former Ethereal)
  4. OllyDbg v 2.0
So what I am going to do next is to double click ClickOnMe.exe and start analyzing how it behaves, using the tools reported above and looks for thinks such as what is it's memory space, what dll file does it use, what connections does it open. 

Using Process Monitor for recording MSFPayload

So lets start with process monitor and try to record the behavior of the malicious file. What I am going to do is first launch the tool, double click on ClickOnMe.exe and then see what can we see from there. When you launch process monitor you can see that there is a filter button, so what I would do is to filter the process image name (we know it is ClickOneMe.exe)


Note: From the drop down list I checked Process Name and by inserting the process image name I filtered the desired executable. Something else someone cold do is to export the results into a CSV file, imported to an excel and do further analysis on how everything happened (time is also included).


Note: Se the XML format you can use, including all this valuable information such as stack trace and stack symbol resolution, and all that with a free tool, amazing ee?

The most interesting feature of this tool is the process activity tool that records all behavior of the process and timeline, just see below the features:


Note: Have a look at the registry activity, the tool is actually parting with the PC. It has totally 257 registry activities, amazing again. It also does some strange file I/O, later on we are going to have some further analysis on how to take advantage of this feature.


Note: This is one of the most interesting feature a process monitoring tool should have because if you click in the button save you can export all registry keys accessed from the process and then write a quick disinfection batch file e.g. deleting all created registry keys from the malicious process by using the command REG DELETE KeyName [/v ValueName | /ve | /va] [/f] from command prompt or what ever tool you use. You can also filter the registry keys associated with the Trojan based on access rights the Mal-ware has (e.g. read, write e.t.c) usually a Mal-ware is running on users permissions.

Another very cool feature of the tool is the file monitoring capability it has. Process Monitor can actually record all file accessed, modified and used by the Mal-ware while running, filtered per path, extension, and folder name:


Note: See the tool differentiating, how the Mal-ware treats WINDOWS, Prefetch and System32 system files. Metasploit has done a good job optimizing the behavior of MSFPayload utility. ClickOnMe.exe generates even a prefetch to optimize it behavior.  

Prefetcher as MSFPayload Mal-ware accelerator

The Prefetcher is a component of versions of Microsoft Windows starting with Windows XP. It is a component of the Memory Manager that speeds up the Windows boot process, and shortens the amount of time it takes to start up programs. In Windows Vista, SuperFetch and ReadyBoost extend upon the prefetcher and attempt to accelerate application and boot launch times respectively by monitoring and adapting to usage patterns over periods of time and loading the majority of the files and data needed by them into memory so that they can be accessed very quickly when needed. When Mal-ware is using prefetch then it can optimize it's performance.

Suspicious dll files loaded by MSFPayload        

One of the not so few dll files that our MSFPayload loads implies that network activity is happening from the Mal-ware. If you click to expand the plus sign in system32 you will see that mswsock.dll is used by the Mal-ware which means that an outbound connection was attempted. Winsock dll is a windows socket library. One of the many interesting function implemented in Winsock.dll is the gethostbyname which by the way is deprecated. The function mentioned tells us that our Trojan can do a DNS address resolution and sent probably personal data (of course we would have to be sure what function is used).   

Suspicious files loaded by MSFPayload
  
Now if you check the AppPatch windows file system you will see that SysMain.sdb was used, which contains both matching information and compatibility fixes per application. It can be found in the %Windir%\AppPatch directory.

Using FPort for recording MSFPayload

Fport is used to identify unknown open ports and their associated applications. FPort supports Windows NT4, Windows 2000 and Windows XP, it reports all open TCP/IP and UDP ports and maps them to the owning application. This is the same information you would see using the 'netstat -an' command, but it also maps those ports to running processes with the PID, process name and path. Fport can be used to quickly identify unknown open ports and their associated applications. Someone could use FPort to take periodically snapshots from the system your are trying to disinfect and that way record all connections from a possibly malicious software (you can add a task scheduler). The output of FPort concerning the ClickOnMe.exe is:

FPort v2.0 - TCP/IP Process to Port Mapper
Copyright 2000 by Foundstone, Inc.


Pid   Process                Port  Proto   Path                         
3268  ClickOnMe ->  2565  TCP   C:\Documents and Settings\jerry\trojan\ClickOnMe.exe
3268  ClickOnMe ->  9000  UDP   C:\Documents and Settings\jerry\trojan\ClickOnMe.exe


Note: See that the MSFPayload uses both TCP and UDP.
  
Using Wireshark for recording MSFPayload

Wireshark is the world's foremost network protocol analyzer. It lets you capture and interactively browse the traffic running on a computer network. It is the de facto (and often de jure) standard across many industries and educational institutions. Wireshark development thrives thanks to the contributions of networking experts across the globe. It is the continuation of a project that started in 1998.   

We canuse Wireshark to record the MSFPayload and see how the payload looks like in the wire. When the ClickOnMe.exe tries to spawn a reverse shell to the attacker and then start listening for a connection (meaning it binds a shell to the desired port). So lets see what it does it. This is how start listening for all packets by selecting my network card (click to enlarge):


Note: This is how you start listening the net-card. Because tons of tutorials exist out there about Wireshark I am not going to waste more time on Wiresharking the MSFPayload.

Using OllyDebug for recording MSFPayload

OllyDbg is a 32-bit assembler level analyzing debugger for Microsoft Windows. Emphasis on binary code analysis makes it particularly useful in cases where source is unavailable. OllyDbg is a shareware, but you can download and use it for free.With OllyDbg you can analyze all sorts of Mal-ware and verify information that you collected from other software.

So what I would do is to launch MSFPayload and the attack the process and this is what you get:

  
Note: The process terminates immediately after it launches, but that is the stack footprint we get from OllyDebugger. 

Further investigation with Olly Debugger will reveal all engaged dll used from the MSFPayload (click to enlarge):


Note: You can see that the screen shot from above verifies the result from process monitor, again it reveals that mswsock.dll is used so a data confidentiality issue is what you should be looking for.

Using Olly Debugger can help you extract valuable hidden text about what the executable might be doing. In this occasion we could actually see from some ASCII dumps that the Mal-ware is connecting to something:

Address   ASCII dump
0040D230  C:H:P:A:g:X:de:Sq   bgcolor=whit
0040D250  e   Total of %d requests complet
0040D270  ed
 %s
 ..done
 Finished %d requ
0040D290  ests
   apr_socket_connect()
0040D2B0 
Test aborted after 10 failures

0040D2D0 
  
Server timed out

 apr_poll
0040D2F0      apr_sockaddr_info_get() for
0040D310  %s  error creating request buffe
0040D330  r: out of memory
   INFO: %s hea
0040D350  der ==
---
%s
---
 Request too
0040D370  long
   %s %s HTTP/1.0
%s%s%sCo
0040D390  ntent-length: %u
Content-type:
0040D3B0  %s
%s
    PUT POST    text/pla


Note: From the HTTP/1.0, PUT and POST keywords we can understand that the Mal-Ware is using Http to communicate with the attacker. We also know that Meterpreter payload is using http to communicate with the attacking machine. Show by going through these type of details we can find a lot of hidden information and make almost certain the connect back IP. We can even identify how many failed connection it will do until it stops trying to connect back to some IP.

The text shown below shows how it might be constructed our executable:

http://www.zeustech.net
0040E9C0  /<br>
   This is ApacheBench, Ve

Note: If we Google zeustech.net we will find that is a company with traffic manager appliances. Now if we Google ApacheBench (ab) we will find out that is a single-threaded command line computer program for measuring the performance of HTTP web servers. Originally designed to test the Apache HTTP Server, it is actually generic enough to test any web server.The ab tool comes bundled with the standard Apache source distribution, and like the Apache web server itself, is free, open source software and distributed under the terms of the Apache License.

Detecting Mal-ware through ApacheBench signature

Using the above information we can use industry antivirus software to build costume IPS and AV signatures:

Example Usage (taken from Wiki):

    ab -n 100 -c 10 http://www.something.com/

This will execute 100 HTTP GET requests, using 10 threads (10 requests per thread) to the specified URL, in this example, "http://www.yahoo.com". If someone goes to the relevant web page can actually find out about a the little details. So my assumption is that Metasploit is using Apache Bench some how to generate the shellcodes.There is a very interesting google-code project about Apache Bench you can find here.

Finally Removing The Mal-ware

OK we identified the Mal-ware, we found all the changes the Mal-ware did to our system now what? Well the question is relatively easy, you remove the virus. The process of doing that is pretty much easy. First you record all changes through the tools we described then you export the results in CVS format and import them into the excel you process the data e.g. identify new malicious registry keys, maliciously generated files e.t.c. After we do that we generate a Vb-script or a batch file performing the necessary actions to remove the virus. You can actually automate this process by writing an excel file that spits the desired Vb-script or use batch files using macros or you can simple use a bash script to do that by using various delicious tools. The Vb-script or a batch skeleton should consist of 4 sections:

[Section 1]

The Registry Key section (we do removing or deleting keys):
  1. Registry keys to delete.
  2. Registry keys to write.
[Section 2]
 
The File/Folder Section (we do removing or restoring files/folders):
  1. Malicious files/folders to delete.
  2. Malicious files/folders to restore.
[Section 3]
 
The Process Section (we do process killing):
  1. Malicious process to kill (kill process with the desired process image name).
  2. Malicious service to kill (kill service and make sure it does not restart).
[Section 4]

The Network Section (we do network activity killing):
  1. Malicious Network activity to block ( e.g. Write costume signatures for host based IPS)
  2. Malicious Network activity to record (e.g. Write costume signatures for host based IDS)
Further disinfection actions can be taken using other antivirus tools such as host integrity and software blocking tools. We can then distribute the appropriate Vb-script or batch file using Active Directory log-in scripts or other appropriate solutions such as software delivery tools.   


Epilogue

I proved once more that with freeware tools you can do lots of interesting stuff and one of them is Mal-ware analysis.

References:
  1. http://www.wireshark.org/
  2. http://www.mcafee.com/us/downloads/free-tools/fport.aspx
  3. http://technet.microsoft.com/en-us/sysinternals/bb896645
  4. http://www.computing.net/answers/programming/delete-a-registry-key-with-batch/8218.html 
  5. http://en.wikipedia.org/wiki/Prefetcher 
  6. http://msdn.microsoft.com/en-us/library/windows/desktop/ms738524%28v=vs.85%29.aspx
  7. http://en.wikipedia.org/wiki/ApacheBench 
  8. http://www.symantec.com/connect/articles/are-you-infected-detecting-malware-infection
  9. http://code.google.com/p/apachebench-standalone/wiki/HowToBuild 

11/01/2012

Injecting Shellcodes into processes....

Sometime ago, many security focused sites and mailing lists were abuzz with the release of a new tool called ShellCodeExec that has the ability to execute alpha numerically created shellcode (as commonly generated with the Metasploit Framework) the link to the tool can be found here.

Can be compiled and works on POSIX (Linux/Unices) and Windows systems.

Can be compiled and works on 32-bit and 64-bit architectures.

Works in DEP/NX-enabled environments: it allocates the memory page where it stores the shellcode as +rwx - Readable Writable and eXecutable.

It supports alphanumeric encoded payloads: you can pipe your binary-encoded shellcode (generated for instance with Metasploit's msfpayload) to Metasploit's msfencode to encode it with the alpha_mixed encoder.

Set the BufferRegister variable to EAX registry where the address in memory of the shellcode will be stored, to avoid get_pc() binary stub to be prepended to the shellcode.

Spawns a new thread where the shellcode is executed in a structure exception handler (SEH) so that if you wrap shellcodeexec into your own executable, it avoids the whole process to crash in case of unexpected behaviours.

After a search about that tool I found out also about another tool called  Syringe that seemed to work smoother!! with more options,  the link to the tool can be found here. Further reading to a cool blog found here, I found out about the  Syringe options and how to use them.....

Have a look:

C:\Documents and Settings\User\Desktop>syringe.exe
Syringe v1.2
A General Purpose DLL & Code Injection Utility

Usage:

Inject DLL:
syringe.exe -1 [ dll ] [ pid ]

Inject Shellcode:
syringe.exe -2 [ shellcode ] [ pid ]

Execute Shellcode:
syringe.exe -3 [ shellcode ]

And after an extensive research in the internet I found some interesting link about downloading ShellCodes with interesting features which you can find here. Have fun.............