Python for Offensive PenTest - Hussam Khrais - E-Book

Python for Offensive PenTest E-Book

Hussam Khrais

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Python is an easy-to-learn and cross-platform programming language that has unlimited third-party libraries. Plenty of open source hacking tools are written in Python, which can be easily integrated within your script.

This book is packed with step-by-step instructions and working examples to make you a skilled penetration tester. It is divided into clear bite-sized chunks, so you can learn at your own pace and focus on the areas of most interest to you. This book will teach you how to code a reverse shell and build an anonymous shell. You will also learn how to hack passwords and perform a privilege escalation on Windows with practical examples. You will set up your own virtual hacking environment in VirtualBox, which will help you run multiple operating systems for your testing environment.

By the end of this book, you will have learned how to code your own scripts and mastered ethical hacking from scratch.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 207

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Python for Offensive PenTest

 

 

A practical guide to ethical hacking and penetration testing using Python

 

 

 

 

 

 

 

 

 

 

 

Hussam Khrais

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Python for Offensive PenTest

Copyright © 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: David BarnesAcquisition Editor: Namrata PatilContent Development Editor: Dattatraya MoreTechnical Editors: Nirbhaya Shaji and Sayali Thanekar Copy Editor: Laxmi SubramanianProject Coordinator: Shweta H BirwatkarProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Jisha ChirayilProduction Coordinator: Arvindkumar Gupta

First published: April 2018

Production reference: 1250418

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-897-9

www.packtpub.com

mapt.io

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 www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, 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

Hussam Khrais is a senior security engineer, GPEN, and CEHHI with over 7 years of experience in penetration testing, Python scripting, and network security. He spends countless hours forging custom hacking tools in Python. He currently holds the following certificates in information security:

GIAC Penetration Testing

(

GPEN

)

Certified Ethical Hacker

(

CEH

)

Cisco Certified Network Professional - Security

(

CCNP Security

)

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com 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

Title Page

Copyright and Credits

Python for Offensive PenTest

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Warming up – Your First Antivirus-Free Persistence Shell

Preparing the attacker machine

Setting up internet access

Preparing the target machine

TCP reverse shell

Coding a TCP reverse shell

Server side

Client side

Data exfiltration – TCP

Server side

Client side

Exporting to EXE

HTTP reverse shell

Coding the HTTP reverse shell

Server side

Client side

Data exfiltration – HTTP

Client side

Server side

Exporting to EXE

Persistence

Making putty.exe persistent

Making a persistent HTTP reverse shell

Tuning the connection attempts

Tips for preventing a shell breakdown

Countermeasures

Summary

Advanced Scriptable Shell

Dynamic DNS

DNS aware shell

Interacting with Twitter

Parsing a tweet in three lines

Countermeasures

Replicating Metasploit's screen capturing

Replicating Metasploit searching for content

Target directory navigation

Integrating low-level port scanner

Summary

Password Hacking

Antivirus free keylogger

Installing pyHook and pywin

Adding code to keylogger

Hijacking KeePass password manager

Man in the browser

Firefox process

Firefox API hooking with Immunity Debugger

Python in Firefox proof of concept (PoC)

Python in Firefox EXE

Dumping saved passwords out of Google Chrome

Acquiring the password remotely

Submitting the recovered password over HTTP session

Testing the file against antivirus

Password phishing – DNS poisoning

Using Python script

Facebook password phishing

Countermeasures

Securing the online account

Securing your computer

Securing your network

Keeping a watch on any suspicious activity

Summary

Catch Me If You Can!

Bypassing host-based firewalls

Hijacking IE

Bypassing reputation filtering in next generation firewalls

Interacting with SourceForge

Interacting with Google Forms

Bypassing botnet filtering

Bypassing IPS with handmade XOR encryption

Summary

Miscellaneous Fun in Windows

Privilege escalation – weak service file

Privilege escalation – preparing vulnerable software

Privilege escalation – backdooring legitimate windows service

Privilege escalation – creating a new admin account and covering the tracks

Summary

Abuse of Cryptography by Malware

Introduction to encryption algorithms

Protecting your tunnel with AES – stream mode

Cipher Block Chaining (CBC) mode encryption

Counter (CTR) mode encryption 

Protecting your tunnel with RSA

Hybrid encryption key

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Python is an easy-to-learn cross-platform programming language that has unlimited third-party libraries. Plenty of open source hacking tools are written in Python and can be easily integrated within your script. This book is divided into clear bite-size chunks, so you can learn at your own pace and focus on the areas that are of most interest to you. You will learn how to code your own scripts and master ethical hacking from scratch.

Who this book is for

This book is for ethical hackers; penetration testers; students preparing for OSCP, OSCE, GPEN, GXPN, and CEH; information security professionals; cyber security consultants; system and network security administrators; and programmers who are keen on learning all about penetration testing.

What this book covers

Chapter 1, Warming up– Your First Antivirus-Free Persistence Shell, prepares our Kali Linux as the attacker machine. It also prepares out a target and gives a quick overview of the TCP reverse shell, the HTTP reverse shell, and how to assemble those.

Chapter 2, Advanced Scriptable Shell, covers evaluating dynamic DNS, interacting with Twitter, and the use of countermeasures to protect ourselves from attacks.

Chapter 3, Password Hacking, explains the usage of antivirus free loggers, hijacking the KeePass password manager, Firefox API hooking, and password phishing.

Chapter 4, Catch Me If You Can!, explains how to bypass a host-based firewall outline, hijack Internet Explorer, and bypass reputation filtering. We also interact with source forge and Google forms.

Chapter 5, Miscellaneous Fun in Windows, focus on exploiting vulnerable software in Windows and different techniques within privilege escalation. We'll also look into creating backdoors and covering our tracks. 

Chapter 6, Abuse of Cryptography by Malware, provides a quick introduction to encryption algorithms, protecting your tunnel with AES and RSA, and developing hybrid-encryption keys.

To get the most out of this book

You'll need an understanding of Kali Linux and the OSI model. Also, basic knowledge of penetration testing and ethical hacking would be beneficial.

You will also need a 64-bit Kali Linux and a 32-bit Windows 7 machine with Python installed, on Oracle VirtualBox. A system having a minimum of 8 GB RAM is recommended.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

 

www.packtpub.com

.

Select the

 

SUPPORT

 

tab.

Click on

 

Code Downloads & Errata

.

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 https://github.com/PacktPublishing/Python-for-Offensive-PenTest. 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 https://github.com/PacktPublishing/. 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: https://www.packtpub.com/sites/default/files/downloads/PythonforOffensivePenTest_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: 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: "Now, if you pay a close attention to the service name which gets created by Photodex software which is ScsiAccess."

A block of code is set as follows:

if 'terminate' in command: # If we got terminate command, inform the client and close the connect and break the loop conn.send('terminate') conn.close() break

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

apt-get install idle

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: "Go to Advanced system settings | Environment Variables."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] 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 [email protected].

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 www.packtpub.com/submit-errata, 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 [email protected] 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 authors.packtpub.com.

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 packtpub.com.

Warming up – Your First Antivirus-Free Persistence Shell

Nowadays, security solutions such as firewalls, IPS, and sandboxing are becoming more and more advanced to prevent and detect cyber-attacks. So, being an advanced hacker requires you to code your own script and tools to bypass these security solutions.

The following topics will be covered in this chapter:

Preparing the attacker machine

Preparing the target machine

TCP reverse Shell

HTTP reverse Shell

Persistence

Tuning connection attempts

Tips for preventing a shell breakdown

Countermeasures

Preparing the attacker machine

In this section, we will prepare our Kali Linux machine as the attacker. Note that we are assuming that the operating system is already set up in VMware or VirtualBox. As of now, we will be using VirtualBox for all our chapters. 

We can check the version of any Linux OS by running the following cat command to display the content from the file /etc/os-release, which contains OS distribution data. We will be using Kali Linux version 2018.1, as you can see from the following screenshot:

It doesn't matter what your Kali version is. For this book, we will be using the latest version available at the time of writing. Since, by default, Python is preinstalled in every Linux distribution, we can get the version details from either the interactive shell by running the command python or by using python -V, as shown in the following screenshot: 

We will be using Python 2.7.14+ for now, which came preinstalled with our Linux version.

So, let's go for networking a little bit. In this chapter, the Kali IP is 10.0.2.15. We can check the Kali IP by running the ifconfig eth0 command. This will return the network interface configuration as shown here: 

Setting up internet access

To set up the internet on our system, we just need to change the network mode to Network Address Translation (NAT) in VirtualBox. NAT mode will mask all network activity as if it came from your host OS, although VirtualBox can access external resources. To do this, perform the following steps:

Click on the 

Devices

menu from VirtualBox's menu bar

Go to

Network

and select

Network Settings

Select the network mode as 

NAT

 and click on

OK

as shown in the following screenshot:

Once you perform the preceding steps, you should be able to reach the internet, as long as the VirtualBox host does. You can check internet access by running ping 8.8.8.8 from the terminal.

Now, if you don't have a GUI compiler for Python, you can just install it using the following command:

apt-get install idle

Once it's installed, let's do a quick print program using IDLE (using Python-2.7),which we installed using the previous command. Open a new Python file and type print ('hello there'). Run the program and save it on the desktop. Once you finish accessing the internet, you now need to change the network mode back to Internal Network so that we can reach out to our Windows target. This is shown in the following screenshot:

Note that the Windows target globally machine is sitting on the same internal network as Kali attacker globally machine, intnet, here.

And, as a last step, we should verify that we still got the same IP address, which is 10.0.2.15 by running ifconfig in the terminal. 

if the IP changes, you can change the IP back by running ifconfig eth0 10.0.2.15.

Preparing the target machine

In this section, we will be preparing our target. We are using a 32-bit Windows 7 machine as our target. We will begin by installing Python 2.7.14+ version from https://www.python.org/downloads/. After you begin the installation, you'll notice that Python will install other handy tools such as pip and easy_install. We will be using pip to install third-party libraries later on.

Similar to what we have done in Kali, we will create a quick and simple Python script just to make sure that everything is working fine. Create a new file. Type print ('hi'), run the script, and save it to the desktop. After this, we need to add Python to our path, so we can start an interactive mode or interactive shell anywhere from the command line. Open a command line and type python; you will see that Windows does not recognize the python.exe application by default, so we've got to add that manually.

Perform the following steps to achieve this:

Go to

Advanced system settings

|

Environment Variables.

In

System Variables

, scroll down until you reach the variable

Path

. You will need to append the Python path and the

pip

path here.

Copy the path where the Python application is installed and append it to the

Variable value

.

Ensure that you insert a semicolon at the end, just to make sure that you append it to our existing

Variable value

.

Also, copy the path where

pip

is installed from the

/Scripts

folder and append it to the

Variable value

as shown in the following screenshot: 

Restart the machine so that it recognizes the new values we've just inserted.

After the restart is complete, open a command line and type

python

and the interactive shell will appear:

Now, to get connectivity with our Kali machine, make sure that the network setting is set to

Internal Network

and the network name matches the name on the Kali side, which is

intnet

:

Lastly, we need to give this machine an IP address on the same subnet as the Kali machine. We can change the network settings by going to 

Network and Internet

/

Network and Sharing Center

 from the control panel. Click on the 

Local Area Connection

and then click on 

Properties

. From there, go to

Internet Protocol Version 4 (TCP/IPv4)

, enter the

IP address

as

10.0.2.10

 and the rest as shown in the following screenshot. Then click on 

OK

:

We have installed the Python compiler on the target machine just to have a better way to explain the code and compile it. However, we will compile the Python script into a standalone EXE later on, so it'll work on any target without having a Python compiler installed.

TCP reverse shell

In this section, we will have a quick overview of TCP reverse shells, why we need a reverse connection, and what a shell is. The best way to answer these questions is to study the topology shown in the following figure:

Let's say that we have an Attacker connected somewhere on the Internet, and on the right side we have our Target. So technically, we have a PC that is fully patched with a built-in firewall enabled, and we have the corporate firewall in place. And most likely that Corporate firewall is integrated with an IPS module or Antivirus software. So now, for the attacker to access this protected PC, there are two major problems here. First, the attacker needs to bypass the built-in or the host-based firewall on the operating system, which, by default, will block any incoming connection to that PC unless it's explicitly permitted; and the same rule goes for the corporate firewall as well.

But, if the attacker could somehow find a way to send a malicious file to the user, or maybe trick that user into visiting our malicious website and downloading a malicious file, then we might be able to compromise that PC or maybe the whole network. So, in order to bypass the firewall root restriction, we need to make our target, which is the TCP client, initiate the connection back to us. So, in this case, we are acting as a TCP server, and our target, or our victim here, is acting as a TCP client and this is exactly why we need a reverse shell.

Now, we need to understand what a shell is in the first place. If we can initiate a cmd process on the target machine and bind that process to a network socket, in this case, it's called a reverse shell. Hence, when we say that we sent a TCP reverse shell on port 123 to the target machine, it means that once the victim runs the file, we're expecting to receive a reverse TCP connection on port 123. So, the destination port in this case will be 123, and we should be listening on this port. So this port should be open in our Kali machine. Then, after completing the TCP three-way handshake, we can send certain commands to the victim/target, make the victim execute them, and get the result back to us.

Keep in mind that a combination of social engineering and client-side attacks, which we discussed here, is the most powerful type of attack, and is highly likely to succeed.

Coding a TCP reverse shell

In this section, we will call a sample TCP server on the Kali machine and a sample TCP client on the target machine. Then, we will see how to execute some commands remotely from the Kali machine.

Client side

Now, let's look into the client side script:

# Python For Offensive PenTest: A Complete Practical Course - All rights reserved