Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters
Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters
Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters
Ebook443 pages3 hours

Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters

Rating: 4 out of 5 stars

4/5

()

Read preview

About this ebook

Fully-updated for Python 3, the second edition of this worldwide bestseller (over 100,000 copies sold) explores the stealthier side of programming and brings you all new strategies for your hacking projects.

When it comes to creating powerful and effective hacking tools, Python is the language of choice for most security analysts. In Black Hat Python, 2nd Edition, you’ll explore the darker side of Python’s capabilities—writing network sniffers, stealing email credentials, brute forcing directories, crafting mutation fuzzers, infecting virtual machines, creating stealthy trojans, and more.
 
The second edition of this bestselling hacking book contains code updated for the latest version of Python 3, as well as new techniques that reflect current industry best practices. You’ll also find expanded explanations of Python libraries such as ctypes, struct, lxml, and BeautifulSoup, and dig deeper into strategies, from splitting bytes to leveraging computer-vision libraries, that you can apply to future hacking projects.
 
You’ll learn how to:
    Create a trojan command-and-control using GitHub
    Detect sandboxing and automate common malware tasks, like keylogging and screenshotting
    Escalate Windows privileges with creative process control
    Use offensive memory forensics tricks to retrieve password hashes and inject shellcode into a virtual machine
    Extend the popular Burp Suite web-hacking tool
    Abuse Windows COM automation to perform a man-in-the-browser attack
    Exfiltrate data from a network most sneakily
 
When it comes to offensive security, your ability to create powerful tools on the fly is indispensable. Learn how with the second edition of Black Hat Python.
 
New to this edition:
All Python code has been updated to cover Python 3 and includes updated libraries used in current Python applications. Additionally, there are more in-depth explanations of the code and the programming techniques have been updated to current, common tactics. Examples of new material that you'll learn include how to sniff network traffic, evade anti-virus software, brute-force web applications, and set up a command-and-control (C2) system using GitHub.
LanguageEnglish
PublisherNo Starch Press
Release dateApr 13, 2021
ISBN9781718501133
Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters

Related to Black Hat Python, 2nd Edition

Related ebooks

Programming For You

View More

Rating: 3.7692308 out of 5 stars
4/5

13 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 5 out of 5 stars
    5/5

    Nov 14, 2024

    Thank You This Is Very Good, Maybe This Can Help You
    Download Full Ebook Very Detail Here :
    https://amzn.to/3XOf46C
    - You Can See Full Book/ebook Offline Any Time
    - You Can Read All Important Knowledge Here
    - You Can Become A Master In Your Business

Book preview

Black Hat Python, 2nd Edition - Justin Seitz

PRAISE FOR THE FIRST EDITION OF BLACK HAT PYTHON

Another incredible Python book. With a minor tweak or two many of these programs will have at least a ten-year shelf life, and that is rare for a security book.

—Stephen Northcutt, founding president of the SANS Technology Institute

A great book using Python for offensive security purposes.

—Andrew Case, Volatility core developer and coauthor of The Art of Memory Forensics

If you truly have a hacker’s mindset, a spark is all you need to make it your own and do something even more a`mazing. Justin Seitz offers plenty of sparks.

—Ethical Hacker

Whether you’re interested in becoming a serious hacker/penetration tester or just want to know how they work, this book is one you need to read. Intense, technically sound, and eye-opening.

—Sandra Henry-Stocker, IT World

Definitely a recommended read for the technical security professional with some basic previous exposure to Python.

—Richard Austin, IEEE Cipher

Black Hat Python

2nd Edition

Python Programming for Hackers and Pentesters

by Justin Seitz and Tim Arnold

San Francisco

BLACK HAT PYTHON, 2nd Edition. Copyright © 2021 by Justin Seitz and Tim Arnold.

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

Fourth printing

26 25 24 23 22     4 5 6 7 8

ISBN-13: 978-1-7185-0112-6 (print)

ISBN-13: 978-1-7185-0113-3 (ebook)

Publisher: William Pollock

Executive Editor: Barbara Yien

Production Editor: Dapinder Dosanjh

Developmental Editor: Frances Saux

Cover Illustration: Garry Booth

Interior Design: Octopod Studios

Technical Reviewer: Cliff Janzen

Copyeditor: Bart Reed

Compositor: Jeff Lytle, Happenstance Type-O-Rama

Proofreader: Sharon Wilkey

For information on book distributors or translations, please contact No Starch Press, Inc. directly:

No Starch Press, Inc.

245 8th Street, San Francisco, CA 94103

phone: 1-415-863-9900; info@nostarch.com

www.nostarch.com

Library of Congress Control Number: 2014953241

No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

The information in this book is distributed on an As Is basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.

To my beautiful wife, Clare. I love you.

—Justin

About the Authors

Justin Seitz is a renowned cybersecurity and open source intelligence practitioner and the co-founder of Dark River Systems Inc., a Canadian security and intelligence company. His work has been featured in Popular Science, Motherboard, and Forbes. Justin has authored two books on developing hacking tools. He created the AutomatingOSINT.com training platform and Hunchly, an open source intelligence collection tool for investigators. Justin is also a contributor to the citizen journalism site Bellingcat, a member of the International Criminal Court’s Technical Advisory Board, and a Fellow at the Center for Advanced Defense Studies in Washington, DC.

Tim Arnold is currently a professional Python programmer and statistician. He spent much of his early career at North Carolina State University as a respected international speaker and educator. Among his accomplishments, he has ensured that educational tools are accessible to underserved communities worldwide, including making mathematical documentation accessible to the blind.

For the past many years, Tim has worked at SAS Institute as a principal software developer, designing and implementing a publishing system for technical and mathematical documentation. He has served on the board of the Raleigh ISSA and as a consultant to board of the International Statistical Institute. He enjoys working as an independent educator, making infosec and Python concepts available to new users and elevating those with more advanced skills. Tim lives in North Carolina with his wife, Treva, and a villainous cockatiel named Sidney. You can find him on Twitter at @jtimarnold.

About the Technical Reviewer

Since the early days of Commodore PET and VIC-20, technology has been a constant companion to Cliff Janzen—and sometimes an obsession! Cliff spends a majority of his workday managing and mentoring a great team of security professionals, striving to stay technically relevant by tackling everything from security policy reviews and penetration testing to incident response. He feels lucky to have a career that is also his favorite hobby and a wife who supports him. He is grateful to Justin for including him on the first edition of this wonderful book and to Tim for leading him to finally make the move to Python 3. And special thanks to the fine people at No Starch Press.

Foreword

It has been six years since I wrote the foreword to the very successful first edition of Black Hat Python. Much has changed in the world during this time, but one thing hasn’t: I still write an awful lot of Python code. In the field of computer security, you will still come across tools written in a variety of languages, depending on the task. You’ll see C code written for a kernel exploit, JavaScript code written for a JavaScript fuzzer, or a proxy written in a newer hipper language like Rust. But Python is still the workhorse in this industry. For my money, it is still the easiest language with which to get started, and with the large number of libraries available, it is the best language for quickly writing code to perform complex tasks in a simple way. The majority of computer security tools and exploits are still written in Python. This includes everything from exploit frameworks like CANVAS to classic fuzzers like Sulley.

Prior to the publication of the first edition of Black Hat Python, I had written many fuzzers and exploits in Python. These included exploits against Safari for Mac OS X, iPhone and Android phones, and even Second Life. (You may have to Google that last one.)

Anyway, since then, I’ve written a pretty special exploit, with help of Chris Valasek, that was able to remotely compromise a 2014 Jeep Cherokee and other cars. Of course, this exploit was written in Python, using the dbus-python module. All of the tools we wrote, which eventually allowed us to remotely control the steering, brakes, and acceleration of the compromised vehicle, were also written in Python. You could say, in a way, that Python was responsible for the recall of 1.4 million Fiat Chrysler vehicles.

If you are interested in tinkering with information security tasks, Python is a great language to learn because of the large number of reverse engineering and exploitation libraries available for your use. Now, if only the Metasploit developers would come to their sense and switch from Ruby to Python, our community would be united.

In this new edition to what has become a beloved classic, Justin and Tim have updated all the code to Python 3. Personally, I’m a dinosaur who is hanging onto Python 2 for as long as possible, but as useful libraries finish migrating to Python 3, even I will soon have to learn it. This edition manages to cover a large range of topics that an enterprising young hacker would need to get started, from the basics of how to read and write network packets to anything you might need for web application auditing and attacking.

In general, Black Hat Python is a fun read written by experts with years of experience who are willing to share the secrets they have learned along the way. While It might not immediately turn you into a super stunt hacker like me, it will certainly get you started down the correct path.

Remember, the difference between script kiddies and professional hackers is that the former uses other people’s tools.

The latter can write their own.

Charlie Miller

Security Researcher

St. Louis, Missouri

October 2020

Preface

Python hacker, Python programmer. You could use either of those terms to describe us. Justin has spent a great deal of time penetration testing, which requires the ability to rapidly develop Python tools, with a focus on delivering results (not necessarily on prettiness, optimization, or even stability). Tim’s mantra is make it work, make it understandable, make it fast—in that order. When your code is readable, it becomes understandable to those you share it with, but also to yourself when you look at it a few months down the road. Throughout this book, you will learn that this is how we code: hacking is our final purpose, and clean, understandable code is the method we use to get there. We hope that this philosophy and style helps you as well.

Since the first edition of this book appeared, much has happened in the Python world. Python 2 reached its end-of-life in January 2020. Python 3 has become the recommended platform for coding and teaching. Therefore, this second edition refactors the code and ports it to Python 3 using the latest packages and libraries. It also takes advantage of the syntax changes provided by Python 3.6 and higher versions of Python 3, such as Unicode strings, context managers, and f-strings. Lastly, we’ve updated this second edition with additional explanations of coding and networking concepts, such as the use of context managers, Berkeley Packet Filter syntax, and a comparison of the ctypes and struct libraries.

As you progress through the book, you will realize that we don’t take deep dives into any single topic. This is by design. We want to give you the basics, with a little flavor, so that you gain foundational knowledge in the world of hacking tool development. With that in mind, we’ve sprinkled explanations, ideas, and homework assignments throughout the book to kickstart you in your own direction. We encourage you to explore these ideas, and we would love to hear about any tooling you’ve completed on your own.

As with any technical book, readers at different skill levels will experience this book differently. Some of you may simply grab it and nab chapters that are pertinent to your latest consulting gig. Others may read it cover to cover. If you are a novice-to-intermediate Python programmer, we recommend that you start at the beginning of the book and read the chapters in order. You will pick up some good building blocks along the way.

To start, we lay down networking fundamentals in Chapter 2. Then we slowly work our way through raw sockets in Chapter 3 and using Scapy in Chapter 4 for some more interesting network tooling. The next section of the book deals with hacking web applications, starting with your own custom tooling in Chapter 5 and then extending the popular Burp Suite in Chapter 6. From there, we will spend a great deal of time talking about trojans, beginning with using GitHub for command and control in Chapter 7, all the way through Chapter 10, where we will cover some Windows privilege escalation tricks. The final chapter is about the Volatility memory forensics library, which helps you understand how the defensive side thinks and shows how you can leverage their tools for offense.

We try to keep the code samples short and to the point, and the same goes for the explanations. If you are relatively new to Python, we encourage you to punch out every line to get that coding muscle memory going. All of the source code examples from this book are available at https://nostarch.com/black-hat-python2E/.

Here we go!

Acknowledgments

Tim offers a big thank you to his wife, Treva, for her enduring support. If it were not for several serendipitous incidents, he would not have had the opportunity to work on this book. He thanks the Raleigh ISSA, especially Don Elsner and Nathan Kim, for supporting and encouraging him to teach a local class using the first edition of this book. Teaching that class and working with his students led to his love for the book. And to his local hacker community, not least the Oak City Locksports folks, he offers thanks for their encouragement, and for providing a sounding board for his ideas.

Justin would like to thank his family—his beautiful wife, Clare, and his five children, Emily, Carter, Cohen, Brady, and Mason—for all of the encouragement and tolerance while he spent a year and a half of his life writing this book. He loves them all very much. To all his friends in the cyber and OSINT community who share drinks, laughs, and Tweets: thanks for letting him piss and moan to you on the daily.

Another huge thank you to Bill Pollock of No Starch Press and to our patient editor, Frances Saux, for helping make the book so much better. Thanks to the rest of the team at No Starch—including Tyler, Serena, and Leigh—for all of the hard work you put into this book and the rest in your collection. We both appreciate it. We would also like to thank our technical reviewer, Cliff Janzen, who provided absolutely amazing support throughout the whole process. Anyone who is writing an infosec book should really get him on board; he was amazing and then some.

1

Setting Up Your Python Environment

This is the least fun, but nevertheless critical, part of the book, where we walk through setting up an environment in which to write and test Python. We’ll do a crash course in setting up a Kali Linux virtual machine (VM), creating a virtual environment for Python 3, and installing a nice integrated development environment (IDE) so that you have everything you need to develop code. By the end of this chapter, you should be ready to tackle the exercises and code examples in the remainder of the book.

Before you get started, if you don’t have a hypervisor virtualization client such as VMware Player, VirtualBox, or Hyper-V, download and install one. We also recommend that you have a Windows 10 VM at the ready. You can get an evaluation Windows 10 VM here:https://developer.microsoft.com/en-us/windows/downloads/virtual-machines/.

Installing Kali Linux

Kali, the successor to the BackTrack Linux distribution, was designed by Offensive Security as a penetration testing operating system. It comes with a number of tools preinstalled and is based on Debian Linux, so you’ll be able to install a wide variety of additional tools and libraries.

You will use Kali as your guest virtual machine. That is, you’ll download a Kali virtual machine and run it on your host machine using your hypervisor of choice. You can download the Kali VM from https://www.kali.org/downloads/ and install it in your hypervisor of choice. Follow the instructions given in the Kali documentation: https://www.kali.org/docs/installation/.

When you’ve gone through the steps of the installation, you should have the full Kali desktop environment, as shown in Figure 1-1.

f01001v2

Figure 1-1: The Kali Linux desktop

Because there may have been important updates since the Kali image was created, let’s update the machine with the latest version. In the Kali shell (ApplicationsAccessoriesTerminal), execute the following:

tim@kali:~$ sudo apt update

tim@kali:~$ apt list --upgradable

tim@kali:~$ sudo apt upgrade

tim@kali:~$ sudo apt dist-upgrade

tim@kali:~$ sudo apt autoremove

Setting Up Python 3

The first thing we’ll do is ensure that the correct version of Python is installed. (The projects in this book use Python 3.6 or higher.) Invoke Python from the Kali shell and have a look:

tim@kali:~$ python

This is what it looks like on our Kali machine:

Python 2.7.17 (default, Oct 19 2019, 23:36:22)

[GCC 9.2.1 20191008] on linux2

Type help, copyright, credits or license for more information.

>>>

Not exactly what we’re looking for. At the time of this writing, the default version of Python on the current Kali installation is Python 2.7.18. But this isn’t really a problem; you should have Python 3 installed as well:

tim@kali:~$ python3

Python 3.7.5 (default, Oct 27 2019, 15:43:29)

[GCC 9.2.1 20191022] on linux

Type help, copyright, credits or license for more information.

>>>

The version of Python listed here is 3.7.5. If yours is lower than 3.6, upgrade your distribution with the following:

$ sudo apt-get upgrade python3

We will use Python 3 with a virtual environment, which is a self-contained directory tree that includes a Python installation and the set of any extra packages you install. The virtual environment is among the most essential tools for a Python developer. Using one, you can separate projects that have different needs. For example, you might use one virtual environment for projects involving packet inspection and a different one for projects on binary analysis.

By having separate environments, you keep your projects simple and clean. This ensures that each environment can have its own set of dependencies and modules without disrupting any of your other projects.

Let’s create a virtual environment now. To get started, we need to install the python3-venv package:

tim@kali:~$ sudo apt-get install python3-venv

[sudo] password for tim:

...

Now we can create a virtual environment. Let’s make a new directory to work in and create the environment:

tim@kali:~$ mkdir bhp

tim@kali:~$ cd bhp

tim@kali:~/bhp$ python3 -m venv venv3

tim@kali:~/bhp$ source venv3/bin/activate

(venv3) tim@kali:~/bhp$ python

That creates a new directory, bhp, in the current directory. We create a new virtual environment by calling the venv package with the -m switch and the name you want the new environment to have. We’ve called ours venv3, but you can use any name you like. The scripts, packages, and Python executable for the environment will live in that directory. Next, we activate the environment by running the activate script. Notice that the prompt changes once the environment is activated. The name of the environment is prepended to your usual prompt (venv3 in our case). Later on, when you’re ready to exit the environment, use the command deactivate.

Now you have Python set up and have activated a virtual environment. Since we set up the environment to use Python 3, when you invoke Python, you no longer have to specify python3—just python is fine, since that is what we installed into the virtual environment. In other words, after activation, every Python command will be relative to your virtual environment. Please note that using a different version of Python might break some of the code examples in this book.

We can use the pip executable to install Python packages into the virtual environment. This is much like the apt package manager because it enables you to directly install Python libraries into your virtual environment without having to manually download, unpack, and install them.

Let’s do a quick test and install the lxml module, which we’ll use in Chapter 5 to build a web scraper. Enter the following into your terminal:

(venv3) tim@kali:~/bhp: pip install lxml

You should see output in your terminal indicating that the library is being downloaded and installed. Then drop into a Python shell and validate that it was installed correctly:

(venv3) tim@kali:~/bhp$ python

Python 3.7.5 (default, Oct 27 2019, 15:43:29)

[GCC 9.2.1 20191022] on linux

Type help, copyright, credits or license for more information.

>>> from lxml import etree

>>> exit()

(venv3) tim@kali:~/bhp$

If you get

Enjoying the preview?
Page 1 of 1