100% found this document useful (2 votes)
21 views

(Ebook) Python Penetration Testing Essentials: Techniques for ethical hacking with Python, 2nd Edition by Mohit ISBN 9781789138962, 1789138965 - The complete ebook set is ready for download today

The document provides access to various eBooks focused on penetration testing and ethical hacking, including titles like 'Python Penetration Testing Essentials' and 'Learning Kali Linux.' It offers instant downloads in multiple formats and emphasizes the practical application of Python in security testing. The content is suitable for Python programmers and security researchers looking to enhance their skills in ethical hacking.

Uploaded by

devredkaoula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
21 views

(Ebook) Python Penetration Testing Essentials: Techniques for ethical hacking with Python, 2nd Edition by Mohit ISBN 9781789138962, 1789138965 - The complete ebook set is ready for download today

The document provides access to various eBooks focused on penetration testing and ethical hacking, including titles like 'Python Penetration Testing Essentials' and 'Learning Kali Linux.' It offers instant downloads in multiple formats and emphasizes the practical application of Python in security testing. The content is suitable for Python programmers and security researchers looking to enhance their skills in ethical hacking.

Uploaded by

devredkaoula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Instant Ebook Access, One Click Away – Begin at ebooknice.

com

(Ebook) Python Penetration Testing Essentials:


Techniques for ethical hacking with Python, 2nd
Edition by Mohit ISBN 9781789138962, 1789138965

https://ebooknice.com/product/python-penetration-testing-
essentials-techniques-for-ethical-hacking-with-python-2nd-
edition-35189888

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Learning Kali Linux: Security Testing, Penetration Testing, and Ethical
Hacking, 2nd Edition by Ric Messier ISBN 9781098154134, 9781098154127, 1098154126,
1098154134

https://ebooknice.com/product/learning-kali-linux-security-testing-penetration-
testing-and-ethical-hacking-2nd-edition-51708994

ebooknice.com

(Ebook) The Basics of Hacking and Penetration Testing: Ethical Hacking and
Penetration Testing Made Easy by Patrick Engebretson ISBN 1597496553

https://ebooknice.com/product/the-basics-of-hacking-and-penetration-testing-
ethical-hacking-and-penetration-testing-made-easy-2371036

ebooknice.com

(Ebook) Effective Python Penetration Testing by kan

https://ebooknice.com/product/effective-python-penetration-testing-50195672

ebooknice.com

(Ebook) Beginning Ethical Hacking with Python by Sanjib Sinha ISBN 9781484225417,
1484225414

https://ebooknice.com/product/beginning-ethical-hacking-with-python-47822990

ebooknice.com
(Ebook) Ethical Hacking and Penetration Testing Guide by Rafay Baloch ISBN
9781482231618, 9781482231625, 1482231611, 148223162X

https://ebooknice.com/product/ethical-hacking-and-penetration-testing-
guide-4747804

ebooknice.com

(Ebook) Learning Kali Linux: security testing, penetration testing, and ethical
hacking by Messier, Ric ISBN 9780123456786, 9781492028697, 0123456789, 149202869X

https://ebooknice.com/product/learning-kali-linux-security-testing-penetration-
testing-and-ethical-hacking-11894646

ebooknice.com

(Ebook) Python Penetration Testing Cookbook by Rehim, Rejah ISBN 9781784399771,


1784399779

https://ebooknice.com/product/python-penetration-testing-cookbook-22009540

ebooknice.com

(Ebook) Einstieg in Kali Linux: Penetration Testing und Ethical Hacking mit Linux
(German Edition) by Jürgen Ebner ISBN 9783747504635, 3747504639

https://ebooknice.com/product/einstieg-in-kali-linux-penetration-testing-und-
ethical-hacking-mit-linux-german-edition-36414130

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James ISBN
9781459699816, 9781743365571, 9781925268492, 1459699815, 1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com
||||||||||||||||||||

||||||||||||||||||||
||||||||||||||||||||

Python Penetration Testing


Essentials
Second Edition

5FDIOJRVFTGPSFUIJDBMIBDLJOHXJUI1ZUIPO

Mohit

BIRMINGHAM - MUMBAI

||||||||||||||||||||
||||||||||||||||||||

Python Penetration Testing Essentials


Second Edition
Copyright a 2018 Packt Publishing

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.

Commissioning Editor: Vijin Boricha


Acquisition Editor: Noyonika Das
Content Development Editor: Roshan Kumar
Technical Editor: Sushmeeta Jena
Copy Editor: Safis Editing
Project Coordinator: Hardik Bhinde
Proofreader: Safis Editing
Indexer: Aishwarya Gangawane
Graphics: Jason Monteiro
Production Coordinator: Deepika Naik

First published: January 2015


Second edition: May 2018

Production reference: 1290518

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

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

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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

About the author


Mohit is a Python programmer with a keen interest in the field of information security. He
has B.Tech (UIET, KUK, 2009) and M.E (Thapar University, 2012) degree. He is a CEH,
ECSA at EC-Council USA. He has worked in IBM and Sapient. He is currently doing PhD
from Thapar Institute of Engg & Technology under Dr. Maninder Singh. He has published
several articles in national and international magazines. He is the author of Python
Penetration Testing Essentials, Python: Penetration Testing for Developers and Learn Python in 7
Days also by Packt. His username is mohitrajcs on gmail. .

||||||||||||||||||||
||||||||||||||||||||

About the reviewers


Sanjeev Jaiswal is a computer graduate from CUSAT with 9 years of industrial experience.
He uses Perl, Python, AWS, and GNU/Linux for his day-to-day activities. He's currently
working on projects involving penetration testing, source code review, security design, and
implementations in AWS and Cloud security projects.

He is learning DevSecOps and security automation currently as well. Sanjeev loves


teaching engineering students and IT professionals. He has been teaching for the past 8
years in his leisure time. He founded Alien Coders and Cybercloud Guru as well.

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.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit BVUIPSTQBDLUQVCDPN
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.

||||||||||||||||||||
||||||||||||||||||||

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

Checking the HTTP header 155


Information gathering of a website from whois.domaintools.com 157
Email address gathering from a web page 159
Banner grabbing of a website 160
Hardening of a web server 161
Summary 162
Chapter 8: Client-Side and DDoS Attacks 163
Introducing client-side validation 163
Tampering with the client-side parameter with Python 164
Effects of parameter tampering on business 169
Introducing DoS and DDoS 172
Single IP, single ports 172
Single IP, multiple port 174
Multiple IP, multiple ports 176
Detection of DDoS 178
Summary 181
Chapter 9: Pentesting SQL and XSS 182
Introducing the SQL injection attack 183
Types of SQL injections 184
Simple SQL injection 184
Blind SQL injection 184
Understanding the SQL injection attack by a Python script 184
Learning about cross-site scripting 194
Persistent or stored XSS 195
Nonpersistent or reflected XSS 195
Summary 204
Other Books You May Enjoy 205
Index 208

[ 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.

Who this book is for


If you are a Python programmer, a security researcher, or a network admin who has basic
knowledge of Python programming and want to learn about penetration testing with the
help of Python, this book is ideal for you. Even if you are new to the field of ethical hacking,
this book can help you find the vulnerabilities in your system so that you are ready to
tackle any kind of attack or intrusion.

What this book covers


$IBQUFS, Python with Penetration Testing and Networking, goes through the prerequisites of
the following chapters. This chapter also discusses the socket and its methods. The server
socket's method defines how to create a simple server.

$IBQUFS, Scanning Pentesting, covers how to perform network scanning to gather


information on a network, host, and the services that are running on the hosts. You will see
a very fast and efficient IP scanner.

$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.

To get the most out of this book


In order to understand the book reader must have the knowledge of Networking
fundamentals, basic knowledge of Linux OS, good knowledge of information security and
core Python.

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.

Download the example code files


You can download the example code files for this book from your account at
XXXQBDLUQVCDPN. If you purchased this book elsewhere, you can visit
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly to you.

[2]

||||||||||||||||||||
||||||||||||||||||||

Preface

You can download the code files by following these steps:

1. Log in or register at XXXQBDLUQVCDPN.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR/7-Zip for Windows


Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux

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!

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: IUUQXXXQBDLUQVCDPNTJUFTEFGBVMUGJMFT
EPXOMPBET1ZUIPO1FOFUSBUJPO5FTUJOH&TTFOUJBMT4FDPOE&EJUJPO@$PMPS*NBHFTQEG.

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."

A block of code is set as follows:


JNQPSUPT
SFTQPOTFPTQPQFO QJOHO
GPSMJOFJOSFTQPOTFSFBEMJOFT 
QSJOUMJOF

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

Any command-line input or output is written as follows:


python setup.py install

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."

Warnings or important notes appear like this.

Tips and tricks appear like this.

[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!

For more information about Packt, please visit QBDLUQVCDPN.

[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:

The scope of pentesting


The need for pentesting
Components to be tested
Qualities of a good pentester
Approaches to pentesting
Understanding the tests and tools you'll need
Network sockets
Server socket methods
Client socket methods
General socket methods
Practical examples of sockets
Socket exceptions
Useful socket methods

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Introducing the scope of pentesting


In simple words, penetration testing is used to test the information security measures of a
company. Information security measures entail a company's network, database, website,
public-facing servers, security policies, and everything else specified by the client. At the
end of the day, a pentester must present a detailed report of their findings such as
weaknesses, vulnerabilities in the company's infrastructure, and the risk level of particular
vulnerabilities, and provide solutions if possible.

The need for pentesting


There are several points that describe the significance of pentesting:

Pentesting identifies the threats that might expose the confidentiality of an


organization
Expert pentesting provides assurance to the organization with a complete and
detailed assessment of organizational security
Pentesting assesses the network's efficiency by producing a huge amount of
traffic and scrutinizes the security of devices such as firewalls, routers, and
switches
Changing or upgrading the existing infrastructure of software, hardware, or
network design might lead to vulnerabilities that can be detected by pentesting
In today's world, potential threats are increasing significantly; pentesting is a
proactive exercise to minimize the chances of being exploited
Pentesting ensures whether suitable security policies are being followed or not

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]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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:

Routers, switches, or gateways


Public-facing systems; websites, DMZ, email servers, and remote systems
DNS, firewalls, proxy servers, FTP, and web servers

Testing should be performed on all hardware and software components of a network


security system.

Qualities of a good pentester


The following points describe the qualities of a good pentester. They should:

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]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Defining the scope of pentesting


Before we get into pentesting, the scope of pentesting should be defined. The following
points should be taken into account while defining the scope:

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.

The scope of pentesting is defined in two types of tests:

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:

Black-box pentesting follows a non-deterministic approach of testing:


You will be given just a company name
It is like hacking with the knowledge of an outside attacker

[9]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

You do not need any prior knowledge of the system


It is time-consuming
White-box pentesting follows a deterministic approach to testing:
You will be given complete knowledge of the infrastructure that
needs to be tested
This is like working as a malicious employee who has ample
knowledge of the company's infrastructure
You will be provided information on the company's infrastructure,
network type, company's policies, do's and don'ts, the IP address,
and the IPS/IDS firewall
Gray-box pentesting follows a hybrid approach of black-box and white-box
testing:
The tester usually has limited information on the target
network/system that is provided by the client to lower the costs
and decrease trial and error on the part of the pentester
It performs the security assessment and testing internally

Introducing Python scripting


Before you start reading this book, you should know the basics of Python programming,
such as the basic syntax, variable type, data type tuple, list dictionary, functions, strings,
and methods. Two versions, 3.4 and 2.7.8, are available at QZUIPOPSHEPXOMPBET.

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

Understanding the tests and tools you'll


need
As you have seen, this book is divided into nine chapters. To conduct scanning and sniffing
pentesting, you will need a small network of attached devices. If you don't have a lab, you
can make virtual machines on your computer. For wireless traffic analysis, you should have
a wireless network. To conduct a web attack, you will need an Apache server running on
the Linux platform. It is a good idea to use CentOS or Red Hat Version 5 or 6 for the web
server because this contains the RPM of Apache and PHP. For the Python script, we will
use the Wireshark tool, which is open source and can be run on Windows as well as Linux
platforms.

Learning the common testing platforms with


Python
You will now perform some pentesting; I hope you are well acquainted with networking
fundamentals such as IP addresses, classful subnetting, classless subnetting, the meaning of
ports, network addresses, and broadcast addresses. A pentester must be knowledgeable in
networking fundamentals as well as in at least one operating system; if you are thinking of
using Linux, then you are on the right track. In this book, we will execute our programs on
Windows as well as Linux. In this book, Windows, CentOS, and Kali Linux will be used.

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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

Here is the description of the parameters:


TPDLFU@GBNJMZTPDLFU"'@*/&51'@1"$,&5

"'@*/&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.

Server socket methods


In a client-server architecture, there is one centralized server that provides service, and
many clients request and receive service from the centralized server. Here are some
methods you need to know:

TPDLFUCJOE BEESFTT : This method is used to connect the address (IP


address, port number) to the socket. The socket must be open before connecting
to the address.
TPDLFUMJTUFO R : This method starts the TCP listener. The R argument
defines the maximum number of lined-up connections.

[ 12 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

Client socket methods


The only method dedicated to the client is the following:

TPDLFUDPOOFDU BEESFTT : This method connects the client to the server. The
BEESFTT argument is the address of the server.

General socket methods


The general socket methods are as follows:

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.

Be careful while using the TPDLFUSFDWGSPN@JOUP CVGGFS method


in older versions of Python. Buffer overflow vulnerability has been found
in this method. The name of this vulnerability is CVE-2014-1912, and its
vulnerability was published on February 27, 2014. Buffer overflow in the
TPDLFUSFDWGSPN@JOUP function in .PEVMFTTPDLFUNPEVMFD in
Python 2.5 before 2.7.7, 3.x before 3.3.4, and 3.4.x before 3.4rc1, allows
remote attackers to execute arbitrary code via a crafted string.

[ 13 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

Now, it is time for the practical; no more mundane theory.

Moving on to the practical


First, we will make a server-side program that offers a connection to the client and sends a
message to the client. Run TFSWFSQZ:
JNQPSUTPDLFU
IPTU4FSWFSBEESFTT
QPSU1PSUPG4FSWFS
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TCJOE IPTUQPSU CJOETFSWFS
TMJTUFO 
DPOOBEESTBDDFQU
QSJOUBEES/PX$POOFDUFE
DPOOTFOE 5IBOLZPVGPSDPOOFDUJOH
DPOODMPTF

The preceding code is very simple; it is minimal code on the server side.

[ 14 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

This is the output of the TFSWFSQZ program:


G:PythonNetworking>python server1.py

Now, the server is in the listening mode and is waiting for the client.

Let's see the client-side code. Run DMJFOUQZ:


JNQPSUTPDLFU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
IPTUTFSWFSBEESFTT
QPSUTFSWFSQPSU
TDPOOFDU IPTUQPSU
QSJOUTSFDW 
TTFOE )FMMP4FSWFS
TDMPTF

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

The output of TFSWFSQZ is shown here:

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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 general syntax of CZUFBSSBZ is as follows:


CZUFBSSBZ <TPVSDF<FODPEJOH<FSSPST>>>

Let's illustrate this with an example:


NCZUFBSSBZ .PIJU.PIJU
N<>

N<>

N<>)FMMP
N
CZUFBSSBZ C )FMMP.PIJU

This is an example of slicing the CZUFBSSBZ.

Now, let's look at the TQMJU operation on CZUFBSSBZ :


NCZUFBSSBZ )FMMP.PIJU
N
CZUFBSSBZ C )FMMP.PIJU
NTQMJU
<CZUFBSSBZ C )FMMP CZUFBSSBZ C .PIJU >

The following is the BQQFOE operation on CZUFBSSBZ :


NBQQFOE 
N
CZUFBSSBZ C )FMMP.PIJU
CZUFBSSBZ C )FMMP8PSME

The next example is of TSFDW@JOUP CVGG . In this example, we will use CZUFBSSBZ to
create a buffer to store data.

First, run the server-side code. Run TFSWFSQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".

[ 18 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

Let's run the client-side program. Run DMJFOUQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
TDPOOFDU IPTUQPSU
CVGCZUFBSSBZ   CVGGFSDSFBUFE
QSJOU/VNCFSPG#ZUFTTSFDW@JOUP CVG
QSJOUCVG
TDMPTF

In the preceding program, a CVG parameter is created using CZUFBSSBZ . The


TSFDW@JOUP CVG statement gives us the number of bytes received. The CVG parameter
gives us the string received.

The output of DMJFOUQZ and TFSWFSQZ is shown in the following screenshot:

[ 19 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

This time, I will create a UDP socket.

Run VEQQZ, and we will discuss the code line by line:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
TCJOE IPTUQPSU
EBUBBEESTSFDWGSPN 
QSJOUSFDFJWFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF

TPDLFU40$,@%(3". creates a UDP socket, and EBUBBEESTSFDWGSPN 


returns two things, the first is the data and the second is the address of the source.

Now, see the client-side preparations. Run VEQQZ:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
QSJOUTTFOEUP IFMMPBMM IPTUQPSU
TDMPTF

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The following screenshot shows the output of VEQQZ (the UDP server) and VEQQZ (the
UDP client):

The server program successfully received data.

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.

For example, let's look at the following code:


JNQPSUTPDLFU
IPTU
QPSU
TTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@%(3".
TCJOE IPTUQPSU
TTFUUJNFPVU 
EBUBBEESTSFDWGSPN 
QSJOUSFDFWJFEGSPNBEES
QSJOUPCUBJOFEEBUB
TDMPTF

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
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The output is shown in the following screenshot:

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

The output is shown in the following screenshot:

[ 22 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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:

FYDFQUJPOTPDLFUIFSSPS: This block catches the address-related error.


FYDFQUJPOTPDLFUUJNFPVU: This block catches the exception when a timeout
on a socket occurs, which has been enabled by TFUUJNFPVU . In the previous
example, you can see that we used TPDLFUUJNFPVU.
FYDFQUJPOTPDLFUHBJFSSPS: This block catches any exception that is raised
due to HFUBEESJOGP and HFUOBNFJOGP .
FYDFQUJPOTPDLFUFSSPS: This block catches any socket-related errors. If you
are not sure about any exception, you could use this. In other words, you can say
that it is a generic block and can catch any type of exception.

Downloading the example code

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.

Useful socket methods


So far, you have gained knowledge of socket and client-server architecture. At this level,
you can make a small program of networks. However, the aim of this book is to test the
network and gather information. Python offers very beautiful as well as useful methods to
gather information. First, import the socket and then use these methods:

TPDLFUHFUIPTUCZOBNF IPTUOBNF : This method converts a hostname to the


IPv4 address format. The IPv4 address is returned in the form of a string. Here is
an example:
>>> import socket>>>
socket.gethostbyname('thapar.edu')'220.227.15.55'>>>>>>
socket.gethostbyname('google.com')'173.194.126.64'>>>

[ 23 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

I know you are thinking about the OTMPPLVQ command. Later, you will see more magic.

TPDLFUHFUIPTUCZOBNF@FY OBNF : This method converts a hostname to the


IPv4 address pattern. However, the advantage over the previous method is that
it gives all the IP addresses of the domain name. It returns a tuple (hostname,
canonical name, and IP_addrlist) where the hostname is given by us, the
canonical name is a (possibly empty) list of canonical hostnames of the server for
the same address, and IP_addrlist is a list of all of the available IP addresses of
the same hostname. Often, one domain name is hosted on many IP addresses to
balance the load of the server. Unfortunately, this method does not work for
IPv6. I hope you are well-acquainted with tuples, lists, and dictionaries. Let's
look at an example:
>>> socket.gethostbyname_ex('thapar.edu')('thapar.edu', [],
['14.139.242.100', '220.227.15.55'])>>>
socket.gethostbyname_ex('google.com')>>>('google.com', [],
['173.194.36.64', '173.194.36.71', '173.194.36.73',
'173.194.36.70',
'173.194.36.78', '173.194.36.66', '173.194.36.65',
'173.194.36.68',
'173.194.36.69', '173.194.36.72', '173.194.36.67'])>>>

It returns many IP addresses for a single domain name. This means that one domain such
as UIBQBSFEV or HPPHMFDPN runs on multiple IPs.

TPDLFUHFUIPTUOBNF : This returns the hostname of the system where the


Python interpreter is currently running:
>>> socket.gethostname()'eXtreme'

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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'

In the preceding example, FEHFTUBSTIWGSD is the hostname, and GBDFCPPLDPN


is the domain name. In the following example, FQDN is not available for UIBQBSFEV:
>>> socket.getfqdn('thapar.edu')'thapar.edu'

If the name argument is blank, it returns the current machine name:


>>> socket.getfqdn()'eXtreme'>>>

TPDLFUHFUIPTUCZBEES JQ@BEESFTT : This is like a reverse lookup for the


name. It returns a tuple (hostname, canonical name, and IP_addrlist) where
hostname is the hostname that responds to the given JQ@BEESFTT, the canonical
name is a (possibly empty) list of canonical names of the same address, and
IP_addrlist is a list of IP addresses for the same network interface on the same
host:
>>> socket.gethostbyaddr('173.194.36.71')('del01s06-in-
f7.1e100.net', [], ['173.194.36.71'])>>>
socket.gethostbyaddr('119.18.50.66')Traceback (most recent call
last): File "<pyshell#9>", line 1, in <module>
socket.gethostbyaddr('119.18.50.66')herror: [Errno 11004] host
not found

It shows an error in the last query because reverse DNS lookup is not present.

TPDLFUHFUTFSWCZOBNF TFSWJDFOBNF<QSPUPDPM@OBNF> : This converts


any protocol name to the corresponding port number. The Protocol name is
optional, either TCP or UDP. For example, the DNS service uses TCP as well as
UDP connections. If the protocol name is not given, any protocol could match:
>>> import socket>>> socket.getservbyname('http')80>>>
socket.getservbyname('smtp','tcp')25>>>

[ 25 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

TPDLFUHFUTFSWCZQPSU QPSU<QSPUPDPM@OBNF> : This converts an internet


port number to the corresponding service name. The protocol name is optional,
either TCP or UDP:
>>> socket.getservbyport(80)'http'>>>
socket.getservbyport(23)'telnet'>>>
socket.getservbyport(445)'microsoft-ds'>>>

TPDLFUDPOOFDU@FY BEESFTT : This method returns an error indicator. If


successful, it returns ; otherwise, it returns the FSSOP variable. You can take
advantage of this function to scan the ports. Run the DPOOFDU@FYQZ program:
JNQPSUTPDLFU
SNJQ 
QPSUMJTU<>

GPSQPSUJOQPSUMJTU
TPDLTPDLFUTPDLFU TPDLFU"'@*/&5TPDLFU40$,@453&".
SFTVMUTPDLDPOOFDU@FY SNJQQPSU
QSJOUQPSUSFTVMU
TPDLDMPTF

The output is shown in the following screenshot:

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

This socket method converts the host and port arguments into a sequence of five tuples.

Let's take a look at the following example:


>>> import socket
>>> socket.getaddrinfo('www.thapar.edu', 'http')
[(2, 1, 0, '', ('220.227.15.47', 80)), (2, 1, 0, '',
('14.139.242.100', 80))]
>>>

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.

Use the following code to find the result in a readable form:


JNQPSUTPDLFU
EFGHFU@QSPUOVNCFS QSFGJY 
SFUVSOEJDU  HFUBUUS TPDLFUB B
GPSBJOEJS TPDLFU
JGBTUBSUTXJUI QSFGJY

QSPUP@GBNHFU@QSPUOVNCFS "'@
UZQFTHFU@QSPUOVNCFS 40$,@
QSPUPDPMTHFU@QSPUOVNCFS *113050@

GPSSFTJOTPDLFUHFUBEESJOGP XXXUIBQBSFEV  IUUQ 

GBNJMZTPDLUZQFQSPUPDBOPOOBNFTPDLBEESSFT

QSJOU 'BNJMZ QSPUP@GBN<GBNJMZ>


QSJOU 5ZQF UZQFT<TPDLUZQF>
QSJOU 1SPUPDPM QSPUPDPMT<QSPUP>
QSJOU $BOPOJDBMOBNF DBOPOOBNF
QSJOU 4PDLFUBEESFTT TPDLBEES

[ 27 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

The output of the code is shown in the following screenshot:

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 ]

||||||||||||||||||||
||||||||||||||||||||

Python with Penetration Testing and Networking Chapter 1

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.

In this chapter, we will cover the following topics:

How to check live systems


Ping sweep
TCP scanner
How to create an efficient IP scanner
Services running on the target machine
The concept of a port scanner
How to create an efficient port scanner

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:

For the application layer, PDU indicates data


For the transport layer, PDU indicates a segment
For the internet or the network layer, PDU indicates a packet
For the data link layer or network access layer, PDU indicates a frame
For the physical layer, that is, physical transmission, PDU indicates bits

||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

How to check live systems in a network and


the concept of a live system
A ping scan involves sending an ICMP ECHO Request to a host. If a host is live, it will
return an ICMP ECHO Reply, as shown in the following diagram:

+%/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.

First, I shall write a simple and small piece of code, as follows:


JNQPSUPT
SFTQPOTFPTQPQFO QJOHO
GPSMJOFJOSFTQPOTFSFBEMJOFT 
QSJOUMJOF

[ 31 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

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 of the program is as follows:


G:Project SnakeChapter 2ip>ips.py
Pinging 10.0.0.1 with 32 bytes of data:
Reply from 10.0.0.1: bytes=32 time=3ms TTL=64
Ping statistics for 10.0.0.1:
 Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
 Minimum = 3ms, Maximum = 3ms, Average = 3ms

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 output shows that the host is not live.

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.

I want my code to work for a range of IP addresses:


JNQPSUPT
OFUSBX@JOQVU &OUFSUIF/FUXPSL"EESFTT
OFUOFUTQMJU 
QSJOUOFU
B 
OFUOFU<> B OFU<> B OFU<> B
QSJOUOFU
TUJOU SBX@JOQVU &OUFSUIF4UBSUJOH/VNCFS
FOJOU SBX@JOQVU &OUFSUIF-BTU/VNCFS

[ 32 ]

||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

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.

To make it platform-independent, use the following code:


JNQPSUPT
JNQPSUQMBUGPSN
PQFSQMBUGPSNTZTUFN
JG PQFS8JOEPXT 
QJOHQJOHO
FMJG PQFS-JOVY 
QJOHQJOHD
FMTF
QJOHQJOHD

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.

Now, let's see the full code as follows:


JNQPSUPT
JNQPSUQMBUGPSN
GSPNEBUFUJNFJNQPSUEBUFUJNF
OFUSBX@JOQVU &OUFSUIF/FUXPSL"EESFTT
OFUOFUTQMJU 
B 
OFUOFU<> B OFU<> B OFU<> B
TUJOU SBX@JOQVU &OUFSUIF4UBSUJOH/VNCFS
FOJOU SBX@JOQVU &OUFSUIF-BTU/VNCFS
FOFO 
PQFSQMBUGPSNTZTUFN

JG PQFS8JOEPXT 
QJOHQJOHO
FMJG PQFS-JOVY 
QJOHQJOHD
FMTF
QJOHQJOHD
UEBUFUJNFOPX
QSJOU4DBOOJOHJO1SPHSFTT
GPSJQJOYSBOHF TUFO 

[ 33 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

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.

The output of the QJOH@TXFFQQZ program is as follows:


G:Project SnakeChapter 2ip>python ping_sweep.py
Enter the Network Address 10.0.0.1
Enter the Starting Number 1
Enter the Last Number 60
Scanning in Progress
10.0.0.1 --> Live
10.0.0.2 --> Live
10.0.0.5 --> Live
10.0.0.6 --> Live
10.0.0.7 --> Live
10.0.0.8 --> Live
10.0.0.9 --> Live
10.0.0.10 --> Live
10.0.0.11 --> Live
scanning complete in 0:02:35.230000

To scan 60 IP addresses, the program took 2 minutes 35 seconds.

[ 34 ]

||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

The TCP scan concept and its implementation


using a Python script
Ping sweep works on the ICMP ECHO request and the ICMP ECHO reply. Many users
turn off their ICMP ECHO reply feature or use a firewall to block ICMP packets. In this
situation, your ping sweep scanner might not work. In this case, you need a TCP scan. I
hope you are familiar with the three-way handshake, as shown in the following diagram:

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

Now, let's see the following code for a TCP scan:


JNQPSUTPDLFU
GSPNEBUFUJNFJNQPSUEBUFUJNF
OFUSBX@JOQVU &OUFSUIF*1BEESFTT
OFUOFUTQMJU 
B 
OFUOFU<> B OFU<> B OFU<> B
TUJOU SBX@JOQVU &OUFSUIF4UBSUJOH/VNCFS
FOJOU SBX@JOQVU &OUFSUIF-BTU/VNCFS
FOFO 

[ 35 ]

Technet24
||||||||||||||||||||
||||||||||||||||||||

Scanning Pentesting Chapter 2

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.

The output of the JQUDQTDBOQZ program is as follows:


G:Project SnakeChapter 2ip>python iptcpscan.py
Enter the IP address 10.0.0.1
Enter the Starting Number 1
Enter the Last Number 60
10.0.0.8 is live
10.0.0.11 is live
10.0.0.12 is live
10.0.0.15 is live
scanning complete in 0:00:57.415000
G:Project SnakeChapter 2ip>

[ 36 ]

||||||||||||||||||||
Another Random Scribd Document
with Unrelated Content
and Aegina, and so forth—telling him such stories from Greek history
as I could remember, or partially invent. In the Acropolis itself,
wandering among the splendid and touching ruins, there wasn’t a
soul but a dirty man, with large patches on his knees, gathering
snails.
“He follows the footsteps of Pericles, of Alcibiades, and of Solon,”
I said, “and from their dim traces he gathers snails for soup. Such,
my dear Teddy,” I added, tranquilly, “is all the history he knows. To
him the Acropolis is nothing but a hunting-ground for snails.”
“You’re talking exactly like Mr. Barlow!” replied Teddy, with a
dissatisfied snort.
In the afternoon we again set out for the Acropolis. At the
bottom of the sacred ascent a couple of carriages were waiting.
“It can scarcely be they,” I said. “They would come round and try
all the hotels first, surely.”
“Oh, a man like Brentin would do anything!” Teddy cried.
I looked into the first carriage, and soon recognized a little,
rather old, cloak Lucy used to wear, with a high Medici collar. She
never had much money for her clothes, poor child, and was apt to
be a little behind the fashions.
“It’s really they, Teddy,” I said. “Come along and we’ll give them
a fright. They deserve it.”
“They do, indeed!” shouted Teddy, scarlet with rage.
We peeped in cautiously at the entrance, and there they were.
We could see them all crossing from the Parthenon towards the
Erechtheum, headed by that toad Brentin. We let them get well
inside the walls of the beautiful little temple, and then we went
quickly across to the left towards them.
Just as we got up to the white marble walls, I pushed Teddy and
said, “Hide.” Then I went on in alone. Brentin was just saying, “This
is apparently the Erechtheum. There’s mighty little of it left; why
don’t they put it straight, anyway?”
You should just have seen their faces when they turned and saw
me. Lucy, who was looking very pale, ran tottering towards me with
a little cry, and nearly fainted in my arms. My sister followed, and
was soon on my other shoulder. Miss Rybot waved her parasol,
Forsyth and Hines cheered, and Arthur Masters gave a loud gone
away! All Brentin said was, with rather a forced smile, “Well, all
right, eh? Here you are. You got my telegram?”
We sat down on the fallen blocks of marble, and everybody
began talking at once. Where was Teddy, they asked, and why
wasn’t he with me? Had he really been caught, or had he, after all,
run straight away home in his fright?
As if trying to avoid a painful subject, “Why didn’t you come to
Venice, as we arranged?” I asked.
“We heard the French corvette was somewhere up in those
waters,” Brentin replied, “and thought it safer not. We should have
come to look for you here at once, only we calculated you couldn’t
possibly arrive till to-morrow. But what about Parsons? What’s the
matter with your telling us all about Parsons?”
“Poor Teddy!” I sighed, and everybody looked shocked. I had
scarcely made up my mind whether to say he was dead, or in prison
for life, when Teddy himself suddenly fell in among us on his hands
and knees. He looked so ghastly, with his white face and red cactus
scars—to say nothing of his extraordinary way of entering—that the
ladies began to scream, and Bob Hines fell over backward.
“Teddy!”
“Hush! Hush! Hush!” hissed Teddy. “Bailey Thompson!”
“Im-pawsible,” snarled Brentin. “He’s in Minorca.”
“I say it’s Bailey Thompson. I saw him from outside, just coming
in.”
“Alone?”
“Yes. Keep quiet!”
We all huddled close together and kept as still as death.
“I couldn’t be mistaken,” Teddy whispered. “He’s got on the same
clothes and carrying the shawl, and he was looking about him, just
as he used at Monte Carlo.”
“You don’t say!” said Brentin, looking scared. “What the plague is
he doing in Athens? We shall have all our trouble over again.” And
then, thinking he was not very polite, he added, “And how are you?
All right?”
“No thanks to you!” grunted Teddy, at which the unfeeling
Brentin began to chuckle.
“Somebody’s scratched your face well for you,” he laughed.
“Looks like marriage lines!”
We lay very still, hoping against hope Thompson wouldn’t think
the Erechtheum worth a visit; but the fact was he had looked in the
carriages outside and questioned the driver, and, from the cloaks
and what the man had said, made up his mind it was our party. So,
after peeping in at the Parthenon, he came straight across; we heard
his footsteps, the divisional tread, closer and closer. Then he
tumbled over a column, swore, and the next moment was inside
surveying us, huddled together like a covey of partridges, with an
expression I don’t find it at all easy to describe—it was such a
mixture of everything.
Poor creature, he had evidently suffered! His face was drawn, his
beard unshaved, and his forlorn eyes looked defiantly out from
under a heavily lined brow. His mouth was tight and grim, and yet
about the compressed lips there was an air of satisfaction, almost of
unholy mirth. When he saw us, ran his glance over us and noted we
were all there, netted for the fowler, flame leaped to his sombre
eyes. There was dead silence while he stepped majestically,
solemnly forward, threw his plaid shawl on a column, and
unbuttoned his dusty frock-coat.
“And how are you?” said Brentin, coolly. “Come to see over the
Acropolis?”
Thompson glared at him, and without replying sat down on his
shawl.
“How did you get here? Had a good voyage? Sakes alive, man,
what a hole in your boot!”
“Poor man!” whispered Lucy, “how fearfully tired and ill he looks.”
At so unexpected an expression of sympathy, the detective’s
expression suddenly changed. Poor wretch, he was worn out,
hungry, and depressed; humiliated and miserable, I suppose, at
being so egregiously outwitted; for his lip trembled, and, putting his
face in his dog-skin hands, he actually began to cry. I never felt so
ashamed of myself, so sorry for a man, in my life.
“Cry, baby, cry!” taunted Brentin. “Serve you thundering well
right—”
“Be quiet!” I sternly cried. Brentin scowled at me, while poor
Thompson began to search with blinking eyes for his handkerchief.
Then I went on, with real feeling in my voice:
“We are sorry, Mr. Thompson, for the way we have treated you,
but you must see there was no other course open to us. We were
entirely frank with you, but you were never frank with us. We
discovered your identity quite by accident, and took the advantage
we thought our due of the discovery.”
“Oh, all right, sir, thank you!”
“At any rate,” struck in the irrepressible Brentin, with a wink at
me, “you have the satisfaction of knowing you spoiled a fine piece of
work, which will now, I guess, be consummated by other more
imperfect hands than ours.”
“What!” said the detective, brightening. “You never even made
the attempt?”
“What do you take us for?” cried the ingenious and evasive
Brentin. “Make an attempt of that nature, with the sharpest
detective in old England on our heels? No, sir!”
Thompson looked pleased, and then, with sly malice, observed:
“But, after all, gentlemen, you might have done it with perfect
safety.”
“What!”
“With the most perfect safety, I assure you. I had not yet
communicated with the Monte Carlo police.”
“That so? But afterwards?”
“Oh, afterwards, I should have pinched you all, of course!”
“There you are!” cried Brentin; “we knew that, mighty well. No,
sir! There are no flies on us. You gave us a fright, Mr. Bailey
Thompson, and we, I guess, have given you one. But no real
damage has been done to either party. Let us cry quits. Your hand,
sir!”
The simple fellow shook his hand obediently, and, polite as ever,
bowed to the ladies. My sister he already knew. She smiled at him
and said:
“But how on earth have you got here, Mr. Bailey Thompson? We
all understood you were going to the Balearic Isles.”
“I know nothing of my original destination, madam,” the
detective replied. “I only know that after steaming for some few
hours in one direction, Mr. Van Ginkel suddenly bouted ship and
went full speed in the other.”
“But why, I wonder?”
“Some matter, I understood from the captain, connected with his
divorced wife.”
“The Princess Danleno,” said Brentin.
“Some such name. She had left Cannes and gone to San Remo,
and Mr. Van Ginkel was anxious to see her and effect a
reconciliation, so the captain told me. He is full of caprice, like all
invalids, and on the caprice seizing him he simply bouted ship
without a word. But first he had to get rid of me; so he carried me,
full speed ahead, to the southernmost point of Greece—somewhere
near Cape Colonna, I believe—and there he carted me ashore,
gentlemen, like a sack of coals.”
The poor man’s lip began to tremble again, and he looked round
our circle piteously for sympathy.
“Dear! dear!” murmured Brentin; “how like him! And never said a
word the whole time, I dare say?”
“Not one! That was early on Monday morning. Since then I have
been slowly making my way up the Morea with great difficulty and
discomfort, mainly on foot, and sometimes getting a lift in a country
wagon. At Nauplia I managed to secure a passage in a coasting
steamer, which, after a tempestuous voyage, has just landed me at
the Piræus. There I saw your yacht, gentlemen, and knew, of
course, you were in the neighborhood.”
“How did you manage about the language in the Peloponnese?”
asked Hines, curiously.
“Why, fortunately, I can draw a little,” replied the detective, who
was every moment recovering his spirits, “and anything I wanted I
drew. But, often as I drew a beefsteak or a chop, gentlemen,” he
said, plaintively, “I never got it. Nothing but eggs and a sort of
polenta, and once—only once—goat’s flesh, when I drew a
bedstead, in token that I wanted to sleep there. And the fleas,
gentlemen, the fleas!” he cried. “There is a large Greek flea—”
“Never mind that just now,” said Brentin, gravely. “There are
elegant and refined ladies present. The essential is you are safe, and
bear us all no malice. That is so, eh?”
“None in the world!” cried the good fellow. “But I shall be much
obliged if you will give me directions how to get home from the
Acropolis in Athens to Brixton. I have no money to speak of, and a
large hole in my right boot.”
“That will be all right, sir,” said Brentin, rising, with his grand air.
“Henceforth you are our guest. By-gones are by-gones, and we will
look after you till you are safely landed at Charing Cross.”
“Thence, by tram or ’bus, over Westminster Bridge,” murmured
Hines, as we all rose, shook ourselves, and prepared to descend.
“Well, all’s well that ends well,” cried Thompson. “But, all the
same, I rather regret, for all our sakes, the Monte Carlo business
was left untried.”
“Some other day, sir,” said Brentin; “some other day, when you
are enjoying your well-earned retirement, and an officer not quite so
plaguy sharp is in your place.”
The pleased detective walked jauntily on in front with the rest,
while Brentin, my sister, and I followed, Lucy clinging fondly to my
arm.
“But what are you going to do with him?” I whispered. “It is
ingenious to let him suppose the thing has not been done; but once
he gets on board the yacht he’s bound to discover all, and that he’s
been fooled again. Then it will be all up, indeed!”
“Some of you must take him home overland, on the pretence
there isn’t room for every one on the Amaranth.”
“But he must find it all out directly he gets to England, mustn’t
he?” said Lucy, softly.
“I hope to goodness he won’t come trooping over to Medworth
Square,” my sister observed. “I shall never hear the last of it from
Frank. And, after all, I’ve done nothing, have I?”
“True, O queen!” muttered Brentin, knitting his brows. “But by
the time he gets back the scent will be fairly cold. And the Casino
authorities are taking the sensible course of ignoring the whole
affair. That is so, isn’t it? No doubt, you’ve seen the papers.”
Yes, I said, I had, and that was their line.
“There you are, then! For the rest, we must simply trust our luck.
It has stood by us pretty well so far. Oh, and, by-the-way, what
about Mr. Parsons? How did you manage to get him out?”
I rapidly sketched my part in the affair, and made them all laugh
amazingly as I told them of my disguise and its accidental
resemblance to Lord B.
“Whether we are drunken men or fools,” laughed Brentin, “I
know not; but Providence has certainly looked after us so far in a
way that I may fairly call the most favored nation clause.”
“Quoti moris minus est, eo minus est periculi!” I quoted,
somehow happening to remember the sentence from my old Latin
grammar. “Which is the Latin, ladies, for ‘Where there is the less
fear, there is the less danger.’ ”
Lucy pressed my arm and smiled happily.
Just as we neared the carriages:
“By-the-way,” I asked, “what did it all tote up to?”
“The boodle?”
“Yes.”
“Just over one million four hundred and fifty thousand francs;
roughly speaking, fifty-eight thousand pounds of your money.”
“You’ll be back in Wharton Park, dearest,” I whispered, “before
the swallow dares!”
She pressed my arm again and smiled more happily than ever.
“The only thing that troubles me,” said my sister, “is how on
earth I am to establish an alibi to Frank’s satisfaction, in case there’s
a rumpus when we get back.”
“Alibis are old-fashioned nowadays,” I answered. “We shall have
to think of something else for you than an alibi.”
The unsuspicious Bailey Thompson was standing at one of the
carriage doors in a dandified attitude, making himself agreeable to
Miss Rybot.
As we drove away he again said—for after all he was human and
meant to be malicious—“But I do really wonder you didn’t do it,
gentlemen, after all!”
“Don’t torture us with remorse, Mr. Bailey Thompson, sir,” Brentin
cried; “the sense of neglected opportunity is hard to bear.”
“Well, all I can say is, I never saw an easier bit of work in my life,
and in my absence you were really perfectly safe. Those French
police are such utter fools, and as likely as not the Casino people
would have let you off. Come, now, confess! Don’t you regret it?”
“Sir,” said Brentin, loftily, “I regret nothing, and never did. All is
for the best in the best of all possible worlds.”
And the good detective couldn’t understand why, a few moments
later, Brentin was seized with a great roar of laughter. He explained
it was from seeing “Κοῦκ” in Greek letters over Cook’s offices; it
looked so droll! We all laughed heartily, too, and so drove up in
immense mirth and spirits to our hotel.
CHAPTER XXIII

WE ARRIVE SAFE IN LONDON AND GO TO MEDWORTH SQUARE—


BACK AT “THE FRENCH HORN”—NEWS AT LAST OF THE
AMARANTH—I INTERVIEW MR. CRAGE AND FIND HIM ILL

Very little remains to tell; but that little is of importance. Of our


journey home together (my sister, Lucy, Bailey Thompson, Parsons,
and I, the others sailing on board the yacht) I need say nothing, for
it was entirely pleasant and uneventful. Our luggage wasn’t even
robbed on the Italian lines; we felt the cold somewhat as we neared
home, and that was all.
At Charing Cross Thompson was evidently well-known to the
officials; he proclaimed us all his friends and above suspicion, so our
portmanteaus were barely looked at; everybody touched their hats
to him, and we felt quite royal in our immunities.
There we parted. Teddy jumped into a cab for Euston, to catch
the night express for his dear Southport; my sister, Lucy, and I went
off in a four-wheeler to Medworth Square; while the still
unsuspicious Thompson remained on the platform, bowing and
smiling. Once safely landed at Charing Cross, our duty to him was
plainly at an end. No doubt he would immediately go off to Brixton,
find his sister, Mrs. Wingham, and learn the truth; but what that
might mean to us I really neither knew nor cared. We had so far so
brilliantly succeeded that readers must not blame me if I continued
obstinately optimistic, and believed, whatever trouble might still be
in store for us, we should certainly somehow emerge from it
scathless and joyous.
“I hope,” my sister said, as we drove away, “he won’t think it
rude of me not asking him to come and call. After all, he’s not quite
of our world, and he would need such a deal of explaining, for Frank
always insists on knowing exactly who everybody is.”
“He won’t think of coming of his own accord, I suppose?”
whispered Lucy. “And, oh! I do so wish he wasn’t a friend of Mr.
Crage’s.”
“Lor’ bless you!” I philosophically remarked, “it’s even money we
none of us ever see or hear of him again.”
But we did, that day week exactly, when he turned up at “The
French Horn,” purple with ineffective rage, accompanied by his
dazed French confrère, Monsieur Cochefort.
In Medworth Square all was as usual. The Thursday evening
German band was playing the usual selection from that tiresome old
“Mikado,” and my sweet niece Mollie was soon tearing down the
stairs to welcome us.
“She watch for you every night, ma’am,” her Welsh nurse said;
“and last night she go down-stairs her best, and blow up Mr. Blyth
like anything for doing a door-bell ring exactly like yours, ma’am.”
My brother-in-law was very glad to get his wife back, and, having
been warned by letter, welcomed my dear Lucy with sufficient
warmth. How could he help it? Everywhere she went she won all
hearts. Brentin and Parsons both admired her desperately, and Bob
Hines, my sister told me, paid her more attention on the yacht
coming from Monte Carlo than he had ever been known to pay any
one before.
Even Forsyth, who is one of the most difficile men I know (unless
the young lady makes a dead set at him, when he thinks her lovely),
even he said to me, “That’s a real pretty girl, Vincent, and you’re a
very lucky man to get her;” while Miss Rybot once quite surprised
me by the warmth of her congratulation. “She’s so fresh and
unaffected, Mr. Blacker,” she said. “She’s like a breeze that meets
you at the end of a country lane when you come suddenly upon the
sea.” Which I thought both poetical and perfectly true—rather a rare
combination nowadays.
The next morning Lucy and I were off to Liverpool Street for
Nesshaven and “The French Horn.” As we drove up, and I saw the
familiar place once more, blinking in the soft February sunshine, just
as we had left it, I could scarcely believe all I had gone through in
the way of peril and adventure. Somehow, if one leaves a place for a
time, and has experiences of moment in the interval, one expects
those experiences to have had their effect elsewhere, too, even on
inanimate objects.
I felt older, wiser, more developed, more of a man, and I was
astonished to find the place quite unaltered and Mr. Thatcher looking
just the same as he came running out in his dirty old blazer. His
mother was at the window, gazing through the panes with the naïve
curiosity of a child at new arrivals. She kissed Lucy, and said to me:
“Well, here you are back safe, you bad young man. You’ve given us
a rare fright, I can tell you”—and that was all.
That same evening, when the ladies were safely abed, I had a
long talk with Mr. Thatcher in the bar parlor. After dear Lucy’s
escapade, we decided we might as well be married at once, without
waiting for Easter; and that, with the help of a license, the following
Thursday, February 6th, would be none too soon. For myself, apart
from other considerations, I thought it clearly wisest to get married
and clear out of the country, on a lengthy wedding-tour, as quick as
we could; so that, in case of search being made for me, as the head
and guiding spirit of the raid, I might, for some few months at any
rate, be non inventus.
Next, I delicately approached the subject of the repurchase of
Wharton Park. I told Mr. Thatcher we had been extraordinarily lucky
at Monte Carlo, and that, by a combination of rare circumstances, I
was the richer by £30,000 than when I started. He was shrewd
enough to listen in silence and ask no sort of question as to what
particular system I had pursued to enable me to return with so large
a sum. In fact, I scarcely gave him time to ask questions, I was so
rapid, hurrying forward only to the main point, whether Crage’s offer
were still open and we should still be able to get the old wretch out.
He told me that since Crage’s last visit and offer to marry Lucy he
had seen nothing of him, and, so far as he knew, the place was still
to be had. We could, if I liked, go up to the house in a day or two
and make inquiries cautiously, or write Crage a letter making him a
formal proposal.
To which I replied that, knowing something of human nature, I
judged it best, when we made our offer, to be prepared with the
actual sum in notes and gold to make it good; for, with a man like
Crage, combined of malice and craft, he would most likely try to
bluff and raise us unless he saw the very gold and notes before him,
beyond which, not having any more to offer, we were not prepared
to go.
“Very true,” said Thatcher. “There’s nothing like the ready to
tempt a man, as I know very well. Why, when I was in business—”
“Then all we can do,” I continued, cutting him short, “is to wait in
patience till the boodle—”
“The what?” said Thatcher, taking the pipe out of his mouth.
“It’s an American term—the money we have won, arrives. It’s
coming in the yacht, and should be here in a day or two now. Then
we’ll go up with it to the house, in a bag, and spread it out on the
table—”
“And I shall be back in Wharton Park again!” cried Thatcher.
“Gracious powers! Who would have thought it possible? And, of
course, it will be settled on Lucy. Me for life, and then Lucy. How
delighted my poor old mother will be!”
“Yes,” I said, “and that your name may be perpetuated, I will add
it to my own. Father-in-law, here’s health and prosperity to those
two fine old English families, the Thatcher-Blackers!”
So there was nothing we could do but wait in patience for the
arrival of the Amaranth. It was tedious, anxious work, for though I
never doubted all would be well, yet Bailey Thompson’s portentous
silence somewhat alarmed me; and as the days passed, and neither
he nor the yacht gave any sign of their existence, my nerves began
to get unstrung, and I grew worn and irritable.
Fortunately, as often happens in the early days of February, the
weather was beautifully fine; so fine that the more flatulent class of
newspapers were full of letters from country correspondents, who
were finding hedge-sparrows’ eggs and raspberries in their gardens,
and the usual Lincolnshire parson broke into jubilant twitterings over
his dish of green pease. Otherwise, I don’t think I really could have
borne it.
At last, late on the Tuesday evening, came a telegram from
Brentin at Southampton—“Safe, will arrive to-morrow”—and I began
to breathe a little easier. But not a word of any sort from Bailey
Thompson, neither a reproach nor a threat; till I felt like that
Damocles of Syracuse who, though seated on a throne, was yet
immediately under a faintly suspended sword. For here was I, on a
throne, indeed—the throne of dear Lucy’s pure and constant
affection—and yet!—at any moment!—
Dramatically enough, the sword fell on my very wedding morning
—on its flat side, happily—giving me a shock, but no cut of any sort,
as I am now briefly going to tell.
The next morning came another telegram from Brentin in
London, to say he would arrive at six and beg he might be met. All
was well, he wired, adding “Any news Thompson?”
I wired back to the “Victoria” there was none: “bring boodle with
you;” and then I went off and found Thatcher.
For always I had had the fancy to pay old Crage out of the place
and be married on the same day, and here was now my chance. We
were to be married in Nesshaven Church, in the grounds of Wharton
Park, at twelve; what was to prevent us, I said to Thatcher, from
walking on up to the house first with £30,000, completing the
purchase, and hasting to the wedding afterwards? Thence back to
“The French Horn” for a light lunch, afterwards catch the half-past-
two train for Liverpool Street, and so to Folkestone in the evening.
There was nothing to prevent it, said Thatcher, who for the last
two days had gone about in a triumphant, bulging white waistcoat;
only it would require rather delicate handling, all to be done
successfully. Crage should be prepared, for instance, he thought; for,
notwithstanding the sight of the money, the sight of dear Lucy in her
happy wedding radiance might turn him sour, and he might after all
refuse to complete. What was to prevent one of us, he said—
meaning, of course, me—going up to the house and sounding the
old man first? Then we should know exactly how we stood, and
what chance there was of our money being accepted.
Now, for the last week nothing had been seen of the old man,
and rumors had reached us, chiefly through the gardener, he was
very ill. He hadn’t been to church for more than a month, and at
church he had always been a very regular attendant; not so much
because he had any real religion in him as that he might aggravate
the parson by catching him up loudly in the responses, and barking
his way harshly through the hymns a good half-line behind the rest
of the congregation. Indeed, the chief attraction, I fear, at
Nesshaven Church was old Crage and his nauseous eccentricities,
and people who had heard how he had once lighted up his pipe
during the sermon and sat there sucking at it in the Wharton pew,
came from miles round in the hope he would enliven the discourse
by doing it again.
Nor had he been seen about the grounds, nor stumping down to
the inn, as he mostly did once a week to insult the inmates; in short,
the end that comes to us all—good, bad, and indifferent—was clearly
coming now to him, and if business were ever to be done, it must be
done speedily and at once.
So, before Brentin came, early on the Wednesday afternoon, I
trudged alone up to the house. There wasn’t a sign of life in it, and
when I rang at the hall door I heard the heavy bell clanging away
down the empty passages and cold servants’ quarters as in the
depths of an Egyptian tomb. I rang and rang, until at last I heard
shuffling footsteps approach. From the other side of the door came
stertorous breathing and wheezing, and the undoing of a chain; then
a burglar’s bell was taken off and fell with a jangle on the stone floor
inside, and at last the door was pulled ajar.
Poor old Crage! He looked out at me with his wicked, frightened
old face, pinched, haggard, unshaven, dirty; terror-struck, as though
he feared, I were Death himself who had been knocking at the door.
He was in his shirt and trousers and a frowzy old dressing-gown,
and his bare, bony feet were thrust in worn leather slippers. As he
breathed his throat rattled dismally, and his long hand, with the
thick, muddy veins, shook so he couldn’t fold the dressing-gown
round his gaunt, corded, bare throat.
“Hullo, young cockney!” he croaked; “what’s to do?”
“How are you, Mr. Crage?” I asked, shocked at the old man’s
fallen, forlorn look.
“Very bad!” he whispered, his rheumy eyes blinking with watery
self-pity.
“Is there anybody looking after you?”
“No—no—thieves! all thieves!—don’t want ’em.”
Then he made as if he would shut the door.
“I came up to see you on business,” I said; “about selling the
house.”
“No business to-day,” he croaked. “Too ill. Come to-morrow—any
time. Come to-morrow.” And with that he shut the door in my face.
I heard him shuffling away across the hall, kicking the fallen bell
with a tinkle along the floor, and then, as I turned to go, I heard him
fall and groan. I ran in hastily, and with great difficulty managed to
get him on his feet again. He stood there for some few minutes,
clutching me and rattling his throat; then, hanging on my arm,
dragging me along with him, he paddled off down a short dark
passage towards a half-open door, pushed it wide, and pulled me
after him into the great empty drawing-room.
The blinds were down, and the fading February sun gleamed in
on the bare worn carpet. In front of the fine fireplace, with a little
dying wood-fire in it, stood an arm-chair, with a small table beside it.
A candle and snuffers were on it, and a plate of stale bread-and-
butter. On the high mantel-piece was a medicine bottle, full and
corked.
He sank back into his chair, and lay there, breathing heavily, with
his eyes closed.
“But is there nobody looking after you?” I asked, and he made
some twitching movement with his fingers.
Just at that moment in flounced the gardener’s wife, drying her
hands on her apron. She was a big, handsome, shameless-looking
creature, with a naming eye and a hard, high color on her stiff
cheeks.
“Now you’ve been moving yourself about again!” she cried,
bending over him.
Crage opened his eyes and looked up at her maliciously.
“He came up on business,” he whispered.
“You’re a pretty man to do business, ain’t you?” she sneered.
“No, not to-day,” he mocked. “Too ill. All right to-morrow. Tell the
genelman to come to-morrow, early. Quite well to-morrow.”
I turned to go, and Crage, raising himself in his chair, rasped out:
“Bring the money with you, young cockney, or no business. Mind
that!”
The woman followed me to the door.
“Has he got a doctor?” I asked.
“Doctor Hall came once,” she said, “but he won’t do anything he
tells him. He won’t take his medicine and he won’t go to bed. He
says he’ll die if he goes to bed. He sleeps all night in that arm-chair
in the drawing-room. If he don’t die soon, I shall; I know that very
well. If you’ve got any business to do with him, you’d better come
early in the morning. He can’t last much longer.”
And with that she closed the door on me, and I heard her putting
up the chain again and the burglar’s bell as I went away down the
weedy gravel path.
CHAPTER XXIV

ARRIVAL OF BRENTIN—MY WEDDING-DAY—WE GO TO WHARTON


—BAILEY THOMPSON AND COCHEFORT FOLLOW US—WE
FINALLY DEFEAT THEM BOTH

Brentin was in “The French Horn” by a quarter to seven, and,


rather to my surprise, he came alone. I thought Hines or Masters
would surely have come with him; but no, he said, except for
Forsyth, they had all parted company at Southampton. Masters and
Miss Rybot had gone to Sea View, where they were to be married
almost immediately, and Hines had gone off to stay with a married
sister at Bournemouth. Forsyth alone had travelled up to town with
him, and then gone on straight to Colchester to take up his
neglected regimental duties. So I wrote out a telegram to be sent
first thing in the morning, begging him to come over and be my best
man.
And the boodle? Brentin winked and, with his hands on his
knees, began to laugh, like the priest in the Bonne Histoire.
“Some of it has melted, sir,” he joyously cried. “Your friend Hines
has got his, and Mr. Parsons, by this time, is toying with ay
registered letter way up in Southport. I have handsomely
recompensed Captain Evans and the crew; they have, no doubt,
been tanking-up and painting Portsmouth red all the time. I have
reimbursed myself for the yacht and other trifles, and there now
remains the £30,000 for your young lady’s ancestral home, and
some £20,000 for the hospitals and so on. To-morrow, sir, we will
draw up a list of the most deserving of them.”
“You have the money with you?”
“Yes,” he said; it was all safe in what he called his grip, or hand-
bag, and quite at my service. I told him of my desire to complete the
purchase immediately before the marriage was solemnized, and then
we fell to talking of Bailey Thompson and his strange silence.
“Why, the man is piqued, sir,” said Brentin; “that’s what he is,
piqued. Beyond saying that, I do not propose to give him ay second
thought. He is mad piqued, and that’s all there is to it!”
So I tried to feel completely at my ease, and managed to spend a
very happy evening in the bar parlor, Lucy playing to us and Brentin
occasionally bursting into raucous song. Now, when I think of him, I
like best to remember him as he was that evening, forgetting his
harder, commoner side, when he so outrageously proposed to desert
poor Teddy; even refusing (as I forgot at the time to mention) to
allow the cannon to be brought into play for his rescue by shelling
the rooms. He was infinitely gay and amusing, only finishing up the
evening, after dear Lucy’s retirement, with a long and violent dispute
with Mr. Thatcher on the vague subject of the immortality of the
soul. Thatcher believed he had a soul and would live forever, in
another, happier sphere; Brentin denied it, could see no sign of
Thatcher’s soul anywhere; so I left them trying to shout each other
down, both speaking at once.
I retired to rest with many solemn, touching thoughts. The last
night of bachelorhood gives rise to at least as much deep reflection
as that of the young maiden’s; more, in fact, so far as the bachelor
himself is concerned. I thought over it all so long and deeply I at last
got confused, and when I woke, the bright February sun was
streaming in on my best clothes and the bells from Nesshaven
Church were ringing.
All the morning those bells rang out their happy, irregular peal.
“The village church beneath the trees,
Where first our marriage vows were given,
With merry peal shall swell the breeze,
And point with slender spire to heaven!”

Only, to be exact, Nesshaven Church has no spire, but a sunk,


old, bird-haunted, ivy-clad tower.
It was Thatcher’s idea to set the bells going early and keep them
at it all day; you see, they rang not only for the marriage of his only
child, but for his return to their ancestral home; and, when they
showed any sign of flagging, Thatcher listened with a pained
expression, and cried, “Why, surely they’re not going to stop yet!
Run, Bobby, or Harriet, or George, my man!”—or whoever happened
to be handy—“and tell ’em to keep ’em going, and give ’em this from
me. Here, Vincent, my boy, have you got half-a-crown?”
By ten o’clock we were all dressed and ready, waiting only for
Forsyth. Soon after ten he came, and the procession started. It was
a lovely day again, mild and sunny, and, in true country-wedding
fashion, we all set out to walk. Lucy, looking perfectly sweet in gray,
was on her father’s arm, and the old lady, in black silk, on mine;
while Brentin, carrying his grip, with the boodle in it, and that good
little chap, Forsyth, brought up the rear.
The old lady, who within the last three months seemed to me to
have failed a good deal, mentally, at any rate, stepped out right well,
hanging lightly on my arm. At first she thought we were going
straight to the church, and couldn’t understand why we left it on our
right and went on up to the big house. Then she seemed to think it
quite natural, and that the place was hers again, and began talking
of her early days, when first she was married and came to Wharton
as a bride. Once or twice, indeed, she called me “Francis,” her
husband’s name, who died in 1850, and drew my attention to the
scandalous, weedy state of the walks.
“And this is what we pay good wages for!” she cried. “These men
must be spoken to about it, my dear, immediately.”
The gardener’s wife, who opened for us the hall door, was
astonished at our numbers.
“Why, what a crowd of you!” she said.
The old lady passed her haughtily.
“Come, Tom!” she cried to Mr. Thatcher. “We’ll go up-stairs and
have tea in my room. Come, Lucy!”
And up-stairs, up the bare stone staircase, they went, for, as I
whispered to Thatcher, it was just as well the ladies should be out of
the way while we did our business.
In the great empty drawing-room we found old Crage ready
waiting for us. He had dressed himself up in rusty attorney black for
the occasion, and the plain kitchen-table was neatly spread with
bundles of documents, title-deeds, and so forth.
As the woman showed us in, she told me he had been up all
night rummaging in his old tin boxes, talking and mumbling to
himself. Now he seemed quite spry and well again. I could scarcely
believe, as he sat there alert and attentive, he was the same
stricken, shambling old hunks I had seen the previous afternoon,
dragging himself about, senile and dying. Such is the power of the
will and the business instinct, prolonged even to the verge of the
grave!
Brentin, who, as usual, took everything into his own hands,
adopted the simplest method of dealing with him. Crage received us
in complete silence, and no one spoke a word, while Brentin opened
his grip and took out the notes and two or three little bags of gold.
The gold he emptied into heaps and piled them round the notes.
Then, “Thirty thousand pounds,” he said, with a smile—“thirty
thousand pounds! Is it a deal?”
Crage sat bolt upright, with his hand curved over his ear.
“For the entire property?” he asked.
“For the entire property. Is it a deal? Thirty thousand pounds,
neither less nor more.” And he emptied the grip and shook it, to
show that not a penny more remained.
“It’s worth more in the open market,” said Crage, cautiously.
“Then take it to the open market. We have no time to haggle. My
client is on his way to be married. Good-day.” And with that he
began to scrape the notes and gold together again.
“Hold hard!” cried Crage. “Don’t hurry an old man.”
“We’ll give the old man three minutes,” said Brentin, coolly
pulling out his watch.
We were all three of us grouped round the table, watching Crage,
with our backs to the door. The woman stood at his elbow, and we
could, in the complete silence, hear the heavy, swinging tick-tick of
Brentin’s large old-fashioned watch.
“Half time!” cried Brentin, when suddenly we heard steps outside
in the hall. I had just time to recognize Bailey Thompson’s even,
divisional tread, when he pushed the door open and stepped in. He
was dressed as usual, and behind him came a gentleman in a tight
black frock-coat, an evident Frenchman, thin, dark, and wiry, with a
withered face, like a preserved Bordeaux plum.
“One moment, if—you—please, gentlemen!” cried Bailey
Thompson, as he stepped up to the table.
My heart gave a bound, and Forsyth started and said, “Ho!” but
the unabashed Brentin merely politely replied, “One moment to you,
sir. We will attend to you directly.—Time’s up, Mr. Crage! is it or is it
not a deal?”
Bailey Thompson laughed. “Cool as ever, Mr. Brentin, I see,” he
said. “But don’t you think this amusing farce of yours has gone on
long enough? It has been successful so far, as I always thought it
would be!”
“You’re mighty good!”
“We have no desire to be unduly hard on you.”
“You are mighty particular good!”
“The Casino authorities are, on the whole, willing to regard you
as eccentric English gentlemen of position, who have played a very
cruel practical joke on them.”
“That so?”
“That is so. This is their representative, Mossieu Cochefort.”
“Enchantay!” cried Brentin, with a bow.
“He is charged to say that, on the due return of the money you
have sto—ahem!—carried off, and an undertaking from you in
writing that you none of you ever visit the place again, on any
pretence, they are willing to forego criminal proceedings, and no
further questions will be asked.”
“Oh, come off it!” cried Brentin, laughing.
“Otherwise,” continued Bailey Thompson, with great gravity, “I
must ask you, Mr. Blacker, and Mr. Forsyth here, to follow me to the
cab in waiting at the door, and return with us to London as our
prisoners.”
“In short, sir,” said Brentin, swelling with indignant importance,
“you invite us, eccentric gentlemen of recognized position, to
compound a felony!”
Thompson shrugged his shoulders, and Mossieu Cochefort looked
puzzled.
“Be ashamed of yourself, sir!” Brentin cried, his voice ringing
scornfully through the empty room. “Be ashamed of yourselves, you
and Mossieu Cochefort, and give over talking through your hat! Mr.
Crage, if you will write out a formal receipt we will look upon the
affair as settled. The formal transfer can be effected later.”
“Aye, aye!” mumbled Crage, and, with his eyes on the money,
began fumbling in the inside pocket of his rusty black coat for the
receipt.
“Gentlemen!” cried Thompson, with affected earnestness, “I warn
you! I very solemnly warn you—”
“Oh, come off it, Mr. Bailey Thompson, sir!” was Brentin’s
emphatic and withering reply; “come off it, and shut your head. We
have long had enough of you and your gas. For my part, my earnest
advice to you and Mossieu Cochefort is that you kiss yourselves
good-bye and go your several ways. And tell your amazing Casino
Company from us that the only undertaking we will give them is not
to come and do it again in the fall. To repeat a success is always
dangerous; and next time, no doubt, you will all be better prepared.
—Now, Mr. Crage, the receipt!”
“Qu’est ce qu’il a dit?” asked the puzzled Frenchman, as
Thompson, fuming and fretting, dragged him off to the window to
explain.
Meantime old Crage had produced his receipt, already written
and signed, and, handing it over, with trembling, eager fingers was
beginning to count the notes.
“Ten fifties—ten thousands—ten twenties,” he was mumbling,
“nice clean notes—beautiful crisp notes—he won’t get ’em back from
me, if that’s what he’s after! No, no, not from Crage. Crage wasn’t in
Clement’s Inn for forty years for nothing. Ten more fifties!—” So he
went on mumbling to himself, and stuffing the notes away in a
broken old pocket-book, while Brentin handed me over the receipt,
and snapped his grip with a click.
“It’s all right,” he whispered. “We’ve bluffed ’em. Keep cool.”
“Hadn’t you better let me keep ’em for you!” whined the woman,
bending over Crage’s chair. “You’ll only lose ’em. Give ’em me to take
care of for you, there’s a dearie!”
To which pathetic appeal the old man paid no sort of heed, but
pushed the pocket-book into his inside breast-pocket, with many
senile signs of satisfaction and joy.
“And now!” cried Brentin, in imperturbable high spirits, “the
wedding-procession will reform, and proceed to the church for the
tying of the sacred knot. Mr. Bailey Thompson—Mossieu Cochefort—
we shall be glad if you will join us, and afterwards, at ‘The French
Horn,’ to a slight but high-toned repast. Good-day, Mr. Crage; take
care of yourself and your money. Let us hope that when the robins
nest they will find you in your usual robust health. Mossieu Cochefort
—Mr. Bailey Thompson—if you will kindly follow us—”
But a sudden access of fury seemed to have seized the usually
calm little detective; he was stamping his feet, waving his arms,
almost foaming at the mouth.
In execrable French, Stratford-atte-Bow-Street French, he began
to swear aloud he would have nothing more to do with it, that he
had done his best, that he had never yet had dealings with the
French police but they hadn’t muddled it; for his part, his work was
finished, and he was going home.
“Here they are!” he cried, “three of them, all ready for you. Will
you have them, or won’t you? Les voilar! Nong? Vous ne les voulay
pas? Then if you don’t want them, why the ——” (dreadful bad
word!) “did you bring me off down here?” he yelled, breaking into
profane English.
“Mais, voyons! voyons!” murmured the startled and conciliatory
Cochefort.
“Damn your voyons!” Bailey Thompson screamed. “If you don’t
want them, and won’t take them, do the rest of it yourself, the best
way you can. I wash my hands of it. Good-day, gentlemen, and
thank your lucky stars for the imbecility of the French police!” and
with that he rushed to the door, through the hall, and out into his
cab. As he pulled the hall door open I heard the wedding-bells come
surging in with a new burst of joy.
“Mais, mon ami!” cried Cochefort, as Thompson tore himself
away, “ne me laissez pas comme ça!” and with much gesticulation
prepared to follow.
But Brentin sagely stopped him. “Restay, Mossieu Cochefort!” he
said, graciously; “Restay avec nous. Tout va biang. Restay!”
“Mais, quel cochon!” cried the angry Cochefort, stretching out his
black kid hands, and shaking them in Bailey Thompson’s direction.
“Ma parole d’honneur! a t’on jamais vu un pareil sacré cochon!”
“C’est vrai!” said Brentin. “Mais il est toujours comme ça. Vous
savvy, il n’est pas gentilhomme. Nous sommes tous gentilhommes.
Nous vous garderong et vous traiterong tray biang. Restay!”
So Mossieu Cochefort allowed himself to be comforted, and
restay’d. We took him with us to the church, and did him right well
at lunch, and then, so forlorn and downcast the poor creature
seemed, Lucy and I carried him off with us up to town, if only out of
kindness, to put him on his way back to Monaco.
On the way up in the train he confessed to me his only
instructions had been to try and get the money back, and that if he
couldn’t manage that, or part of it, he was directed not to think of
embarrassing the authorities by taking us all in charge. I could
conceive, he said, that the authorities didn’t want to be made the
laughing-stock of Europe by having to try us, nor to add to their
already heavy expenses by keeping us in prison—nearly all quite
young men—for the term of our natural lives. He hadn’t been able
fully to explain all this to Bailey Thompson: the man was such a
lunatic, he said, and so obstinate: and besides, from the moment of
his arrival Bailey Thompson had ridden the high horse over him, and
proudly declaring he didn’t require to be taught his duties by a
foreigner, had immediately carried him off down to Nesshaven,
scarcely allowing him once to open his mouth all the way.
At Liverpool Street he seemed more lost, poor wretch, than ever.
He knew no single word of English, and looked at us so pathetically,
as we stood on the platform together, our soft hearts were touched.
So we made up our minds to carry him along with us to Folkestone,
dine him at the “Pavilion,” and afterwards see him safe on board the
night-boat for Boulogne.
It was droll, all the same, this carrying a French detective about
with us on our wedding-day; but the man was so truly grateful I
have never regretted it. We gave him a good dinner at the hotel,
and at ten o’clock walked him out on to the pier for his boat. He
made me a little speech at parting, declaring I had treated him “en
vrai camarade,” and that if ever I wanted to come to Monte Carlo
again I was to let him know and he would see I came to no harm.
To Lucy he presented all his compliments and felicitations on
securing the affection of “un si galant homme!” and then, with a
twenty-pound note I slipped into his hand at parting, bowed himself
away, and was soon lost to sight in the purlieus of the second cabin,
whither he went prepared to be dreadfully sick, smooth and calm as
the night was.
As Lucy and I strolled back to the hotel, arm-in-arm, we both
were silent.
At last, just as we got back and heard the steamer’s final
clanging bell and despairing whistle, “I can’t make out, really,
whether you’ve all done right or wrong,” she whispered, softly; “but
this I know, dearest, you have been most extraordinarily lucky.”
To which simple little speech I merely pressed her arm, by way of
showing how thoroughly I agreed with her.
CONCLUSION
This is the true account of our raiding the tables at Monte Carlo,
done the best way I could.
For the rest, I may just mention poor old Crage died before the
end of the month, and by Easter Mr. Thatcher and his mother were
safely installed in Wharton Park. Arthur Masters was married to Miss
Rybot in April, Forsyth is to do the same to a widow (so he says) in
September, Bob Hines is very flourishing with his new gymnasium
and swimming-bath—just about finished now, as I write, at the end
of June—and Parsons is, I believe, at Southport, parading Lord
Street as usual in breeches and gaiters.
As for Brentin, I never saw him again, for by the time Lucy and I
had returned from our honeymoon he was back in New York. But I
heard from him the other day—a long, rambling letter, in which he
told me he had sold the Amaranth to Van Ginkel, for his wife the
Princess Danleno, whom he had remarried, and with whom, on
separate vessels, he was sailing about the Greek Archipelago—
probably in belated search for Bailey Thompson. He concluded by
begging me to think of something “snappy” we could do together in
the fall, ending finally by writing: “What’s the matter with our going
to Egypt and turning the Nile into the Red Sea? A communicative
stranger, an Englishman, by his accent, assures me there is just one
place where it can be done. Think it over, sonny, and if you decide to
do it, count on me. Sincerely, Julius C. Brentin.”
I would write more, only Lucy is calling to me from the hay-field,
the other side of the ha-ha of Wharton, where I have come to finish
this work in retirement.
“Around my ivied porch shall cling
Each fragrant flower that drinks the dew,
And Lucy at her wheel shall sing
In russet gown with ’kerchief blue.”

As my dear Lucy says, I really am, and always have been, a most
extraordinarily lucky man.
THE END
TRANSCRIBER NOTES
Misspelled words and printer errors have been corrected. Some
words are hyphenated by the author for emphasis.
Inconsistencies in punctuation have been maintained.
*** END OF THE PROJECT GUTENBERG EBOOK THE SACK OF
MONTE CARLO: AN ADVENTURE OF TO-DAY ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like