Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit - Download the ebook and start exploring right away
Python Penetration Testing Essentials Techniques for ethical hacking with Python 2nd Edition Mohit - Download the ebook and start exploring right away
com
https://ebookmeta.com/product/python-penetration-testing-
essentials-techniques-for-ethical-hacking-with-python-2nd-
edition-mohit/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookmeta.com/product/beginning-ethical-hacking-with-
python-1st-edition-sanjib-sinha/
ebookmeta.com
https://ebookmeta.com/product/learning-kali-linux-security-testing-
penetration-testing-and-ethical-hacking-1st-edition-ric-messier/
ebookmeta.com
https://ebookmeta.com/product/mayor-of-elf-town-4-1st-edition-dante-
king-2/
ebookmeta.com
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/
ebookmeta.com
https://ebookmeta.com/product/essential-revision-notes-for-frcs-urol-
book-1-1st-edition-jack-donati-bourne/
ebookmeta.com
https://ebookmeta.com/product/eyewitness-to-chaos-personal-accounts-
of-the-intervention-in-haiti-1994-1st-edition-walter-e-kretchik/
ebookmeta.com
https://ebookmeta.com/product/the-blobfish-book-jessica-olien/
ebookmeta.com
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-subhashish-
chattopadhyay/
ebookmeta.com
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/
ebookmeta.com
||||||||||||||||||||
||||||||||||||||||||
||||||||||||||||||||
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
||||||||||||||||||||
Exploring the Variety of Random
Documents with Different Content
angustie dell'esercito alemanno in Italia, perchè l'elettor bavaro
cresciuto cotanto di forze entrò nel Tirolo, e giunse ad impossessarsi
della capitale d'Inspruch. L'avrebbe bene accomodato il possesso e
dominio di quella provincia confinante ai suoi Stati; ma si
aggiugnevano due altre mire, l'una di togliere ai Tedeschi quella
strada per cui solevano spignere in Italia i soccorsi di milizie, e l'altra
di aprirsi un libero commercio coll'esercito franzese, esistente in
Italia, affin di riceverne più facilmente gli occorrenti sussidii.
Mossesi infatti il duca di Vandomo nel mese d'agosto dalla
Lombardia con parte del suo esercito alla volta del Trentino,
sperando di toccar la mano ai Bavaresi, che avevano da venirgli
incontro. Marciarono i Franzesi per Monte Baldo e per le rive del lago
di Garda, e cominciarono ad aggrapparsi per quelle montagne, con
impadronirsi delle castella di Torbole, Nago, Bretonico e d'altre, che
non fecero difesa, a riserva del castello d'Arco, il quale per cinque
giorni sostenne l'empito de' cannoni nemici, con fatiche incredibili fin
colà strascinati. Giunse poi sul fine d'agosto dopo mille stenti
l'esercito franzese alla vista di Trento, ma coll'Adige frapposto, e con
gli abitanti nell'opposta riva preparati a contrastare gli ulteriori
avanzamenti dei nemici. Nè le minaccie del Vandomo, nè molte
bombe avventate contro la città atterrirono punto i Trentini, e
massimamente dacchè in aiuto loro accorse con alcuni reggimenti
cesarei il generale conte Solari. All'aspetto di questi movimenti,
comune credenza era in Italia che in breve si avessero a vedere in
precipizio gli affari dell'imperadore, fatta che fosse l'unione del
Bavaro col duca di Vandomo. Stettero poco a disingannarsi al
comparire all'improvviso mutata tutta la scena. I Tirolesi d'antico
odio pregni contra de' Bavaresi, e massimamente i bravi lor
cacciatori, sì fattamente cominciarono a ristrignere e tempestar coi
loro fucili le truppe nemiche, prendendo spezialmente di mira gli
uffiziali, che altro scampo non ebbe l'elettore, se non quello di
ritirarsi alle sue contrade. Medesimamente non senza maraviglia dei
politici fu osservato ritornarsene il duca di Vandomo in Italia, dopo
aver sacrificato inutilmente di gran gente e munizioni in quella
infelice spedizione. Ora ecco il motivo di sua ritirata.
Non avea mai potuto Vittorio Amedeo duca di Savoia, siccome
principe di mirabile accortezza, e attentissimo non meno al presente
che ai futuri tempi, mirar senza ribrezzo la tanto accresciuta
grandezza della real casa di Francia, e parevagli fabbricato il
mortorio alla sua sovranità, dacchè il ducato di Milano era caduto in
mano d'un monarca sì congiunto di sangue colla potenza franzese.
Portò la congiuntura dei tempi ch'egli si avesse a collegar colle due
corone, tuttochè scorgesse così fatta lega troppo contraria ai proprii
interessi; ma stava egli sempre sospirando il tempo di poter rompere
questa catena; e parve ora venuto, dacchè era vicino a spirare il
tempo del contratto impegno della sua lega coi re di Francia e di
Spagna. Non lasciava la corte cesarea di far buona cera a questo
principe, benchè in apparenza nemico, nè sul principio della rottura
scacciò da Vienna il di lui ministro, come avea praticato con quello
del duca di Mantova. Spedì eziandio nel luglio dell'anno presente a
Torino (per quanto pretesero i Franzesi) il conte di Aversbergh
travestito per intavolare con lui qualche trattato, ma senza sapersi se
ne seguisse conclusione alcuna finora. Quel che è certo, non avea
voluto il duca permettere che le sue truppe passassero verso il
Trentino. Ora i forti sospetti conceputi nella creduta vacillante fede
del duca Vittorio Amedeo diedero impulso al re Cristianissimo di
richiamare in Lombardia il duca di Vandomo. Tornato questo
generale colle sue genti a San Benedetto di Mantova di qua dal Po,
già da lui scelto per suo quartier generale, nel dì 28 oppure 29 di
settembre, messo in armi tutto l'esercito suo, fece disarmar le truppe
di Savoia che si trovavano in quel campo ed altri luoghi, ritenendo
prigioni tutti gli uffiziali e soldati. Non erano più di tre mila; altri
nondimeno li fecero ascendere a quattro o a cinquemila. Per questa
impensata novità e violenza alterato al maggior segno il duca,
principe di grande animo, ne fece alte doglianze per tutte le corti;
mise le guardie in Torino agli ambasciatori di Francia e Spagna;
occupò gran copia d'armi spedite dalla Francia in Italia, ed
imprigionò quanti Franzesi potè cogliere nei suoi Stati. Quindi si
diede precipitosamente a premunirsi e a mettere in armi tutti i suoi
sudditi, per resistere al temporale che andava a scaricarsi sopra i
suoi Stati; giacchè non tardò il duca di Vandomo a mettere in viaggio
buona parte dell'esercito suo contro il Piemonte. Saltò fuori in tal
guisa un nuovo nemico delle due corone, e un nuovo teatro di
guerra in Italia.
Nel dì 5 di dicembre pubblicamente dichiarò il re di Francia Luigi
XIV la guerra contra di esso duca di Savoia, i il quale nel dì 25 di
ottobre, come scrisse taluno, o piuttosto nel dì 8 di novembre, come
ha lo strumento rapportato dal Lunig, avea già stretta lega
coll'imperadore Leopoldo. In esso strumento si vede promesso al
duca Vittorio Amedeo tutto il Monferrato, spettante al duca di
Mantova con Casale, e inoltre Alessandria, Valenza, la Valsesia e la
Lomellina, con obbligo di demolir le fortificazioni di Mortara.
Promettevano inoltre le potenze marittime un sussidio mensile di
ottanta mila ducati di banco ad esso principe, durante la guerra. Fu
poi aggiunto un altro alquanto imbrogliato articolo della cessione
ancora del Vigevanasco, per cui col tempo seguirono molte dispute
colla corte di Vienna. Per essersi trovato il duca colto all'improvviso
dallo sdegno franzese, e specialmente sprovveduto di cavalleria, gli
convenne ricorrere al generale conte di Staremberg, il quale,
desideroso di assistere il nuovo alleato, mise improvvisamente in
viaggio, nel dì 20 di ottobre, mille cinquecento cavalli sotto il
comando del generale marchese Annibale Visconti. Benchè sollecita
fosse la lor marcia, più solleciti furono gli avvisi al duca di Vandomo
del lor disegno; laonde ben guernito di milizia il passo della
Stradella, Serravalle ed altri siti, allorchè colà giunsero gli affaticati
Alemanni, trovarono un terribil fuoco, e andarono presto in rotta.
Molti furono gli uccisi, molti i prigioni, ed a quei che colla fuga si
sottrassero al cimento, convenne dipoi passare fino a San Pier di
Arena presso Genova, e valicare aspre montagne per giugnere in
Piemonte. Questo picciolo rinforzo, e l'essere stati i Franzesi, a
cagion del suddetto passaggio, impegnati in varii movimenti, servì di
non lieve respiro al duca di Savoia; ma non già a preservarlo
dagl'insulti a lui minacciati dal potente nemico. Il perchè determinò
in fine il saggio conte Guido di Staremberg un'arditissima impresa,
che, per essere felicemente riuscita, riportò poscia il plauso
d'ognuno. Quando si pensava la gente che l'esercito suo, postato sul
Modenese e Mantovano di qua da Po, si fosse ben adagiato nei
quartieri d'inverno e pensasse al riposo, all'improvvisa con circa dieci
mila fanti e quattro mila cavalli, seco menando sedici cannoni, nel
giorno santo del Natale passò esso Staremberg la Secchia, e pel
Carpigiano s'indirizzò alla strada maestra chiamata Claudia,
prendendo pel Reggiano e Parmigiano con marcie sforzate il
cammino alla volta del Piemonte, senza far caso dei rigori della
stagione, delle strade rotte e di tanti fiumi gravidi di acqua che
conveniva passare. Era già tornato il duca di Vandomo al campo di
San Benedetto di Mantova. Al primo avviso di questo impensato
movimento dei nemici, raunate le sue truppe, si diede ad inseguirli
con forze, chi disse minori, e chi maggiori, ma senza poter mai
raggiugnerli, oppure senza mai volerli raggiugnere, per poca voglia
di azzardare una battaglia. Si contarono bensì alcune scaramucce ed
incontri, nei quali lasciarono la vita i due valorosi generali Lictenstein
Tedesco e Solari Italiano; ma questi non poterono impedire al prode
comandante di felicemente superar tutti i disagi, e di pervenire ad
unirsi col duca di Savoia nel dì 13 del seguente gennaio, con infinita
consolazione di lui e de' sudditi suoi.
Presero in questi tempi, cioè nel dì 8 di dicembre, i Franzesi
dimoranti in Modena il pretesto di confiscare al duca Rinaldo d'Este
tutte le sue rendite e mobili, perchè il suo ministro in Vienna,
trovandosi nell'anticamera della regina de' Romani, in passando
l'arciduca Carlo, dichiarato re di Spagna, l'inchinò. A chi vuol far del
male, ogni cosa gli fa giuoco. Entrato nel novembre il maresciallo di
Tessè nella Savoia, s'impadronì di Sciambery sua capitale, e poscia
strinse con un blocco la fortezza di Monmegliano. Riuscì in
quest'anno alle potenze marittime e all'imperatore Leopoldo di ritirar
seco in lega un'altra potenza, cioè Pietro II re di Portogallo. Gli
articoli di questa alleanza furono sottoscritti nel dì 16 di maggio, e
fatte di grandi promesse a quel monarca, fondate nondimeno sugli
incerti avvenimenti delle guerre. Di qui sorsero speranze ne' collegati
di potere un dì detronizzare il re di Spagna Filippo V, al qual fine
creduto fu non solamente utile, ma necessario, che lo stesso
arciduca Carlo, proclamato re di Spagna col nome di Carlo III,
passasse in persona colà per dar polso ai Portoghesi, e per animare
l'occulto partito austriaco che si conservava tuttavia nei regni di
Spagna. Pertanto questo savio, affabile e piissimo principe, preso
congedo dagli augusti lagrimanti suoi genitori e dal fratello Giuseppe
re de' Romani, si mise nel settembre in viaggio alla volta dell'Olanda,
con ricevere immensi onori per dovunque passò. Pertanto ecco
oramai gran parte dell'Europa in guerra per disputare della
monarchia di Spagna; nel qual tempo anche il Settentrione ardeva
tutto di guerra per la lega del Sassone re di Polonia collo czar della
Russia contro il re di Svezia, che diede lor delle aspre lezioni. Presero
in quest'anno i Franzesi Brisac, ricuperarono Landau, diedero una
rotta ai Tedeschi sotto esso Landau; e all'incontro gli Anglolandi
s'impadronirono di Bona, Huz e Limburgo.
Cristo mdcciv. Indizione xii.
Anno di Clemente XI papa 5.
Leopoldo imperadore 47.