Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit download
Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit download
https://ebookmeta.com/product/python-penetration-testing-
essentials-techniques-for-ethical-hacking-with-python-2nd-
edition-mohit/
https://ebookmeta.com/product/beginning-ethical-hacking-with-
python-1st-edition-sanjib-sinha/
https://ebookmeta.com/product/learning-kali-linux-security-
testing-penetration-testing-and-ethical-hacking-1st-edition-ric-
messier/
https://ebookmeta.com/product/learning-kali-linux-security-
testing-penetration-testing-and-ethical-hacking-2nd-edition-
first-early-release-ric-messier/
https://ebookmeta.com/product/mayor-of-elf-town-4-1st-edition-
dante-king-2/
Theatre Translation: A Practice as Research Model 1st
Edition Angela Tiziana Tarantini
https://ebookmeta.com/product/theatre-translation-a-practice-as-
research-model-1st-edition-angela-tiziana-tarantini/
https://ebookmeta.com/product/essential-revision-notes-for-frcs-
urol-book-1-1st-edition-jack-donati-bourne/
https://ebookmeta.com/product/eyewitness-to-chaos-personal-
accounts-of-the-intervention-in-haiti-1994-1st-edition-walter-e-
kretchik/
https://ebookmeta.com/product/the-blobfish-book-jessica-olien/
Spoon Feeding Basic must Know Physics for Boys and Men
for IIT JEE Olympiad kind of exams by Professor
Subhashish Chattopadhyay 1st Edition Professor
Subhashish Chattopadhyay
https://ebookmeta.com/product/spoon-feeding-basic-must-know-
physics-for-boys-and-men-for-iit-jee-olympiad-kind-of-exams-by-
professor-subhashish-chattopadhyay-1st-edition-professor-
College Reunions and Clues Tiffany Black Travel Cozy
Mystery 4 A.R. Winters Et El
https://ebookmeta.com/product/college-reunions-and-clues-tiffany-
black-travel-cozy-mystery-4-a-r-winters-et-el/
||||||||||||||||||||
||||||||||||||||||||
||||||||||||||||||||
5FDIOJRVFTGPSFUIJDBMIBDLJOHXJUI1ZUIPO
Mohit
BIRMINGHAM - MUMBAI
||||||||||||||||||||
||||||||||||||||||||
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
ISBN 978-1-78913-896-2
XXXQBDLUQVCDPN
||||||||||||||||||||
||||||||||||||||||||
NBQUJP
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.
At XXX1BDLU1VCDPN, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
||||||||||||||||||||
||||||||||||||||||||
Contributors
||||||||||||||||||||
||||||||||||||||||||
My special thanks to my wife, Shalini Jaiswal, for her unconditional support, and my
friends Ranjan, Ritesh, Mickey, Vivek, Hari, Sujay, Shankar, and Santosh for their care
and support all the time.
Rejah Rehim is currently the Director and Chief Information Security Officer (CISO) of
Appfabs. Previously holding the title of Security Architect at FAYA India, he is a long-time
preacher of open source and steady contributor to the Mozilla Foundation. He has
successfully created the world's first security testing browser bundle, PenQ, an open
source Linux-based penetration testing browser bundle preconfigured with tools
for security testing. He is also an active member of OWASP and the chapter
leader of OWASP Kerala. Additionally, Rejah also holds the title of commander at
Cyberdome, an initiative of the Kerala Police Department.
||||||||||||||||||||
||||||||||||||||||||
Table of Contents
Preface 1
Chapter 1: Python with Penetration Testing and Networking 6
Introducing the scope of pentesting 7
The need for pentesting 7
Components to be tested 8
Qualities of a good pentester 8
Defining the scope of pentesting 9
Approaches to pentesting 9
Introducing Python scripting 10
Understanding the tests and tools you'll need 11
Learning the common testing platforms with Python 11
Network sockets 11
Server socket methods 12
Client socket methods 13
General socket methods 13
Moving on to the practical 14
Socket exceptions 22
Useful socket methods 23
Summary 29
Chapter 2: Scanning Pentesting 30
How to check live systems in a network and the concept of a live
system 31
Ping sweep 31
The TCP scan concept and its implementation using a Python script 35
How to create an efficient IP scanner in Windows 37
How to create an efficient IP scanner in Linux 44
The concept of the Linux-based IP scanner 44
nmap with Python 47
What are the services running on the target machine? 51
The concept of a port scanner 51
How to create an efficient port scanner 54
Summary 59
Chapter 3: Sniffing and Penetration Testing 60
Introducing a network sniffer 61
Passive sniffing 61
Active sniffing 61
Implementing a network sniffer using Python 61
||||||||||||||||||||
||||||||||||||||||||
Table of Contents
Format characters 63
Learning about packet crafting 73
Introducing ARP spoofing and implementing it using Python 74
The ARP request 74
The ARP reply 75
The ARP cache 75
Testing the security system using custom packet crafting 78
A half-open scan 79
The FIN scan 82
ACK flag scanning 83
Summary 85
Chapter 4: Network Attacks and Prevention 86
Technical requirements 86
DHCP starvation attack 87
The MAC flooding attack 93
How the switch uses the CAM tables 93
The MAC flood logic 94
Gateway disassociation by RAW socket 95
Torrent detection 96
Running the program in hidden mode 104
Summary 106
Chapter 5: Wireless Pentesting 107
Introduction to 802.11 frames 108
Wireless SSID finding and wireless traffic analysis with Python 110
Detecting clients of an AP 120
Wireless hidden SSID scanner 122
Wireless attacks 125
The deauthentication (deauth) attack 125
Detecting the deauth attack 128
Summary 131
Chapter 6: Honeypot – Building Traps for Attackers 132
Technical requirements 132
Fake ARP reply 133
Fake ping reply 135
Fake port-scanning reply 142
Fake OS-signature reply to nmap 145
Fake web server reply 146
Summary 149
Chapter 7: Foot Printing a Web Server and a Web Application 150
The concept of foot printing a web server 150
Introducing information gathering 151
[ ii ]
||||||||||||||||||||
||||||||||||||||||||
Table of Contents
[ iii ]
||||||||||||||||||||
||||||||||||||||||||
Preface
This book is a practical guide that shows you the advantages of using Python for
pentesting, with the help of detailed code examples. This book starts by exploring the
basics of networking with Python and then proceeds to network and wireless pentesting,
including information gathering and attacking. You will learn how to build honeypot traps.
Later on, we delve into hacking the application layer, where we start by gathering
information from a website, and then eventually move on to concepts related to website
hacking, such as parameter tampering, DDOS, XSS, and SQL injection.
$IBQUFS, Sniffing and Penetration Testing, teaches how to perform active sniffing and how
to create a Transport layer sniffer. You will learn special kinds of scanning.
$IBQUFS, Network Attacks and Prevention, outlines different types of network attacks, such
as DHCP starvation and switch mac flooding. You will learn how to detect a torrent on the
client side.
||||||||||||||||||||
||||||||||||||||||||
Preface
$IBQUFS, Wireless Pentesting, goes through wireless frames and explains how to obtain
information such as SSID, BSSID, and the channel number from a wireless frame using a
Python script. In this type of attack, you will learn how to perform pentesting attacks on the
AP.
$IBQUFS, Honeypot ` Building Traps for Attackers, focuses on how to build a trap for
attackers. You will learn how to bulid code from TCP layer 2 to TCP layer 4.
$IBQUFS, Foot Printing a Web Server and a Web Application, dives into the importance of a
web server signature, email gathering, and why knowing the server signature is the first
step in hacking.
$IBQUFS, Client-Side and DDoS Attacks, explores client-side validation and how to bypass
client-side validation. This chapter covers the implantation of four types of DDoS attacks.
$IBQUFS, Pentesting SQL and XSS, discusses two major web attacks: SQL injection and
XSS. In SQL injection, you will learn how to find the admin login page using a Python
script.
In order to perform experiments or run the codes reader can use the virtual machine
(Vmware, virtual box). For Wireless pen-testing readers can use a wireless card TP-Link TL-
WN722N. Becuase TL-WN722N wireless card supports the Kali Linux in VMware.
[2]
||||||||||||||||||||
||||||||||||||||||||
Preface
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
The code bundle for the book is also hosted on GitHub at IUUQTHJUIVCDPN
1BDLU1VCMJTIJOH1ZUIPO1FOFUSBUJPO5FTUJOH&TTFOUJBMT4FDPOE&EJUJPO. In case
there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available
at IUUQTHJUIVCDPN1BDLU1VCMJTIJOH. Check them out!
Code in Action
Visit the following link to check out videos of the code being run:
IUUQTHPPHMT#)7/%
[3]
||||||||||||||||||||
||||||||||||||||||||
Preface
Conventions used
There are a number of text conventions used throughout this book.
$PEF*O5FYU: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Mount the downloaded 8FC4UPSN ENH disk image file as another disk in
your system."
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,TPDLFUOUPIT Y
J
Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"Select System info from the Administration panel."
[4]
||||||||||||||||||||
||||||||||||||||||||
Preface
Get in touch
Feedback from our readers is always welcome.
General feedback: Email GFFECBDL!QBDLUQVCDPN and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at RVFTUJPOT!QBDLUQVCDPN.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit XXXQBDLUQVCDPNTVCNJUFSSBUB, selecting your book,
clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at DPQZSJHIU!QBDLUQVCDPN with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
BVUIPSTQBDLUQVCDPN.
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!
[5]
||||||||||||||||||||
||||||||||||||||||||
1
Python with Penetration Testing
and Networking
Penetration (pen) tester and hacker are similar terms. The difference is that penetration
testers work for an organization to prevent hacking attempts, while hackers hack for any
purpose such as fame, selling vulnerability for money, or to exploit the vulnerability of
personal enmity.
Lots of well-trained hackers have got jobs in the information security field by hacking into a
system and then informing the victim of their security bug(s) so that they might be fixed.
A hacker is called a penetration tester when they work for an organization or company to
secure its system. A pentester performs hacking attempts to break into the network after
getting legal approval from the client and then presents a report of their findings. To
become an expert in pentesting, a person should have a deep knowledge of the concepts of
their technology. In this chapter, we will cover the following topics:
||||||||||||||||||||
||||||||||||||||||||
Consider the example of a well-reputed e-commerce company that makes money from an
online business. A hacker or a group of black hat hackers find a vulnerability in the
company's website and hack it. The amount of loss the company will have to bear will be
tremendous.
[7]
||||||||||||||||||||
||||||||||||||||||||
Components to be tested
An organization should conduct a risk assessment operation before pentesting; this will
help identify the main threats such as misconfiguration or vulnerability in:
Choose a suitable set of tests and tools that balance cost and benefits
Follow suitable procedures with proper planning and documentation
Establish the scope for each penetration test, such as objectives, limitations, and
the justification of procedures
Be ready to show how to exploit the vulnerabilities that they find
State the potential risks and findings clearly in the final report and provide
methods to mitigate the risk(s) if possible
Keep themselves updated at all times because technology is advancing rapidly
A pentester tests the network using manual techniques or the relevant tools. There are lots
of tools available on the market. Some of them are open source and some of them are highly
expensive. With the help of programming, a programmer can make his/her own tools. By
creating your own tools, you can clear your concepts and also perform more R&D. If you
are interested in pentesting and want to make your own tools, then the Python
programming language is the best, since extensive and freely available pentesting packages
are available in Python, in addition to its ease of programming. This simplicity, along with
the third-party libraries such as scapy and mechanize, reduces the code size. In Python, to
make a program, you don't need to define big classes such as Java. It's more productive to
write code in Python than in C, and high-level libraries are easily available for virtually any
imaginable task.
If you know some programming in Python and are interested in pentesting, this book is
perfect for you.
[8]
||||||||||||||||||||
||||||||||||||||||||
You should develop the scope of the project by consulting with the client. For
example, if Bob (the client) wants to test the entire network infrastructure of the
organization, then pentester Alice would define the scope of pentesting by taking
this network into account. Alice will consult Bob on whether any sensitive or
restricted areas should be included or not.
You should take into account time, people, and money.
You should profile the test boundaries on the basis of an agreement signed by the
pentester and the client.
Changes in business practice might affect the scope. For example, the addition of
a subnet, new system component installations, the addition or modification of a
web server, and so on, might change the scope of pentesting.
A non-destructive test: This test is limited to finding and carrying out the tests
without any potential risks. It performs the following actions:
Scans and identifies the remote system for potential vulnerabilities
Investigates and verifies the findings
Maps the vulnerabilities with proper exploits
Exploits the remote system with proper care to avoid disruption
Provides a proof of concept
Does not attempt a Denial-of-Service (DoS) attack
A destructive test: This test can produce risks. It performs the following actions:
Attempts a DoS attack and a buffer overflow attack, which have
the potential to bring down the system
Approaches to pentesting
There are three types of approaches to pentesting:
[9]
||||||||||||||||||||
||||||||||||||||||||
In this book, all experiments and demonstrations have been done in Python version 2.7.8. If
you use Linux OSes such as Kali or BackTrack, then there will be no issue, because many
programs, such as wireless sniffing, do not work on the Windows platform. Kali Linux also
uses the 2.7 version. If you love to work on Red Hat or CentOS, then this version is suitable
for you.
Most hackers choose this profession because they don't want to do programming. They
want to use tools. However, without programming, a hacker cannot enhance his/her skills.
Each and every time, they have to search for the tools over the internet. Believe me, after
seeing its simplicity, you will love this language.
[ 10 ]
||||||||||||||||||||
||||||||||||||||||||
A hacker always loves to work on a Linux system. Since it is a free and open source, Kali
Linux marks the rebirth of BackTrack and is like an arsenal of hacking tools. Kali Linux
NetHunter is the first open-source Android penetration testing platform for Nexus devices.
However, some tools work on both Linux and Windows, but on Windows, you have to
install those tools. I expect you to have knowledge of Linux. Now, it's time to work with
networking on Python.
Network sockets
A network socket address contains an IP address and port number. In a very simple way, a
socket is a way to talk to other computers. By means of a socket, a process can communicate
with another process over the network.
[ 11 ]
||||||||||||||||||||
||||||||||||||||||||
In order to create a socket, use the TPDLFUTPDLFU that is available in the socket
module. The general syntax of a socket function is as follows:
TTPDLFUTPDLFU TPDLFU@GBNJMZTPDLFU@UZQFQSPUPDPM
"'@*/&5 is the address family for IPv4. 1'@1"$,&5 operates at the device driver layer. The
pcap library for Linux uses 1'@1"$,&5. You will see more details on 1'@1"$,&5 in
$IBQUFS, Sniffing and Penetration Testing. These arguments represent the address families
and the protocol of the transport layer:
4PDLFU@UZQFTPDLFU40$,@%(3".TPDLFU40$,@3"8TPDLFU40$,@453&".
The TPDLFU40$,@%(3". argument depicts that UDP is unreliable and connectionless, and
TPDLFU40$,@453&". depicts that TCP is reliable and a two-way, connection-based
service. We will discuss TPDLFU40$,@3"8 in $IBQUFS, Sniffing and Penetration Testing:
QSPUPDPM
Generally, we leave this argument; it takes 0 if it's not specified. We will see the use of this
argument in $IBQUFS, Sniffing and Penetration Testing.
[ 12 ]
||||||||||||||||||||
||||||||||||||||||||
TPDLFUBDDFQU : The use of this method is to accept the connection from the
client. Before using this method, the TPDLFUCJOE BEESFTT and
TPDLFUMJTUFO R methods must be used. The TPDLFUBDDFQU method
returns two values, DMJFOU@TPDLFU and BEESFTT, where DMJFOU@TPDLFU is a
new socket object used to send and receive data over the connection, and
BEESFTT is the address of the client. You will see examples of this later.
TPDLFUDPOOFDU BEESFTT : This method connects the client to the server. The
BEESFTT argument is the address of the server.
TPDLFUSFDW CVGTJ[F : This method receives a TCP message from the socket.
The CVGTJ[F argument defines the maximum data it can receive at any one time.
TPDLFUSFDWGSPN CVGTJ[F : This method receives data from the socket. The
method returns a pair of values, the first value gives the received data, and the
second value gives the address of the socket sending the data.
TPDLFUSFDW@JOUP CVGGFS : This method receives data less than or equal to
CVGGFS. The CVGGFS parameter is created by the CZUFBSSBZ method. We will
discuss this in an example later.
TPDLFUSFDWGSPN@JOUP CVGGFS : This method obtains data from the socket
and writes it into the buffer. The return value is a pair (nbytes, address), where
nbytes is the number of bytes received, and the address is the address of the
socket sending the data.
[ 13 ]
||||||||||||||||||||
||||||||||||||||||||
TPDLFUTFOE CZUFT : This method is used to send data to the socket. Before
sending the data, ensure that the socket is connected to a remote machine. It
returns the number of bytes sent.
TPDLFUTFOEUP EBUBBEESFTT : This method is used to send data to the
socket. Generally, we use this method in UDP. UDP is a connectionless protocol;
therefore, the socket should not be connected to a remote machine, and the
address argument specifies the address of the remote machine. The returned
value tells us the number of bytes sent.
TPDLFUTFOEBMM EBUB : As the name implies, this method sends all data to the
socket. Before sending the data, ensure that the socket is connected to a remote
machine. This method ceaselessly transfers data until an error is seen. If an error
is seen, an exception will rise, and TPDLFUDMPTF will close the socket.
The preceding code is very simple; it is minimal code on the server side.
[ 14 ]
||||||||||||||||||||
||||||||||||||||||||
First, import the socket module and define the host and port number, is the
server's IP address. 4PDLFU"'@*/&5 defines the IPv4 protocol's family.
4PDLFU40$,@453&". defines the TCP connection. The TCJOE IPTUQPSU statement
takes only one argument. It binds the socket to the host and port number. The
TMJTUFO statement listens to the connection and waits for the client. The DPOOBEES
TBDDFQU statement returns two values: DPOO and BEES. The DPOO socket is the client
socket, as we discussed earlier. The DPOOTFOE function sends the message to the client.
Finally, DPOODMPTF closes the socket. From the following examples and screenshot, you
will understand DPOO better.
Now, the server is in the listening mode and is waiting for the client.
In the preceding code, there are two new methods, TDPOOFDU IPTUQPSU , which
connects the client to the server, and TSFDW , which receives the strings sent by the
server.
The output of DMJFOUQZ and the response of the server is shown in the following
screenshot:
[ 15 ]
||||||||||||||||||||
||||||||||||||||||||
The preceding screenshot of the output shows that the server accepted the connection from
. Don't get confused by seeing port ; it is the random port of the client.
When the server sends a message to the client, it uses the DPOO socket, as mentioned earlier,
and this DPOO socket contains the client IP address and port number.
The following diagram shows how the client accepts a connection from the server. The
server is in listening mode, and the client connects to the server. When you run the server
and client program again, the random port gets changed. For the client, the server
port, 12345, is the destination port, and for the server, the client random port, 1789, is the
destination port:
6%2EQOOWPKECVKQP
You can extend the functionality of the server using the XIJMF loop, as shown in the
following program. Run the TFSWFSQZ program:
JNQPSUTPDLFU
[ 16 ]
||||||||||||||||||||
||||||||||||||||||||
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TCJOE IPTUQPSU
TMJTUFO
XIJMF5SVF
DPOOBEESTBDDFQU
QSJOUBEES/PX$POOFDUFE
DPOOTFOE 5IBOLZPVGPSDPOOFDUJOH
DPOODMPTF
The preceding code is the same as the previous one, except the infinite XIJMF loop has been
added.
Run the TFSWFSQZ program, and from the client, run DMJFOUQZ.
One server can give service to many clients. The XIJMF loop keeps the server program alive
and does not allow the code to end. You can set a connection limit to the XIJMF loop; for
example, set XIJMFJ and increment J with each connection.
[ 17 ]
||||||||||||||||||||
||||||||||||||||||||
Before proceeding to the next example, the concept of CZUFBSSBZ should be understood.
The CZUFBSSBZ array is a mutable sequence of unsigned integers in the range of 0 to 255.
You can delete, insert, or replace arbitrary values or slices. The CZUFBSSBZ array's objects
can be created by calling the built-in CZUFBSSBZ array.
The next example is of TSFDW@JOUP CVGG . In this example, we will use CZUFBSSBZ to
create a buffer to store data.
[ 18 ]
||||||||||||||||||||
||||||||||||||||||||
TCJOE IPTUQPSU
TMJTUFO
DPOOBEESTBDDFQU
QSJOUDPOOFDUFECZBEES
DPOOTFOE 5IBOLT
DPOODMPTF
The preceding program is the same as the previous one. In this program, the server sends
5IBOLT; six characters.
[ 19 ]
||||||||||||||||||||
||||||||||||||||||||
Our client program successfully received 6 bytes of the string, 5IBOLT. You must have an
idea of CZUFBSSBZ by now. I hope you will remember it.
Here, I used the UDP socket and the TTFOEUP method, as you can see in the definition
of TPDLFUTFOEUP . You will know that UDP is a connectionless protocol, so there is no
need to establish a connection here.
[ 20 ]
||||||||||||||||||||
||||||||||||||||||||
The following screenshot shows the output of VEQQZ (the UDP server) and VEQQZ (the
UDP client):
Let's assume that a server is running and that there is no client start connection, and that
the server will have been listening. So, to avoid this situation, use
TPDLFUTFUUJNFPVU WBMVF .
Generally, we give a value as an integer; if I give as the value, this would mean wait for
five seconds. If the operation doesn't complete within five seconds, then a timeout
exception would be raised. You can also provide a non-negative float value.
I added one extra line, that is, TTFUUJNFPVU . The program waits for five seconds; only
after that will it give us an error message. Run VEQUJNFQZ.
[ 21 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
The program shows an error; however, it does not look good if it gives an error message.
The program should handle the exceptions.
Socket exceptions
In order to handle exceptions, we'll use the try and except blocks. The following example
will tell you how to handle the exceptions. Run VEQUJNFQZ:
JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
USZ
TCJOE IPTUQPSU
TTFUUJNFPVU
EBUBBEESTSFDWGSPN
QSJOUSFDFWJFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF
FYDFQUTPDLFUUJNFPVU
QSJOU$MJFOUOPUDPOOFDUFE
TDMPTF
[ 22 ]
||||||||||||||||||||
||||||||||||||||||||
In the try block, I put my code, and from the except block, a customized message is printed
if any exception occurs.
Different types of exceptions are defined in Python's socket library for different errors.
These exceptions are described here:
You can download the example code files from your account at IUUQ
XXXQBDLUQVCDPN for all of the Packt Publishing books you have
purchased. If you purchased this book elsewhere, you can visit IUUQ
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly
to you.
[ 23 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
I know you are thinking about the OTMPPLVQ command. Later, you will see more magic.
It returns many IP addresses for a single domain name. This means that one domain such
as UIBQBSFEV or HPPHMFDPN runs on multiple IPs.
To glean the current machine's IP address by using the socket module, you can use the
following trick using HFUIPTUCZOBNF HFUIPTUOBNF :
>>> socket.gethostbyname(socket.gethostname())'192.168.10.1'>>>
You know that our computer has many interfaces. If you want to know the IP address of all
of the interfaces, use the extended interface:.
>>> socket.gethostbyname_ex(socket.gethostname())('eXtreme', [],
['10.0.0.10', '192.168.10.1', '192.168.0.1'])>>>
It returns one tuple containing three elements, the first is the machine name, the second is a
list of aliases for the hostname (empty, in this case,) and the third is the list of the IP
addresses of interfaces.
[ 24 ]
||||||||||||||||||||
||||||||||||||||||||
TPDLFUHFUGREO <OBNF> : This is used to find the fully qualified domain name
if it's available. The fully qualified domain name consists of a host and domain
name; for example, CFUB might be the hostname, and FYBNQMFDPN might be the
domain name. The fully qualified domain name (FQDN) becomes
CFUBFYBNQMFDPN:
>>> socket.getfqdn('facebook.com')'edge-star-shv-12-
frc3.facebook.com'
It shows an error in the last query because reverse DNS lookup is not present.
[ 25 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
GPSQPSUJOQPSUMJTU
TPDLTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
SFTVMUTPDLDPOOFDU@FY SNJQQPSU
QSJOUQPSUSFTVMU
TPDLDMPTF
The preceding program output shows that ports , ,, and are open. This is a
rudimentary port scanner. The program is using the IP address ; this is a
loopback address, so it is impossible to have any connectivity issues. However, when you
have issues, perform this on another device with a large port list. This time, you will have
to use TPDLFUTFUUJNFPVU WBMVF :
TPDLFUHFUBEESJOGP IPTUQPSU<GBNJMZ<TPDLUZQF<QSPUP<GMBHT>>>>
[ 26 ]
||||||||||||||||||||
||||||||||||||||||||
This socket method converts the host and port arguments into a sequence of five tuples.
Output represents the family, represents the socket type, represents the protocol,
represents the canonical name, and represents the socket
address. However, this number is difficult to comprehend. Open the directory of the socket.
QSPUP@GBNHFU@QSPUOVNCFS "'@
UZQFTHFU@QSPUOVNCFS 40$,@
QSPUPDPMTHFU@QSPUOVNCFS *113050@
GBNJMZTPDLUZQFQSPUPDBOPOOBNFTPDLBEESSFT
[ 27 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
The upper part makes a dictionary using the "'@, 40$,@, and *113050@ prefixes that map
the protocol number to their names. This dictionary is formed by the list comprehension
technique.
The upper part of the code might be confusing sometimes, but we can execute the code
separately as follows:
>>> dict(( getattr(socket,n),n) for n in dir(socket) if
n.startswith('AF_'))
{0: 'AF_UNSPEC', 2: 'AF_INET', 6: 'AF_IPX', 11: 'AF_SNA', 12:
'AF_DECnet', 16: 'AF_APPLETALK', 23: 'AF_INET6', 26: 'AF_IRDA'}
Now, this is easy to understand. This code is usually used to get the protocol number:
GPSSFTJOTPDLFUHFUBEESJOGP XXXUIBQBSFEV IUUQ
The preceding line of code returns the five values, as discussed in the definition. These
values are then matched with their corresponding dictionary.
[ 28 ]
||||||||||||||||||||
||||||||||||||||||||
Summary
From reading this chapter, you have got an understanding of networking in Python. The
aim of this chapter was to complete the prerequisites of the upcoming chapters. From the
start, you have learned the need for pentesting. Pentesting is conducted to identify threats
and vulnerabilities in an organization. What should be tested? This is specified in the
agreement; don't try to test anything that is not mentioned in the agreement. The agreement
is your get out of jail free card. A pentester should have knowledge of the latest technology,
and you should have some knowledge of Python before you start reading this book. In
order to run Python scripts, you should have a lab setup, a network of computers to test a
live system, and dummy websites running on the Apache server.
This chapter also discussed the socket and its methods. The server socket method defines
how to make a simple server. The server binds its own address and port to listen to the
connections. A client that knows the server address and port number connects to the server
to get a service. Some socket methods such as TPDLFUSFDW CVGTJ[F ,
TPDLFUSFDWGSPN CVGTJ[F , TPDLFUSFDW@JOUP CVGGFS , TPDLFUTFOE CZUFT ,
and so on are useful for the server as well as the client. You learned how to handle different
types of exceptions. In the Useful socket methods section, you got an idea of how to get the IP
address and hostname of a machine, how to glean the IP address from the domain name,
and vice versa.
In the next chapter, we will be looking at scanning pentesting, which includes IP address
scanning to detect live hosts. To carry out IP scanning, ping sweep and TCP scanning are
used. You will learn how to detect services running on a remote host using a port scanner.
[ 29 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
2
Scanning Pentesting
Network scanning refers to a set of procedures that investigate a live host, the type of host,
open ports, and the type of services running on the host. Network scanning is a part of
intelligence gathering by virtue of which an attacker can create a profile of the target
organization.
You should have a basic knowledge of the TCP/IP layer communication. Before proceeding
further, the concept of the protocol data unit (PDU) should be clear.
PDU is a unit of data specified in the protocol. It is the generic term for data at each layer:
||||||||||||||||||||
||||||||||||||||||||
+%/2TGSWGUVCPFTGRN[
The operating system's QJOH command provides the facility to check whether the host is
live or not. Consider a situation where you have to test a full list of IP addresses. In this
situation, if you test the IP addresses one by one, it will take a lot of time and effort. In
order to handle this situation, we use ping sweep.
Ping sweep
Ping sweep is used to identify the live host from a range of IP addresses by sending the
ICMP ECHO request and the ICMP ECHO reply. From a subnet and network address, an
attacker or pentester can calculate the network range. In this section, I am going to
demonstrate how to take advantage of the ping facility of an operating system.
[ 31 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
In the preceding code, JNQPSUPT imports the OS module so that we can run on the OS
command. The next line, PTQPQFO QJOHO , which takes a DOS
command, is passed in as a string and returns a file-like object connected to the command's
standard input or output streams. The QJOHbO command is a Windows OS
command that sends one ICMP ECHO request packet. By reading the PTQTPQFO
function, you can intercept the command's output. The output is stored in the SFTQPOTF
variable. In the next line, the SFBEMJOFT function is used to read the output of a file-like
object.
The output shows the SFQMZ, CZUF, UJNF, and 55- values, which indicate that the host is
live. Consider another output of the program for IP :
G:Project SnakeChapter 2ip>ips.py
Pinging 10.0.0.2 with 32 bytes of data:
Reply from 10.0.0.16: Destination host unreachable.
Ping statistics for 10.0.0.2:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
The preceding code is very important for proper functioning and is similar to the engine of
a car. In order to make it fully functional, we need to modify the code so that it is platform-
independent and produces easily readable output.
[ 32 ]
||||||||||||||||||||
||||||||||||||||||||
The preceding code asks for the network address of the subnet, but you can give any IP
address of the subnet. The next line, OFUOFUTQMJU , splits the IP address into
four parts. The OFUOFU<> B OFU<> B OFU<> B statement forms the network
address. The last two lines ask for a range of IP addresses.
The preceding code determines whether the code is running on Windows OS or the Linux
platform. The PQFSQMBUGPSNTZTUFN statement informs this to the running
operating system as the QJOH command is different in Windows and Linux. Windows OS
uses QJOHbO to send one packet of the ICMP ECHO request, whereas Linux uses QJOH
bD.
JG PQFS8JOEPXT
QJOHQJOHO
FMJG PQFS-JOVY
QJOHQJOHD
FMTF
QJOHQJOHD
UEBUFUJNFOPX
QSJOU4DBOOJOHJO1SPHSFTT
GPSJQJOYSBOHF TUFO
[ 33 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
BEESOFU TUS JQ
DPNNQJOH BEES
SFTQPOTFPTQPQFO DPNN
GPSMJOFJOSFTQPOTFSFBEMJOFT
JG UUM JOMJOFMPXFS
CSFBL
JG UUM JOMJOFMPXFS
QSJOUBEES -JWF
UEBUFUJNFOPX
UPUBMUU
QSJOUTDBOOJOHDPNQMFUFJOUPUBM
A couple of new things are in the preceding code. The GPSJQJOYSBOHF TUFO
statement supplies the numeric values, that is, the last octet value of the IP address. Within
the GPS loop, the BEESOFU TUS JQ statement makes it one complete IP address, and
the DPNNQJOH BEES statement makes it a full OS command, which passes to
PTQPQFO DPNN . The JG MJOFDPVOU 55- statement checks for the occurrence of
55- in the line. If any 55- value is found in the line, then it breaks the further processing of
the line by using the CSFBL statement. The next two lines of code print the IP address as
live where 55- is found. I used EBUFUJNFOPX to calculate the total time taken to scan.
[ 34 ]
||||||||||||||||||||
||||||||||||||||||||
To establish the connection, the hosts perform a three-way handshake. The three steps in
establishing a TCP connection are as follows:
1. The client sends a segment with the SYN flag; this means the client requests the
server to start a session
2. In the form of a reply, the server sends the segment that contains the ACK and
SYN flags
3. The client responds with an ACK flag
[ 35 ]
Technet24
||||||||||||||||||||
||||||||||||||||||||
UEBUFUJNFOPX
EFGTDBO BEES
TPDLTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TPDLFUTFUEFGBVMUUJNFPVU
SFTVMUTPDLDPOOFDU@FY BEES
JGSFTVMU
SFUVSO
FMTF
SFUVSO
EFGSVO
GPSJQJOYSBOHF TUFO
BEESOFU TUS JQ
JG TDBO BEES
QSJOUBEESJTMJWF
SVO
UEBUFUJNFOPX
UPUBMUU
QSJOUTDBOOJOHDPNQMFUFJOUPUBM
The upper part of the preceding code is the same as in the previous code. Here, we use two
functions. Firstly, the TDBO BEES function uses the socket as discussed in $IBQUFS,
Python with Penetration Testing and Networking. The SFTVMU
TPDLDPOOFDU@FY BEES statement returns an error indicator. The error indicator
is if the operation succeeds, otherwise it is the value of the FSSOP variable. Here, we used
port ; this scanner works for the Windows system. There are some ports such as ,
, (NetBIOS name service), and (Microsoft-DSActive Directory) that are usually
open. So, for better results, you have to change the port and scan repeatedly.
[ 36 ]
||||||||||||||||||||
Exploring the Variety of Random
Documents with Different Content
story; in fact, everybody knows how you got here. I hope you’ll
enjoy every minute of your stay.”
Will was a ruddy-cheeked young man of fully six feet, with
tremendous shoulders and chest, and a voice that would compete,
not without hope of victory, with a bass drum. His smile alone was
enough to win him friends.
“Glad to meet you, Will,” said Clarence. “John here has been
telling me all about you. He says you’re Prefect of the Senior
Sodality. What does that mean?”
“Aren’t you a Catholic?”
“No.”
“Well, the Sodality is organized to honor the Blessed Mother of
God, by getting its members to lead a good Catholic life and by
doing good works. The Prefect is the leading officer; and he’s
supposed, though it may not be always the case, to have special
love for Mary and to show it in his life.”
“By George,” said Clarence, “here it is again. The first Catholic I
ever met to talk with was a little girl with the gypsies, and almost as
soon as she and I got to talking together, she began telling me
about the Blessed Mother and singing her praises.”
“Was the girl a gypsy?” asked Will.
“No; she was captured in Ohio during the flood, last May.”
“Oh; that awful flood!” said Will, his cheerful grin deserting him.
“I lost my little sister in that flood, too.”
“Are you from Ohio?”
“Yes, and my sister’s body wasn’t recovered till two weeks after
she was drowned. Well, let’s change the subject. I hate to think of
it.”
Within an hour Will Benton and Clarence had become fast
friends. Within another, the much-wandering youth, satisfied that his
adventures were over, had fallen into a dreamless sleep, little
suspecting the amazing events that the morrow was destined to
bring.
CHAPTER XVI
In which the Bright-eyed Goddess comes to bat again, and
promises to win the game.
The funeral of the faithful and well-beloved Ben was simple and
solemn, and the mourners fit though few. The Reverend Rector
himself offered up the holy sacrifice of the Mass. Very quietly the
simple cortege proceeded to the Catholic burying ground; and when
the last shovelful of earth was thrown on the coffin Dora stepped
forward and laid upon the mound the flowers such as Ben once
joyed to collect and place at the shrine of “that good woman who
was the Mother of God.”
They were scarcely outside the graveyard, when the Rector
addressed them:
“You have all had too much of tragedy these last days for your
tender years. Dora is a free agent; Clarence is simply our guest; they
have a right to a holiday. As for you, Will, I give you the day in
honor of the efficiency of your strong arm; and you, John, for saving
Clarence.”
The long faces shortened; eyes dimmed with tears grew bright. A
holiday to the school boys! What trouble, what sorrow can hold its
own against a holiday?
“I’ve secured a fine motor-boat for you——”
“I can run a motor all right,” broke in Rieler his face deeply
gashed by a smile.
“And I suggest,” continued the Rector, “Pictured Rocks and a ride
down the river.”
“Ah-h-h-h!” gurgled Dora.
“Oh-h-h-h!” cried Clarence.
“Say—say,” blurted John, “what about our breakfast? We’ve just
been to Communion, you know, all except Clarence, and he hasn’t
eaten yet.”
“There are some things, John,” observed the Rector, “that you
never forget. However, I haven’t overlooked that particular item
either. All you need do is to run down to the Prairie du Chien boat
landing. You’ll find a man there, John Durkin, the boat-owner, who’s
waiting to see that you get off with everything in good order. Then,
John, you motor over to North McGregor, and bring the party up to
Mr. Berry’s hotel. He’s heard of your wonderful adventures, and you
are his breakfast guests.”
“I took a meal there with my pa,” whispered the radiant Rieler,
“when he came up to see me last year. I’m glad I’m hungry,” he
added simply.
“I should think, John,” observed the Rector, “that you must have
that cause for rejoicing a good many times in the day. After your
breakfast, you must get together provisions enough for a good
dinner. The commissary department will be in charge of Will Benton.
Here, Will, are a few dollars for that purpose. Mr. Berry will help you
do the buying.”
T here were, as the two boats came together, shouts and joyous
cries and a quick interchange of crews. Dora was in the arms of
father and mother. Laughter and tears—the tears of strong emotion
—were intermingled with incoherent sobs. Feelings were beyond the
power of human language.
It was then, in the midst of all this, that Master John Rieler, filled
with an enthusiasm which could no longer be bottled up, mounted
the prow of the boat, of which he had that day been the happy
engineer, and raising his cap aloft, bellowed at the top of his voice:
“Three cheers for——” But John did not finish this splendid
sentence, and to this day no one knows for whom he intended the
signal honor; for, happening to wave his cap wildly with these
opening words, he lost his balance, and plumped into the water.
“Oh!” cried Mr. Benton, pulling off his coat.
“Stay where you are,” called the grinning Rector. “Don’t hurt
Rieler’s feelings. To go to his help would be less sensible than
carrying coals to Newcastle.”
John rose just then, and, shaking his locks, smiled graciously at
the crews of the two boats.
“We don’t want you,” said the Rector.
“Thank you, Father,” John made grateful answer, and once more
sank for a long, delicious dive. And thus did the youth continue to
disport himself while huggings were renewed and Babel continued
beside him.
“But, Father,” said Will Benton, “what I can’t understand is this!
Dora was lost; after two weeks her body was recovered and she was
buried in her coffin from our church.”
“You saw the coffin, Will?”
“Yes, Father.”
“But did you see Dora in it?”
“No, Father; you told us she was disfigured and bloated from
being so long in the water; and you said we were not to see her.”
“Exactly. The facts are these: On one day, fourteen bodies of the
flood victims were recovered. Very soon all were identified except
that of a girl dressed in a white dress with a blue sash. I went to
view the body, and really couldn’t make up my mind whether it was
Dora’s, or not. Everybody insisted that it must be Dora. In the
meantime, your mother was so broken-hearted by anxiety that it
looked as if she would lose her mind. It occurred to me that even
the recovery of the body and the Holy Mass over it would set her at
rest, so I took the benefit of the doubt, and allowed the corpse in
white and blue to be buried as though it were Dora’s. But mind, I
never said it was Dora. I allowed the others to do that without
contradicting them; and also my intention in having that Mass
offered was that if Dora were alive, the Mass should go to the poor
abandoned child who took her place.”
“Do you see,” said Dora, “how good our Blessed Mother is? That
little girl because she was in blue and white got a Mass and Christian
burial.”
“Hey, John Rieler,” called the Rector fifteen minutes later, “haven’t
you had enough swimming yet?”
“If it’s all the same to you, Father Rector, I’d like to swim home.”
John, while disporting in the water, had taken off his shoes and
thoughtfully aimed them at the head of the admiring and envious
Clarence.
“It isn’t all the same to me,” responded the Rector. “Here, give
me your hand. Now suppose we start.”
And as they spun homeward, Dora told her wondering parents
the tale of four months on the open road.
“And,” concluded the child, “when I think of dear Ben, who died a
saint, and of Dorcas and her children, who join the Church
tomorrow, and of Clarence who is going to join——”
“You bet I am,” Clarence broke in from the other boat.
“I can’t say that I am sorry.”
“To those who love God all things work together unto good,”
quoted Father Keenan.
“And when I recall,” said Mr. Benton catching Dora by the arms
and beaming with joy and gratitude as he looked upon her radiant
face, “how four months ago, you were pale, anaemic, and sentenced
by the doctor to death within a few months——”
“What!” gasped Will.
“Yes; sentenced to death. The doctor said the child had no sort
of constitution.”
“That doctor was loony,” said Rieler indignantly. “You ought to
see her run. Those fawns you read about in poetry books haven’t
anything on her.”
“I should say not,” added Clarence no less indignantly. “You
should have seen her skipping up Pictured Rocks Hill. She never lost
her wind, never turned a hair, and she’s as sure-footed as a
chamois.”
“All the same,” said the happy father, “the doctor was right. He
was a specialist and knew his business. He told me to keep her in
the open as much as possible; he told me so the very day before the
gypsies ran away with her. For four months she has lived the life the
doctor prescribed—and lived it, I rather think, more abundantly than
had she lived at home. Now, look at her. She is the picture of
health.”
“She’s the picture of something more than health,” whispered
Clarence into the ear of her big brother. “Do you remember those
lines of Wordsworth:
“‘And beauty horn of murmuring sound
Shall pass into her face’?”
Good old Ben said she was an angel. If she isn’t she is, as the
gentlemanly druggists say, ‘something just as good.’”
“Beware of imitations,” said John Rieler.
Whereupon to the manifest discomfort of those in the boat, John
and Clarence set playfully to punching each other.
“Well,” sighed Clarence, as he jumped from the boat at the
Campion landing, “now for a quiet hour before going to bed.”
“Don’t forget supper,” said John.
“I don’t; but that is a quiet affair.”
“All the same,” continued John, “I’m going to keep near you. If
anything happens, I want to be around.”
Then came Dora with her father and mother to greet Clarence;
and the child, as she introduced him, made such comments on their
short but lovely acquaintance as caused Clarence to blush to the
roots of his hair.
“Remember, Clarence,” said Mr. Benton, “that our home is yours,
day or night, winter or summer, in any year, in any season. God sent
you to our little girl.”
“I think,” said Clarence modestly, “that it was, the other way
around. God sent Dora to me. It’s made me—different. Everything I
see and hear now I see and hear from a different angle—and a
better one.”
As they walked up toward the college, Clarence, ably assisted by
the eager John Rieler, pointed out their path of progress toward
Campion on his first arrival. He was at pains to expatiate on John’s
delicacy as to introducing him personally to the Rector.
“It wasn’t so very wrong, anyhow,” said Rieler.
“Didn’t God send me to save Clarence from drowning?”
“Don’t reason that way,” remonstrated Will Benton, whose
reputation as a student of logic was not brilliant only because his
prowess on the athletic field blinded the boys to what were in their
eyes less shining qualities, “Out of evil God draws good; he took
occasion of your breaking the rule to save Clarence’s life.”
“I’m beginning,” said Clarence solemnly, “to lose all faith in the
bright-eyed goddess of adventure. As Betsy Prigg said of Sairey
Gamp’s Mrs. Harris, I don’t believe there ain’t no sich a person.”
“What are you talking about now?” asked Rieler. “Who’s Betsy
Prigg? Who’s Sairey Gamp? Who’s Mrs. Harris? The bright-eyed
goddess has gone to your head, and placed a few bats in your
belfry.”
“John Rieler,” said Clarence, “at your age you ought to be
ashamed of yourself. You ought to know your Dickens. Read Martin
Chuzzlewit, and start tonight.”
“No,” continued Clarence, “I disavow here and now, forever and
forever, the squint-eyed goddess of adventure. I thought I was in
her hands; but now I firmly believe that all along I was in the loving
hands of God.”
Father Keenan, who had preceded the party, was now seen
coming down the steps of the faculty building. He was doing his best
to carry off his Indian immobility of face, but with partial success.
“Clarence,” he cried, “come here.”
“Another adventure,” said Rieler.
Clarence turned deathly pale. Something had happened—
something serious.
“Oh, Father, what is it?” he cried running to the side of the
Rector.
CHAPTER XX
In which there is another joyful reunion, and Clarence presents
an important letter to the Rector of Campion College.