Monday, October 27, 2014

Creating a Secure Tor Environment

As we all know there are ways that your real IP can be leaked when using tor (JavasScript, Flash, Malware and software errors). In this tutorial I'm going to show how to create a fairly secure tor environment using VMWare, which will prevent any IP leaks. The environment can be used for general browsing and malware research.

The first thing you're going to need to do is install VMware workstation (VMware player may also work), then install your favorite windows OS.

As you can see, I'm using Windows 8 because it's a great OS with a totally decent user interface which wasn't designed by Fisher Price.
The following instructions are to be carried out on the host (the computer running VMware)
Next you're going to need to enter the Virtual Machine settings and set the Network Adapter to Bridged, this will allow your VM to act as if it's a part of the network you're connected to. I should warn you that this may not be ideal for malware research as malware could probe, and possibly exploit, devices on your network. I will do a second (more complicated) tutorial that shows how to isolate the VM from your network, whilst still allowing it to connect to the internet via Tor.



If you have multiple network interfaces on your host machine, you will need to go into the VMware "Edit" menu and click "Virtual Network Preferences", from there you can set the bridge to connect to the adapter you use for internet access.



Next you need the network (local) IP Address of the host network adapter you specified in the above. If you don't know how to do that, you can go to the network settings in control panel, right click the network adapter, click "status", then click "details" and it will be under "IPv4 Address".




You should download and install the "Vidalia Relay Bundle" as opposed to the tor browser. You can disable the relay feature by specifying "Client only".



You will also need to edit the torrc file and set it to listen on the host's network IP (and an port of your choice).



The following instructions are to be carried out inside the Virtual Machine
Now you need to setup the VM network adapter. All you need to do is go into the adapter settings, select "internet protocol version 4 (TCP/IPv4) and set "IP Address" to an IP within the network range of your host's adapter (I chose 192.168.1.99 as my host adapter is 192.168.1.66).



If you set up everything correctly thus far, you should get a response when pinging your host's network IP.



Now the VM is connected to your network but will not be able to access the internet, this is a good thing because it means once we finish the setup, internet access from within the VM will only be possible with tor.

I've decided to use proxifier, but the next few steps should work with any proxification software. First we will need to white-list the host's network IP Address so we don't get an infinite loop.



Once that's done it's time to add our proxy server. The proxy server will be the host's IP and the port you decided to install tor on.



Now set the new proxy as the default rule (you can choose to skip this step and make specific rules if you wish).



Finally you need to set the name resolution mode to always resolve via proxy or the system will not be able to look up any domains.



If everything worked, you should be able to open a browser and check that your're connected via tor. If the proxy client is closed, your VM internet will simply stop working instead of revealing your real IP.

Enjoy spending the rest of your life typing captchas.




Monday, October 13, 2014

New IRC Launch

For anyone still into IRC, MalwareTech has partnered with sigterm.no to launch a new IRC network. It's still fairly new so don't expect an instant response, but everyone is welcome (socializing or just asking for help).

Easy Method
Simply use our web IRC client: https://irc.malwaretech.com/

Proper Method
The server requires SSL so you'll need a client like mIRC (Windows), HexChat (Linux/Windows), or LimeChat (Mac). For windows (if you haven't already), you may need to download and install OpenSSL.

Server: irc.malwaretech.com
Port: +6697 (Include the + for SSL)
Channel:     #MalwareTech
Mirc:     /server irc.malwaretech.com:+6697
HexChat:     /server -ssl irc.malwaretech.com 6697


(Tor, I2P, and Proxies are all allowed).

Welcome to IRC



Saturday, October 11, 2014

Usermode Sandboxing

A lot of people (including myself, until recently) think that effective sandboxing requires a filter driver or kernel hooking, but this is no longer the case. A new security feature introduced in Windows Vista known as the Windows Integrity Mechanism can be used to create sandboxes that run entirely in usermode. Although the mechanism was not designed to be used this way, it makes for great driverless sandboxing.

The Windows Integrity Mechanism

Similar to User Account Contorl (UAC), the Windows Integrity Mechanism allows the system to restricted applications from accessing certain resources; however, it's more defined than simply elevated/unelevated. There are 4 main levels provided, which can be set by a parent process prior to execution.

System Integrity (Mandatory Label\System Mandatory Level)
This is the highest integrity level and is used by processes and services running under the Local Service, Network Service, and System account. The purpose of this level is to provide a security layer between Administrator and System, even a process running as full Administrator cannot interact with with System integrity level processes (The only exception to this rule is if the administrator account is granted SE_DEBUG_NAME privilege, then the process can enables this privilege in its token to interact with processes across integrity and user boundaries).

High Integrity (Mandatory Label\High Mandatory Level)
The default integrity level assigned to processes running under the Administrator account, if User Account Control is enabled this level will only be given to elevated processes.

Medium Integrity (Mandatory Label\Medium Mandatory Level)
Given to processes running under a limited (non-Administrator) user account or processes on an Administrator account with UAC enabled. Processes assigned this integrity level can only modify HKEY_CURRENT_USER registry keys, files in non protected folders, and processes with the same or lower integrity.

Low Integrity (Mandatory Label\Low Mandatory Level)
The lowest integrity level is not assigned to processes by default, it is either assigned through inheritance (given to processes created by other low integrity processes) or set by the parent process. A process running with low integrity level can only create/modify keys under HKEY_CURRENT_USER\Software\AppDataLow and write files to %USER PROFILE%\AppData\LocalLow. It is practically impossible for a low integrity process to make any changes to the system; However, it can still read most data.

The windows integrity mechanism has a strict set of rules which makes it a nice system for process isolation (when used properly).

  • A process cannot change its own integrity level.
  • Once a process is running, the integrity level cannot be changed (even by a higher integrity process).
  • A process can create processes with the same (or lower) integrity level, but not higher.
  • Processes cannot modify/write processes/files with a higher integrity level.
There are a few (fairly low risk) exceptions to the above rules.
  • A high integrity process granted SE_DEBUG_NAME can modify processes of higher integrity level. 
  • A medium integrity process that is signed by Microsoft can elevate some COM objects from medium to high integrity (this is what gets leveraged by the auto-elevated process UAC exploit).
  • A process can request elevation from medium to high integrity, but only on execution (spawns UAC prompt). 
Communication between a low and higher integrity process (IPC) is possible when explicitly enabled by the higher integrity process. Any of the following methods can be used:
  • Shared Memory
  • Sockets
  • RPC
  • Windows Messages
  • Named Pipes

Usermode Sandboxing

In the past usermode sandboxes would inject a dll into sandboxed processes and hook various functions within ntdll, although this was generally quite effective, applications could escape the sandbox by reading ntdll from the disk and using it to restore the hooks. Now usermode hooks are making a comeback in sandboxing, but without the previous fallbacks.




Processes can be spawned as low integrity to preventthem making changes to the system; However, in order for the sandboxed process to continue functioning normally, it may need to make some (limited) changes to the system, this is where the hooks come in. 

The sandbox creates a broker process which runs with a normal integrity level, this process then uses CreateProcessAsUser to spawn the target (sandboxed) process at low integrity. Before the target process begins execution, the sandbox dll is loaded and hooks ntdll so the hooks can be used to pass information about any calls (target function, parameter addresses, number of parameters) to the broker process via IPC. The broker process will read the parameters from the sandboxed process and filter/process calls on its behalf. Unlike with previous usermode sandboxes, removal of the hooks will result in the process not being able to modify system resources as it requires the broker process to do so on its behalf. 

This type of sandboxing is already used by some applications (Such as Chrome, Internet Explorer, and Flash Player) to reduce the attack surface for exploits. Low integrity processes are used for processing and handling of untrusted data such as javascript or flash (As a result an exploit would first have to exploit the low integrity process and then exploit the sandbox process to gain full execution on the system).  

For malware sandboxing, things are a bit different: Because low integrity processes can still manipulate other low integrity processes (most browsers run as low integrity), sandboxed malware would still be able to inject into a browser process and pass data back to a command and control server. Low integrity processes are also not very restricted in terms of reading data and could log documents and program data. To protect malware from injecting into browsers or reading personal documents, it would be possible to run the sandboxed and broker process under a different user account (CreateProcessAsUser), aslLow and medium integrity processes cannot read documents from other user's directories or interact with processes across user boundaries; However, they could still read from Program Files and System32. 

Conclusion

Although the Windows Integrity Mechanism is by no means perfect for malware sandboxing, it is definitely a considerable alternative to maintaining complex filter drivers and paying for code signing certificates. Windows 8 even introduces a new features, AppContainer, which nicely complements the Windows Integrity Mechanism by allowing processes to be restricting to only reading and writing within their install folder. If Microsoft could just manage to stop making Fisher Price user interfaces for one operating system, we may see anti-malware sandboxes shifting to usermode as people move away from Windows 7.

Sunday, September 7, 2014

Astute Explorer (GCHQ Challenge 5 - 10)

Continuation for http://www.malwaretech.com/2014/09/astute-explorer-gchq-challenge-1-5.html



Vulnerability
On line 26 the function fails if exactly BLOCK_SIZE is not read, this means if there is data available but less than BLOCK_SIZE is present, or the read fails, the function will return NULL. On failure the function does not free szBuffer so there's a pretty serious memory leak.

Solution
If the read operation fails, the function should free(szBuf) before returning null, it should also be worth considering handling the event that the read function returns less than BLOCK_SIZE.



Vulnerability
I have a hard time understanding the point of this function (it reads the data to a local buffer, which is then disregarded on return), but I'm sure making the function useful is not part of the assignment. The problem exists on line 1009; assuming GetFromInput can read more than 1 byte at a time, it can still exceed MAX_RECEIVE. For example: if MAX_RECEIVE is 10 and GetFromInput reads 20 bytes, siBytesReceived is going to be 20, the loop will exit but the data will have already been written and siBytesRecieved will already have exeeded the limit. There's also the problem that if GetFromInput can fail or return less than MAX_RECEIVE, the loop has no way of checking this and will continue looping (possibly infinitely).

Solution
The best idea would be to implement a parameter in GetFromInput that allows the user to specify the maximum amount of data to read in a single call. The function can then calculate how much data is left before MAX_RECEIVE is hit and specify a limit to prevent more than that from being read.




Vulnerability
I wasn't able to find any vulnerabilities here, unless the user supplies invalid pointers to the function (it should be their job to check they're valid, not the functions). On line 45 the loop will decrement len until it's 0 then exit, as a result it will always return 0.

Solution
Make a copy of len and then decrement the copy.





Vulnerability
If the aim of this code was to use obscure nested if/else statements to make code auditing almost impossible, then the programmer (who probably works on the security team at oracle) did a great job. I'm really not sure what's going on with the code or what err is and where it's set. Assuming err is an actual variable and not pseudo-code a runtime library function like malloc wouldn't set it; if malloc returns NULL the application is going to try and use that null pointer. There's also the issue of the use-after-free on line 52: On error ptr is freed and abrt is set, which means logError will always be passed ptr after it has been freed.

Solution
Stop hiring college kids.




Vulnerability
This piece of code should be instantly recognizable as the apple SSL bug from February (it was all over the news and security sites for months). The extra goto fail; on line 408 means the application will always skip to the cleanup code without setting err, as a result the client doesn't verify that server owns the private key matching the certificate, which opens the client up to MITM attacks.

Solution
Remove the extra goto fail;

Conclusion

Although the challenges are fun, they are really poorly made. Most of the code is taken from various websites and no context is give, leaving the player making massive assumptions about how the code works. I can't think of a real world scenario where you would have to find vulnerabilities in tiny snippet of code without knowing what they do or how the application uses them. Almost all of the vulnerabilities in this article could be non existent if the application performs check prior to calling the snippets, or if assumptions made about the imaginary functions they call are wrong.

Astute Explorer (GCHQ Challenge 1 - 5)

GCHQ has been having trouble finding experienced hackers and programmers to work for them, so they've put out a lot of, admittedly fun, challenges. The idea is that people who do well in the online challenges are selected to do face to face challenges, the top few people from the face to face challenge go through to the masterclass, then the top people from the masterclass will be vetted for a job, finally if you pass the vetting process you get to waste your skill earning 35k/year playing cyber warrior for some NSA wannabes. As you can see, it's better to just use the online challenges to kill some time (You can't even apply for GCHQ unless you're a UK citizen).

Sadly I missed the first challenge, but managed to get into "Astute Explorer" just in time (It's finished now so I'm posting my answers). The challenge is an imaginary company is under cyber attack and want you to help secure their software, they have even been kind enough to provided you with random snippets of C code (without any context). Your job is to provide the line number of the vulnerability, explain why it's a vulnerability, and how to patch it. So let's take a look (my area of expertise is malware, so sorry if I end up getting stuff wrong).




Vulnerability
I'm not sure there's an exact line number, but the vulnerability here is pretty obvious. strcpy and strcat don't do any checks to make sure the target buffer is large enough to fit the string, so by providing a username/password that exceeds the size of szTotalString, you can cause a buffer overflow.

Solution
A lot of people would use functions like strlcpy/StringCchCopy, which copy as much data into the buffer as it can fit then null terminates it. In my opinion this is stupid because the code would still try to check the username and password despite the fact not all of it was copied, I'd personally do strlen on the username and password, then fail if it exceeds the maximum length.



Vulnerability
This is a fun one, you can chain multiple vulnerabilities in the code to cause a heap overflow. The height and width are user specified, so the first thought would be to specify a height and width so large that it causes an integer overflow when calculating the size on line 94, resulting in the allocated buffer being too small to accommodate board_squared_t. If you look at line 91 it makes sure that the height and width don't exceed a certain size, Foiled! Or not? The mistake here is that height and width are signed integers and if you listened in maths: multiplying 2 negative values gives a positive result. We can bypass the maximum size check by specifying large negative values instead, which will then become positive and still cause our integer overflow.

Solution
Pretty simple, just declare height and width as unsigned integers instead of signed.





Vulnerability
I literally have no idea what's going on here. Why is iSize being multiplied by the size of int (4)? What is szBuffer? What does the number is %d = %d mean? If someone handed me this code I'd assume they got their degree in a cereal box and send them back to work at geek squad. Assuming pszArguments[2] is a string and pszArguments[1] is the length of the string, the memcpy operation on line 556 is going to copy 4x more bytes that the length of the string and probably crash. It should also be noted that iArguments isn't checked, so if the user doesn't specify enough arguments, the application is going to crash.

Solution
Stop doing drugs at work.




Vulnerability
On line 84 szError is passed as the format argument to printf. Because printf will interpret any format specifiers in the format argument this is unsafe (format strings exploit). If the error string were to contain "%d%d%d" the next 12 bytes of memory on the stack would be output to the user, it's also possible to use the %n specifier to write arbitrary data to an arbitrary location.

Solution
printf("%s", szError);



Vulnerability
I wasn't able to find any major vulnerabilities here. The code leaks memory because _strdup allocates a buffer, which is never freed. There's also an off-by-one error on line 352: the code checks if the filename is larger than or equal to 3, however the extensions in the szOkExt array include the dot (4 bytes), if the user specified a 3 byte filename the code would try to compare 4 bytes and possibly (but unlikely) crash the application.

Solution
Check if cFileName is bigger than 3 and free szLCase before return.

Conclusion

I'm clearly not a hacker.
Other 5 answers coming tomorrow. 

Monday, June 16, 2014

Usermode System Call hooking - Betabot Style

This is literally the most requested article ever, I've had loads of people messaging me about this (after the Betabot malware made it famous). I had initially decided not to do an article about it, because it was fairly undocumented and writing an article may have led to more people using it; However, yesterday someone linked me to a few blogs posting their implementations of the hook code (without explanation), so I've finally decided to go over it seeming as the code is already available.

Win32/64 System Calls

System call is a term used to describe functions that do not execute code in usermode, instead they transfer execution to the kernel where the actual work is done. A good example of these is the native API (Ex: NtCreateFile\ZwCreateFile). None of the functions beginning with Nt or Zw actually do their work in usermode, they simply call into the kernel and allow the kernel mode function with the same name to do their work (ntdll!NtCreateFile calls ntoskrnl!NtCreateFile).

Before entering the kernel, all native functions execute some common code, this is known as KiFastSystemCall on 32-bit windows and WOW32Reserved under WOW64 (32-bit process on 64-bit windows).

Native function call path in user mode under windows 32-bit

Native function call path in user mode under WOW64

As is evident in both examples: Nt* functions make a call via a 32-bit pointer to KiFastSystemCall (x86) or X86SwitchTo64BitMode (WOW64). Theoretically we could just replace the pointer at SharedUserData!SystemCallStub and WOW32Reserved with a pointer to our code; However, in practice this doesn't work.

SharedUserData is a shared page mapped into every process by the kernel, thus it's only writable from kernel mode. On the other hand WOW32Reserved is writable from user mode, but it exists inside the thread environment block (TEB), so in order to hook it we'd have to modify the TEB for every running thread.

KiFastSystemCall Hook

Because SharedUserData is non-writable, the only other place we can target is KiFastSystemCall which is 5 byte (enough space for a 32-bit jump). Sadly that actually turned out not to be the case because the last byte, 0xC3 (retn), is needed by KiFastSystemCallRet and cannot be modified, which leaves only 4 writable bytes. 

The sysenter instruction is supported by all modern CPUs and is the fastest way to enter the kernel. On ancient CPUs (before sysenter was invented) an interrupt was used (int 0x2E), for compatibility it was kept in all subsequent versions of windows.

The now obsolete KiIntSystemCall

Here you can see, KiIntSystemCall has a glorious 7 writable bytes (enough space for a 32-bit jump and some) it's also within short jump range of KiFastSystemCall. As you've probably guessed by now, we can do a 2 byte short jump from KiFastSystemCall to KiIntSystemCall and then a 32-bit jump from within KiIntSystemCall to our hook procedure.

Now, what if something calls KiIntSystemCall? Well, it's unlikely but we can handle that too: The rule for the direction flag on windows is that it should always be cleared after a call (that is, a function should never assume it to still be set after making a call). We could use the first byte of KiIntSystemCall for STD (set direction flag), then use the first byte of KiFastSystemCall for CLD (clear direction flag) followed by a jump to KiIntSystemCall+1, that way our hook procedure can use the direction flag to see which calls came from which function.

WOW32Reserved Hook

This is a lot simpler, either we can keep track of every thread and hook WOW32Reserved in each thread's environment block (i think this is what betabot does), or we simply overwrite X86SwitchTo64BitMode which is 7 bytes, writable from user mode, and pointed to by the WOW32Reserve field of every thread's environment block.

Dispatching

Most people who write hooks are used to redirecting one function to another; however, because both of these hooks are placed on common code: every single native function will call the hook procedure. Obviously we're going to need a way to tell NtCreateFile calls from NtCreateProcess and so on, or the process is just going to crash and burn.

If we dissemble the first 5 bytes of any native function it will always be "mov eax, XX", this value is the ordinal of the function within the System Service Dispatch Table (SSDT). Once the call enters the kernel, a function will use this number to identify which entry in the SSDT to call, then call it (meaning each function has a unique number). When our hook in called, the SSDT ordinal will still be in the eax register, all we need to do is gather the SSDT ordinals for all the functions we need (by disassembling the first 5 bytes), then we can compare the number in eax with the ordinal for the function we wish to intercept calls for: if it's equal we process the call, if not we just call the original code.

Comparing the function ordinal with the one we want to hook could be messy, especially if we're hooking multiple functions.

cmp eax, [ntcreatefile_ordinal]
je ntcreatefile_hook
cmp eax, [ntcreateprocess_ordinal]
je ntcreateprocess_hook
[...]
jmp original_code

This code is going to get very long and inefficient the more functions are hooked (because every kernel call is passing through this code, the system could slow down), but there's a better way.

We can build an array of DWORDs in memory (assuming we just want to hook NtCreateFile & NtCreateProcess, let's say the NtCreateFile ordinal is 0x02 and NtCreateProcess ordinal is 0x04), the array would look like this:
my_array+0x00 = (DWORD)NULL
my_array+0x04 = (DWORD)NULL
my_array+0x08 = (DWORD)ntcreatefile_hook_address
my_array+0x0C = (DWORD)NULL
my_array+0x10 = (DWORD)ntcreateprocess_hook_address
[...]

Then we could do something as simple as:
lea ecx, [my_array]
lea edx, [4*eax+ecx] ;edx will be &my_array[eax]
cmp [edx], 0
je original_code
call [edx] ;call the address pointed to by edx

This is pretty much what the kernel code for calling the SSDT function by its ordinal would do.

Calling Original Code

As with regular hooking, we just need to store the original code before we hook it. The only difference here is as well as pushing the parameters and calling the original code, the function's ordinal will need to be moved into the eax register.

Thursday, June 5, 2014

Hacking Soraya Panel - Free Bot? Free Bots!

Some security agencies have been raving about a revolutionary new bot that combines point-of-sales card grabbing (ram scraping) with form grabbing. The bot is actually not very interesting and pretty simple, but the panel is a great deal of fun (thanks to xylitol for getting me interested).


By default the panel shows the last 25 connected bots on the index page, not very interesting or helpful feature, but it opens up a whole world of possibilities. To understand what is possible, we need to take a look at the code responsible for adding new bots the the database.


From this code we can gather enough information to "impersonate" a bot. The HTTP method is POST, 'mode' must be '1', 'uid' must be a unique number, 'compname' must be a hex encoded string and so must 'osname'. The only difficult part is the fact the panel requires the bot to use a specific user-agent; however, we can find this by reversing a sample of the bot.

Here I've put together some code to add fake bots to the pane, thus add entries to the "last 25 connections".


Now, what if we decided to be a bit naughty? Let's try and submit HTML code as the bot's computer name. I'm sure this won't work because nobody is that bad at security, right? RIGHT??


Let's see the result...


Oh dear...

We'll, cool. We can submit HTML / JavaScript but what use can that be? Well we could mess with the botmaster by using javascript to redirect him to fbi.gov, replacing the entire page with rick roll, or modify the statistics. But could we hijack all his bot? Turns out the answer is yes!

A quick look at the command page allows us to throw together some code using "XMLHttpRequest()", when executed it will result in an update command being issued to the bot. All we need to do is provide our exe path in urlencoded format.


We could pay for hosting to host our script, only a small price to pay for a lot of free bots. Or, we could just use pastebin... All we need to do now is submit javascript to the panel which will run the code from pastebin.



Once we run it, when the botmaster logs in he will see this on the statistics page (minus the red block over the ip of course)...


The result of him viewing the page will be this....


So looks like revolutionary new malware "Soraya" is a little less than revolutionary when it comes to web security. Anyone with a sample of the bot binary can mess with the botmaster or potentially hijack the entire botnet.

Web Security - As easy as 1, 2, 3.