Saturday, 9 July 2016

Code for Sending ARP request with Raw Sockets in Python

Here is the code

Arp_request.py

#!/usr/bin/python

import struct
import socket

rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
rawSocket.bind(("eth0", socket.htons(0x0800)))

source_mac = "08:00:27:5e:26:c3"        # sender mac address
source_ip  = "192.168.56.101"           # sender ip address
dest_mac = "\xbb\xbb\xbb\xbb\xbb\xbb"   # target mac address
dest_ip  = "192.168.56.103"             # target ip address

# Ethernet Header
protocol = 0x0806                       # 0x0806 for ARP
eth_hdr = struct.pack("!6s6sH", dest_mac, source_mac, protocol)

# ARP header
htype = 1                               # Hardware_type ethernet
ptype = 0x0800                          # Protocol type TCP
hlen = 6                                # Hardware address Len
plen = 4                                # Protocol addr. len
operation = 1                           # 1=request/2=reply
src_ip = socket.inet_aton(source_ip)
dst_ip = socket.inet_aton(dest_ip)
arp_hdr = struct.pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen, operation, source_mac, src_ip, dest_mac, dst_ip)

packet = eth_hdr + arp_hdr
rawSocket.send(packet)

 Note : run the above code with root privilege. Thanks!!

Code for HTTP Sniffing with Raw Socket in Python

Here is the code :

HttpSniff.py

#!/usr/bin/python

import socket
import struct
import binascii

def mac_print(mac):
 mac_ad = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(mac[0]), ord(mac[1]), ord(mac[2]), ord(mac[3]), ord(mac[4]), ord(mac[5]))
 return mac_ad

RawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))

while True:
 packet = RawSocket.recvfrom(65565)
 
 # Check for the TCP packets
 IpHeader = packet[0][14:34]
 TcpHeader = packet[0][34:54]
 ip_hdr = struct.unpack("!B8s1s2s4s4s", IpHeader)
 tcp_hdr = struct.unpack("!HHLLB7s", TcpHeader)
 if binascii.hexlify(ip_hdr[2]) == "06" and (tcp_hdr[0] == 80 or tcp_hdr[1] == 80):
  # Check for the TCP protocol and port 80 [HTTP]
  
  # Extracting the Mac Address from EtherNet Header
  dst_mac = mac_print(packet[0][0:6])
  src_mac = mac_print(packet[0][6:12])

  # Extracting the IP address from IP header
  src_ip = socket.inet_ntoa(ip_hdr[4])
  dst_ip = socket.inet_ntoa(ip_hdr[5])

  # Extracting Source and Destination Port
  src_port = tcp_hdr[0]
  dst_port = tcp_hdr[1]

  # Calculating the length of data
  eth_length = 14
  iph_length = ip_hdr[0]
  iph_length = (iph_length & 0xF) * 4
  tcph_length = tcp_hdr[4]
  tcph_length = (tcph_length >> 4) * 4
  hdr_length = eth_length + iph_length + tcph_length
  data_length = len(packet[0]) - hdr_length
  Data = packet[0][hdr_length:]
  if Data == None:
   continue
  else:
   # print all The Data
   print "Source { IP : " + str(src_ip) + " | Mac : " + src_mac + " | Port : " + str(src_port) + " }"
   print "Dest.  { IP : " + str(dst_ip) + " | Mac : " + dst_mac + " | Port : " + str(dst_port) + " }"
   print "Data : " + Data
   print "---------------------------------------"

Run this code with root privilege otherwise it may not work, and also you need to generate some Http traffic by yourself.

dk0d@ubuntu:~$ sudo ./HttpSniff.py
Source { IP : 192.168.56.1 | Mac : 0a:00:27:00:00:00 | Port : 47708 }
Dest.  { IP : 192.168.56.101 | Mac : 08:00:27:5e:26:c3 | Port : 80 }
Data : 
---------------------------------------
Source { IP : 192.168.56.1 | Mac : 0a:00:27:00:00:00 | Port : 47708 }
Dest.  { IP : 192.168.56.101 | Mac : 08:00:27:5e:26:c3 | Port : 80 }
Data : 
---------------------------------------
Source { IP : 192.168.56.1 | Mac : 0a:00:27:00:00:00 | Port : 47708 }
Dest.  { IP : 192.168.56.101 | Mac : 08:00:27:5e:26:c3 | Port : 80 }
Data : GET / HTTP/1.1
Host: 192.168.56.101
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Mon, 27 Jun 2016 17:03:35 GMT
If-None-Match: "2cf6-536458034b832-gzip"
Cache-Control: max-age=0

thats it.

Saturday, 25 June 2016

Simple Python Web Server with CGI

Here is the code for python CGI web server :
 

 CgiServer.py

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() # This line enables CGI error reporting

ServerHandler = CGIHTTPServer.CGIHTTPRequestHandler
ServerHandler.cgi_directories = ["/"]
HttpServer = BaseHTTPServer.HTTPServer(("", 8000), ServerHandler)
HttpServer.serve_forever()

and here's the code for a sample page:

TestPage.py

#!/usr/bin/env python

print """Content-type:text/html\r\n\r\n
<html>
<head>
 <title>Test Page</title>
</head>
<body>
 <center><h1>Hello world. This is The Test Page</h1></center>
</body>
</html>"""

then set the executable permissions for both file and run the Cgi_Server.py

$ chmod +x CgiServer.py
$ chmod +x TestPage.py
$ ./CgiServer.py

now open your web browser and type the following url

http://localhost:8000/TestPage.py


Voila!! thats it.

for more details visit : https://wiki.python.org/moin/CgiScripts

Wednesday, 22 June 2016

Simple Echo Server in python using Sockets

A simple echo server which just echo the client supplied data or string

server.py

#!/usr/bin/python

import socket

tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpSocket.bind(("0.0.0.0", 8000))
tcpSocket.listen(2)


while 1:
 print "Waiting for a Client ... "
 (client, (ip, sock)) = tcpSocket.accept()

 print "Received connection from : ", ip
 client.send("Press Return or Ctrl+C to close..\n")
 print "Starting ECHO output ... "

 data = 'dummy'

 while len(data):
  data = client.recv(2048)
  if len(data)==1:
   print "Closing connection with ", ip
   client.close()
   print "Connection closed successfully.!!"
   print "---------------------------------"
   break
  if len(data)==0:
   print "Some Error in connection with ", ip
   print "Connection closed with ", ip
   print "---------------------------------"
   break
  print "Client sent:", data
  client.send(data)

tcpSocket.close()

But the above server code process only a single client at a time.


Now with the use of threading we can solve this problem. Here is the second echo server which handle multiple connection with threads

threaded_server.py

#!/usr/bin/python

import thread
import socket

tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpSocket.bind(("0.0.0.0", 8000))
tcpSocket.listen(2)

def conn_handler(client, ip, thread_id):
	print "[T%d]Received connection from : %r" % (thread_id, ip)
	client.send("Press Return or Ctrl+C to close..\n")
	print "[T%d]Starting echo output..." % thread_id
	data = 'dummy'
	while len(data):
		data = client.recv(2048)
		if len(data)==1:
			print "[T%d]Closing connection with %r" % (thread_id, ip)
			client.close()
			print "[T%d]Connection closed successfully.!!" % thread_id
			print "------------------------------------"
			break
		if len(data)==0:
			print "[T%d]Some Error in connection with %r" % (thread_id, ip)
			print "[T%d]Connection closed with %r" % (thread_id, ip)
			print "------------------------------------"
			break
		print "[T%d]Client sent: %s" % (thread_id, data)
		client.send(data)


thread_id = 0
while 1:
	thread_id = thread_id + 1
	print "Waiting for Client ...\n"
	(client, (ip, sock)) = tcpSocket.accept()

	try:
		thread.start_new_thread(conn_handler, (client, ip, thread_id, ))
	except:
		print "Error: Unable to start thread [T%d]\n" % thread_id

tcpSocket.close()


Multi-Process Echo Server 

#!/usr/bin/python

from multiprocessing import Process
import socket
import os
import signal

tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpSocket.bind(("0.0.0.0", 8000))
tcpSocket.listen(2)

def conn_handler(client, ip, Child_id):
	print "[C%d]Received connection from : %r" % (Child_id, ip)
	print "[C%d]Starting echo output... " % Child_id
	data = 'dummy'
	while len(data):
		data = client.recv(2048)
		if len(data)==0:
			print "[C%d]Closing connection with %r" % (Child_id, ip)
			client.close()
			print "[C%d]Connection closed with %r" % (Child_id, ip)
			os.kill(os.getpid(), signal.SIGTERM)
		print "[C%d]Client sent: %s" % (Child_id, data)
		client.send(data)

def main():
	Child_id = 0
	while 1:
		Child_id = Child_id + 1
		print "Waiting for Client  ...\n"
		(client, (ip, sock)) = tcpSocket.accept()

		try:
			Process(target=conn_handler, args=(client, ip, Child_id)).start()
		except:
			print "Error: Uable to start Child Process.!![C%d]" % Child_id
	
	tcpSocket.close()


if __name__ == "__main__":
	main()

you can try it out with nc, to close the connection just press 'Ctrl + C' or use the below client.py code to communicate with multiprocess_server.py

client.py

#!/usr/bin/python
import socket
import sys
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.connect((sys.argv[1], int(sys.argv[2])))
print "Input some string : ['quit' to exit]"
data = "dummy"
while 1:
	data = raw_input("|> ")
	if data=="quit":
		tcpSocket.close()
		break
	tcpSocket.sendall(data)
	result = tcpSocket.recv(2048)
	print result  

Tuesday, 10 May 2016

Some great stuff for beginners to start with Information Security


How to be an InfoSec Geek : https://www.youtube.com/watch?v=OMS-NWKB2RI



Hacker Bootcamp : https://pentesterlab.com/bootcamp

Free Resources for Programming Languages

Web Technologies :
 http://www.w3schools.com/
 http://www.tutorialspoint.com/web_development_tutorials.htm
php videos : https://www.youtube.com/playlist?list=PL_c9BZzLwBRK-pdEkJHvsqd5yBDxvggbs

C & C++ :
http://gribblelab.org/CBootcamp/index.html
http://www.tutorialspoint.com/cprogramming/index.htm
http://www.tutorialspoint.com/cplusplus/index.htm
http://www.cplusplus.com/doc/tutorial/
http://www.java2s.com/Tutorials/C/C_Tutorial/index.htm
http://www.java2s.com/Tutorials/C/Cpp_Tutorial/index.htm

Python :
http://www.tutorialspoint.com/python/index.htm
http://learnpythonthehardway.org/book/

Shell Scripting :
https://bash.cyberciti.biz/guide/Main_Page
https://linuxconfig.org/bash-scripting-tutorial
http://www.tutorialspoint.com/unix/index.htm
http://linuxcommand.org/tlcl.php  [Book:The Linux Command line by William shotts]

Assembly Language :
http://www.securitytube.net/groups?operation=view&groupId=6 {securitytube video}
http://www.securitytube.net/groups?operation=view&groupId=5 {securitytube video}
http://www.tutorialspoint.com/assembly_programming/index.htm
http://www.plantation-productions.com/Webster/www.artofasm.com/Windows/index.html [HLA Book]
https://www.exploit-db.com/docs/16967.pdf {15 first dates with Assembly}


Sites To Learn Exploitation Techniques :

http://www.myne-us.com/2010/08/from-0x90-to-0x4c454554-journey-into.html {Links}
http://www.securitytube.net/groups?operation=view&groupId=4 {buffer Overflow videos}
http://www.securitytube.net/groups?operation=view&groupId=3 {format string videos}
http://www.securitytube.net/groups?operation=view&groupId=7 {videos}
http://x9090.blogspot.in/2010/03/tutorial-exploit-writting-tutorial-from.html
https://www.corelan.be/index.php/category/security/exploit-writing-tutorials/
http://www.thegreycorner.com/
http://fuzzysecurity.com/exploits.html
http://www.securitysift.com/windows-exploit-development-part-1-basics/


Web Application Security :

http://www.securitytube.net/user/Audi {Sql Injection Videos}
https://www.google.com/about/appsecurity/learning/xss/
https://www.steve.org.uk/Security/XSS/Tutorial/
https://www.owasp.org/index.php/Category:Attack
https://www.youtube.com/playlist?list=PL1A2CSdiySGIRec2pvDMkYNi3iRO89Zot {XSS video tutorials}

Metasploit Tutorials :

http://www.securitytube.net/groups?operation=view&groupId=10 {videos}
https://www.offensive-security.com/metasploit-unleashed/


Lab Setup :

Download and install virtualization software. {vmware or virtualbox}
Vulnerable Images Lists :
For web_App_Testing :
https://sourceforge.net/projects/owaspbwa/
https://sourceforge.net/projects/metasploitable/files/Metasploitable2/
https://pentesterlab.com/exercises/

Some posts about lab setup :
http://securityxploded.com/setup-your-pentest-hacker-network.php
http://resources.infosecinstitute.com/hacking-lab/ 


For Exploit Testing Download the LiveCD which provided with the book Hacking: The Art of Exploitation. Its an old live image and good for exploit testing.
https://www.nostarch.com/hackingCD.htm

And also download and install redhat 9 from here

http://redhat.lsu.edu/dist/9/iso/shrike-i386-disc1.iso
http://redhat.lsu.edu/dist/9/iso/shrike-i386-disc2.iso
http://redhat.lsu.edu/dist/9/iso/shrike-i386-disc3.iso

installation Process : https://www.youtube.com/watch?v=QKtzfwyspU0

and for windows test machine just download windows xp sp 2 and 3 both and install it.
for download links just search on google.


and Practice ..Practice ..Practice..!!!