Chapter 6 Infrastructure and Endpoint Attacks – GCIH GIAC Certified Incident Handler All-in-One Exam Guide

CHAPTER 6

Infrastructure and Endpoint Attacks

In this chapter you will learn about

•   Infrastructure attacks

•   Password cracking

•   Buffer overflows

•   Bypassing endpoint security

•   Using tools like Cain, Hashcat, John the Ripper, Hydra, MSFvenom, and Veil framework

Being able to access a target physically can prove valuable in defeating security defenses. Why try to break someone’s password if you can reboot the individual’s machine and start running an operating system of your choice to get the files you need while bypassing it altogether? But even when physical access is not feasible, various methods exist that leverage endpoint weaknesses. One of the most common ones is getting password files for offline cracking or trying to break weak passwords using online attacks. Others include trying to bypass endpoint security countermeasures or leveraging buffer overflow attacks against poorly written applications.

Infrastructure Attacks

It’s important to highlight that this chapter won’t deal with the penetration testing aspect of physical infrastructure (also known as physical) attacks. Examples of those include tailgating, piggybacking, dumpster diving, shoulder surfing, card cloning, key bumping, lock picking, and similar types of attacks. The main interest here is what techniques do attackers use to compromise machines once they get access to them, not how that access is gained to begin with.

DMA Attacks

Directory Memory Access (DMA) is a feature used to allow devices to directly interact with a system’s memory, without the CPU’s intervention. This helps achieve greater speeds, as it reduces any CPU-incurred delays, which would normally be present when it handles all input/output operations. However, with this circumvention any security protocols are also being bypassed. Of course, in order for this to happen, the victim needs to have a device that supports DMA (for example, a network, sound, or graphics card), which the attacker can use to connect over FireWire, PCI, Thunderbolt or any other compatible connection type.

Once that happens, the attacker will commonly try to capture the target’s memory in an effort to identify sensitive data, like passwords or encryption keys. Ulf Frisk did a great Defcon presentation in 2016 about how to perform DMA attacks on Linux, Windows, and macOS systems (https://www.youtube.com/watch?v=fXthwl6ShOg) using Pcileech (https://github.com/ufrisk/pcileech), which he developed. The tool can dump a machine’s memory or write in it, thus allowing an attacker to disable the password requirement for a target system. This can work on systems even with full drive encryption enabled (as long as the system is powered on—it can have its screen locked or be hibernated). Sami Laiho has written a great article in his blog on how to get the BitLocker key from a Windows 10 machine performing a DMA attack to capture its memory (http://blog.win-fu.com/2017/02/the-true-story-of-windows-10-and-dma.html). Inception (https://github.com/carmaa/inception) is another example of a tool that can be used for these types of attacks.

USB Attacks

Attackers can use tools that IT teams also often use to recover, reset, or bypass machine passwords. Examples include Trinity Rescue Kit (http://trinityhome.org), Kon-Boot (https://www.piotrbania.com/all/kon-boot), Ultimate Boot CD (https://www.ultimatebootcd.com), and Hirens Boot CD (https://www.hirensbootcd.org).

Using a bootable flash drive or CD drive (rarely used nowadays, as laptops don’t have CD drives) can allow an attacker to load an operating system of his choice, mount the hard disk, and get access to sensitive data. In some versions of Windows, if an attacker proceeds with deleting the SAM file and rebooting the machine, he can get Administrator access, since Windows will create a new SAM file once the machine boots up, which will now have a blank Administrator password.

The Windows Autorun feature aids USB attacks quite a lot. If a malicious flash drive or CD/DVD is inserted into the machine, all it takes is Autorun to allow it to execute freely. If a standard AV or other endpoint security tool is not present (or doesn’t identify the attack), it could have dire consequences.

Another approach is to attach a malicious hardware device on a USB port, like a hardware keystroke logger, backdoor installer, or storage device for data exfiltration. Hak5 (https://shop.hak5.org) has some great products, which include

•   Bash Bunny  Supports multiple payloads, although it looks like an ordinary USB flash drive. It has a quad-core processor and 8GB SSD drive.

•   Lan Turtle  Hidden within a USB network adapter, it has a graphical shell for setting it up and supports various attacks like Meterpreter shell, reverse shell, nmap scanning, remote file system mounting, and various others.

•   Rubber Ducky  Looks like an ordinary USB drive but allows entering data at great speeds, backdoor installation, data exfiltration, password theft, and keystroke logging, and once attached it mimics a keyboard connection.

•   O.MG Cable  Malicious USB cable that has a wireless network interface to support payload execution and can even be erased remotely to look like a standard USB cable.

Defending Against Infrastructure Attacks

Enforce firmware and BIOS password use and disable USB booting so unauthorized individuals can’t use external media to boot from. Enforce full disk encryption, and consider disabling USB ports (although it makes life much harder for users, as they can’t even connect an external mouse or keyboard to the system). Also, consider blocking or disabling DMA devices, but if that’s not feasible, enforce a Mobile Device Management (MDM) policy that can help control them. Note that DMA security depends on the device’s manufacturer, not the underlying OS. User education can also help a lot. Train staff to never leave their machines unlocked while they are away and not to connect any untrusted devices to them.

Password Cracking

Password files are one of the first things attackers try to get once a system is compromised. That will allow them to perform an offline attack later on in an effort to discover working credentials that may give them access to other machines, possibly of greater value than the currently compromised one. Other techniques involve dumping passwords from the cache, memory, or registry. When unencrypted protocols are used in the network, attackers may not even have to crack passwords. They just wait and sniff all the traffic so they can identify working passwords.

Techniques

As also mentioned earlier, the attackers can use other techniques in addition to traditional password cracking. Those will all be discussed here, including traditional password cracking.

Password Extraction

To make things simpler, an attacker will first try to extract any passwords that exist in plaintext in various locations, to avoid the hustle of having to actually crack passwords since that requires time and resources.

Dumping Hashes from the LSA Cache  Passwords regarding Windows accounts, services, and various domains may be stored in Local Security Authority (LSA) secrets. That’s a registry key found under HKEY_LOCAL_MACHINE\Security\Policy\Secrets. Note that Administrator access is not enough to access that key. It requires system-level permissions. If you want to have a look, you can use SysInternal’s psexec tool using the command psexec -i -s cmd.exe. Once the new command prompt opens, invoke the registry (using regedit.exe over the command prompt) and navigate to the appropriate registry hive mentioned earlier. Attackers will commonly use tools like Creddump (https://tools.kali.org/password-attacks/creddump), Mimikatz (https://github.com/gentilkiwi/mimikatz), or Cain to dump passwords from the LSA cache. Figure 6-1 shows Cain’s LSA secrets dumping feature.

Figure 6-1  Cain’s LSA secrets dumping feature

TIP   An attacker would need to get Administrator access and then place one of those tools on the target system to be able to use it and dump the related passwords.

Credential Manager Passwords  Windows Credential Manager is used to store certificates and credentials for accessing Windows applications, as well as domains, as seen in Figure 6-2.

Figure 6-2  Windows Credential Manager

Cain can again be used to dump any such passwords, as shown in Figure 6-3.

Figure 6-3  Cain dump of Windows Credential Manager

SAM/AD Password Hashes  A tool like Cain, fgdump (http://foofus.net/goons/fizzgig/fgdump), or pwdump8 (http://www.blackmath.it/#Download) can be used to dump the hashed passwords from a Windows machine and crack them afterward. Running pwdump8 on the Windows machine will provide the following output:

Another tool can be used afterward for offline cracking, or an online tool like HashKiller (https://hashkiller.io/listmanager) can even be utilized. More details on cracking will be provided later in this chapter. Passwords can also be dumped from an AD domain controller, Windows volume shadow copy, or extracted from sniffed network traffic.

Password Guessing

With password guessing, attackers attempt to log in to a resource by actively trying username and password combinations. Finding a valid username is not that difficult, as many websites accept e-mails or phone numbers in addition to valid usernames. If the target resource doesn’t have any multifactor authentication enabled, it’s usually a matter of time until a working password is identified for most trivial passwords. To make things worse, attackers are always on the lookout for large breaches relating to credential disclosures. Once that happens, they take a copy of those credentials and use them in scripts in order to automate attacks. When victims use those leaked credentials across various accounts (including their corporate domain), things can get really damaging in no time.

Of course (as you also remember from running the Metasploit module for VNC brute forcing in Chapter 5), you can easily lock an account when entering wrong passwords multiple times. However, that can be tackled by slowing down the speed of the attack or using one password across various accounts and spreading that across different resources. This technique is known as password spraying and is used often in order to avoid locking target accounts.

Also, don’t forget all those great information-gathering techniques from Chapter 3. For example, people who have social media profiles will often update them with really personal details like their pet’s name, place of birth, family member names, favorite book or movie, and much more. Do any of these questions ring a bell? Hopefully, you answered yes to that question. All that information is commonly used as answers to security questions from a variety of websites. How difficult do you think it is for someone to call your bank and, when challenged with security questions, use the publicly available answers from your social media profile information? This is what social engineering is all about.

Traditional Password Cracking

Let me start by saying that not all password cracking attempts are malicious. They can easily be conducted by auditors and system administrators to identify how robust current passwords are and how well password policies are performing. Also, I have seen some really eager system administrators downloading various password cracking tools and using them in an effort to recover files that were password encrypted and contained really important information. Of course, it doesn’t help when this effort is kept a secret and you are receiving multiple alerts saying Cain, John the Ripper, and various other applications are being downloaded on the same machine.

Earlier it was mentioned that one of the first things an attacker does once gaining access to a system is get a copy of the password file. That’s where brute-force attacks come in. I remember discussions about how long it would take to crack a password when I was studying for my postgraduate degree. Academics often say something is feasible, even if that’s just theoretical in nature. For example, if you need to spend $1 trillion to crack a password in one year, that might be theoretically feasible. However, attackers don’t want to wait that long, plus not everyone has $1 trillion in their pocket. As such, brute-force attacks might work well on weak algorithms and passwords but will definitely take a lot of time to crack strong password representations, especially if a lengthy passphrase was used and it contains lowercase and uppercase letters, numbers, and special characters. However, the great advantage of this method is that it is guaranteed to succeed, since all possible combinations are tried in succession.

Dictionary attacks can be used to reduce the required time and computational resources to crack a password and are considered the fastest method. This heavily depends on the quality of the dictionary files in combination with the fact that most people tend to use simple words as passwords (which are easily found in dictionaries). Most password cracking programs have various password lists you can use, not to mention those can easily be modified to include additional entries.

The UK’s National Cyber Security Centre published a study in April 2019 regarding passwords used in various breaches—23.2 million accounts were found using 123456, followed by 7.7 million using 123456789 and almost 4 million using qwerty and password. Any common dictionary attack will crack these passwords (using default dictionaries) in a few seconds. But what happens if users are a bit more security conscious? They may still be lazy but restricted by a password policy. So, instead of using password, they might need to add uppercase letters in addition to a number, making the new password Password1. Hybrid attacks can aid in these scenarios.

When a hybrid attack is used, a dictionary of words would still be in play, but in addition to that, the attacker can designate rules that govern how the password cracking attempt should be executed. In essence, these are the password policy’s guidelines. If the exact details are not known, generic guidelines can be enforced, like using uppercase and lowercase characters and one to three symbols in combination with numbers. Note that the more complex the rules become, the more time and resources will be required to perform an exhaustive search.

Rainbow Tables

This attack is really effective against unsalted passwords. A salt is a random sequence of bits that is added to a password before it gets hashed. This allows the password to be resilient against dictionary attacks and doesn’t allow for identical passwords to be highlighted to the attacker. Let’s take two Windows passwords that are identical and are both stored using NT LAN Manager (NTLM) (discussed in the next section):

June and Jack both share a password of password123. Even if the attacker doesn’t know the password for both users, they do know a common password is being used. As such, they might choose to focus their efforts on cracking the particular password, since it is used across different accounts. Rainbow tables use precomputed tables of hashes (generated from hashing dictionaries of common passwords), which are compared with a password file’s entries (containing the hashed password representations). If a match is found, the attacker can check what password was used to create that hashed entry.

However, if a salt is used, things become more difficult because a random sequence of bits is appended to the password prior to hashing it. So, in the previous example, instead of hashing password123, you would end up hashing something like 872!ytuey*&password123. This greatly increases the possible matches, requiring much more time and computational resources to find a match.

Stored Password Locations and Formats

Windows stores passwords locally using LM and NT hashes, while latest versions of Linux/Unix systems use a shadow file. Let’s see how each of these works and how can attackers exploit any weaknesses.

Windows

Windows uses two password formats for local systems: LANMAN and NT hashes.

NOTE   Windows uses LM challenge-response, NTLMv1, and NTLMv2 for network authentication. There is also a Microsoft implementation of Kerberos that may be used. Don’t confuse network authentication with local password databases.

Let’s revisit the previous pwdump8 output, taken from the Windows machine:

Each user account has three entries next to the username:

•   User’s SID (500 signifies the Administrator account)

•   LANMAN hash (also known as LM and LAN Manager)

•   NT hash (also known as NTLM)

LM Hashes  Notice that all the LM entries have the same value, which is AAD3B435B51404EEAAD3B435B51404EE. That’s used by the tool to denote there’s no password, meaning that no LANMAN hash is being used. That’s because Windows versions from Windows 7 onward don’t include LANMAN hashes in the SAM file. However, in previous Windows versions that hash is present. To make matters worse, LANMAN hashes are also present when an AD domain is being used, stored in systemroot\NTDS\ntds.dit. If an attacker gets a copy of that file, they can easily identify working passwords, since reversing LANMAN is trivial.

Any password must be up to 14 characters long. If it’s longer than that, no LM hash can be generated. If it’s smaller, padding is applied to allow it to reach 14 characters. The hash is then generated from two separate seven-character segments of the actual user’s password. But each seven-character portion can be attacked individually by password cracking software, trying all possible combinations until a match is identified. To make things easier for the attackers, each password is converted to uppercase before padding is applied. That means it doesn’t matter if a security-conscious user has used BeerAndWine, as it would be converted to BEERANDWINE, reducing the possible combinations even more. On average, it can take anywhere from a few hours (if only letters are used) to four or five days (for more complicated combinations) to crack an LM-hashed password, which as technology advances gets reduced even more.

EXAM TIP   LM and NTLM don’t use any salt to encrypt passwords.

NTLM Hashes  To generate an NTLM hash, the user’s password is hashed using the Message Digest 4 (MD4) algorithm (or to be perfectly accurate, the password’s little-endian Unicode Transformation Format (UTF)-16 representation is hashed using MD4). One advantage is that lowercase and uppercase formatting is maintained, making it more challenging for an attacker to identify the password. Passwords can be up to 256 characters, which is a major improvement in comparison to LM’s 14 characters.

Linux

Linux stores password hashes in two files (depending on the version): /etc/passwd and /etc/shadow. Older systems used to store hashed passwords in /etc/passwd, which is readable by any user (as the “r” indicates):

As such, anyone could get a copy and try to crack those hashes—for example, using a rainbow table attack. However, newer implementations use/etc/shadow for password storage, which is only readable by root. An attempt for a standard user (like John) to read the file won’t be successful:

Contrary to Windows, Linux/Unix systems use salt when hashing passwords. In short, if an attacker wants to crack those values, root access is required to first read the /etc/shadow file, and then he would still need to crack salted password hashes.

/etc/passwd Format  If you want to read the passwd file, you can use the command cat /etc/passwd. This is what John’s entry looks like:

EXAM TIP   “x,” “*,” and “!!” indicate a shadow file is being used, so any hashed passwords would be in that and not in /etc/passwd.

Each of the seven columns is used for the following purposes:

•   John  Depicts the username.

•   x  Denotes a shadow file is used to store hashed passwords.

•   12  User ID for the current user. Note that root has a UID of 0.

•   1002  Group ID for current user’s group.

•   John Jameson  Comment field information.

•   /home/John  User’s home directory, which is where John is placed upon login.

•   /bin/sh  User’s shell.

/etc/shadow Format  After logging in as root, use cat /etc/shadow to read the shadow file. John’s entry follows:

Columns are used for the following purposes:

•   John  Depicts the username.

•   $6$lm3z9BUuryRFhwLX$qf14Bb/Vj4e5OFDhUryFydwersM5OU6.33BacHHVRWskl5Wzvlu7fQ48IYF9r7t8tiBpVLy9fdu/vJN2WhriZ0  The preceding character enclosed in $ signs ($6$) indicates the algorithm used for hashing the password. For example, 1 is for MD5, while 2 is for Blowfish, 2a is for eksblowfish, 5 for SHA-256, and 6 for SHA-512. The rest of the characters denote the hashed password value.

•   18232  Last password change (duration is counted in days since 1/1/1970).

•   0  Minimum number of days for a password change (0 means it can be changed immediately).

•   99999  Maximum number of days for a password’s validity (user will be asked to change password after that time passes).

•   7  Number of days the user gets a warning before password expiration (7 means a warning will be displayed a week prior to password expiration).

•   90  Number of days for the account to be disabled (after password expiration).

•   19357  Account expiration (duration is counted in days since 1/1/1970).

Hydra

Hydra (https://github.com/vanhauser-thc/thc-hydra) is a password cracking tool that can be used to perform attacks on local or remote network resources. Its use is very simple, as it only requires a target username (or list of usernames), a password (or password file), and a target resource (or a list of resources) along with a service. There’s even a GUI available, which can be accessed using xhydra.

A list of usernames has been compiled in usernames.txt and a list of passwords in passwords.txt. Let’s target Metasploitable’s FTP server:

Hydra got three successful hits. As you can see, it will continue to test all possible combinations until the username and password lists have been exhausted in an effort to identify all working pairs. The tool also has available options to allow specific ordering, verbose output, blank password test, and allows simultaneous tasks by increasing the number of running threads. It supports a variety of protocols, including AFP, Cisco, FTP, FTPS, HTTP, ICQ, IRC, IMAP, LDAP, MySQL, NNTP, Oracle, POP3, RDP, rlogin, RSH, SIP, SMB, SMTPM, SNMP, SSH, Telnet, and VNC.

Cain

You already saw some Cain (also referred to as Cain & Abel) features earlier, but it’s worth providing more detail regarding the application and its capabilities. It’s a Windows-based software and able to

•   Perform password recovery (using dictionary and brute-force mechanisms)

•   Recover wireless network keys

•   Obtain passwords from cache, LSA secrets, protected storage, registry, browsers, password boxes, credential manager, Windows vault, and Mail client

•   Use traceroute to discover a host

•   Perform ARP cache poisoning

•   Perform VoIP sniffing

•   Perform RSA SecurID token generation

•   Conduct network sniffing for credential extraction (LM challenge-response, NTLMv1, NTLMv2, Kerberos, FTP, HTTP, IMAP, LDAP, POP3, SMB, Telnet, SMTP, ICQ, SIP, and more)

•   Perform war driving

•   Perform hash calculation and cracking functionality (MD2, MD4, SHA-1, SHA-2, RIPEMD-160, password lists - PWL, Cisco IOS/PIX MD5, APOP-MD5, CRAM-MD5, LM, NTLM, MS-cache, RIP, OSPF, VRRP, VNC, Radius Shared-Key, IKE-PSK, SQL/MySQL, Oracle, SIP, WPA-PSK, and CHAP)

You saw some examples earlier on how to use Cain to dump credentials. How about extracting those from a packet capture?

Follow these steps to get a packet capture of FTP traffic, which will then be imported to Caine (or feel free to capture other traffic of your choice, between Windows and Metasploitable):

1.  Install Wireshark (if you haven’t already installed it) on your Windows machine.

2.  Open Wireshark and start capturing traffic (go to the Capture menu and select Start).

3.  Open a command prompt and use telnet or netcat to navigate to Metasploitable’s FTP server (for example, using ncat.exe 172.16.197.136 21):

4.  Once you get a successful login confirmation, terminate the prompt.

5.  In Wireshark, save your file by choosing File | Save As, and in the file type select Wireshark/tcpdump/…pcap. This step is important because if you choose the wrong file type, Cain won’t be able to import your capture. Alternatively, you can install and use Windump for capturing the traffic.

6.  Start Caine.

7.  Select Open and choose the Wireshark packet capture, as seen next.

Upon successful import, you should see a message like this:

1.  Go to the Sniffer tab and select the Passwords tab at the bottom.

2.  Cain should have automatically extracted the password, as seen here:

Feel free to try capturing other protocol traffic, or use any of the other features mentioned earlier.

John the Ripper

John the Ripper (https://www.openwall.com/john), or John for short, is a great tool for password cracking that runs on Linux, macOS, and Windows. A quick introduction can be found at https://www.openwall.com/john/doc with links to additional documents. It supports various operational modes (https://www.openwall.com/john/doc/MODES.shtml) and also offers the option of creating new ones using its built-in compiler. The preconfigured ones are

•   Wordlist  A list of words needs to be provided to act as an attack dictionary. Word mangling is supported, which means you can define word mangling that will be applied during the cracking process. Note that you can designate various password files to be cracked.

•   Single crack  It uses login names, GECOS field information, and the user’s home directory as passwords. This is the fastest cracking mode available.

•   Incremental  This is the equivalent of brute-force cracking. John will try all possible combinations until it succeeds.

•   External  Third-party programs can be used to provide password cracking capability to John.

The default order of operations is to first try single crack mode, followed by wordlist and incremental modes. Example formats that John supports include LM, NTLM, MD5, Blowfish, and DES, as also described in the related documentation located at https://www.openwall.com/john/doc/OPTIONS.shtml. Using the --format parameter tells John what format the file is using. Example options include LM, bsdicrypt, descrypt, bcrypt, md5crypt, AFS, tripcode, dummy, and crypt. It’s worth noting that it can load both passwd and PWDUMP files.

Let’s look at an example of using John to crack passwords from the /etc/shadow file. The easiest way to do this is to make a copy of that file and use it for password cracking. Let’s see how John copes with the default password list and settings.

It only took John a few seconds to crack these passwords in single mode. As passwords get cracked, John will update its database. Results are stored in john.pot, but note that John won’t try to crack any hashes already present in that file. If you want that to happen, you can remove the file’s contents and start fresh. To review cracked passwords, use

Now, what happens if passwords become more complicated? I have added two new passwords in Kali that are longer and don’t have anything to do with the current usernames (Jane and John).

As you can see, John started in single mode but didn’t encounter any hits. As such, it continued with wordlist, using its standard dictionary (password.lst), but that didn’t work either. You can also specify alternative dictionaries or even purchase some online. This is what commonly happens when massive data leaks become public. Attackers get a copy of those passwords and place them in a dictionary, which they use for cracking. Finally, John reverted to incremental mode to start trying all possible combinations, since single and wordlist modes didn’t succeed.

NOTE   If you need to check the progress at any time, you can press the spacebar, which is how those progress entries at 38.15 percent and 71.29 percent were displayed. No progress report will be displayed in incremental mode, as John will be trying all possible combinations and has no way of telling how much time that will take.

If you want to focus on a specific format (for example, SHA-512), you can use

Hashcat

Hashcat (https://hashcat.net/hashcat) has been released as an open-source project since 2015. It can leverage the GPU processing power of hundreds and even thousands of cores and threads to offer greater cracking speeds. It supports a variety of algorithms, protocols, and file formats, like MD4, MD5, SHA-1, SHA-2, SHA-3, Keccak, SipHash, RIPEMD, Whirlpool, GOST, md5crypt, scrypt, WPA, IKE, LM, NTLM, MySQL, TACACS, SIP, Kerberos, Cisco, Office files, Bitcoin wallets, and iTunes backups. It also supports word mangling and is able to perform dictionary or brute-force attacks. Cracked passwords end up in hashcat.potfile. Some of the disadvantages are that it’s unable to auto-detect the hash type (which John the Ripper can do) and has a more complicated command-line syntax.

Let’s see an example of cracking MD5. I have added three MD5 hashed passwords in a file named list:

To review the program’s parameters, use the help function (hashcat --help), which has a really in-depth manual, and also review the tool’s wiki: https://hashcat.net/wiki.

I am going to be using Hashcat in attack mode 0 (-a 0), which will use words in my dictionary, designate MD5 as the algorithm of choice (-m 0), target the file named list, and use John the Ripper’s password list (/usr/share/john/password.lst):

It took Hashcat about three seconds to run over 3,559 passwords and identify a match:

But it didn’t find a match for the two other passwords. Those are the MD5 representations of Jane and John, which John the Ripper managed to identify when it was being used in single cracking mode, since it used information about the current users. Feel free to try other password hashes by adjusting the -m parameter accordingly.

For example, SHA-1 is 100, scrypt is 8900, NTLM is 1000, LM is 3000, md5crypt is 500. If you want to test Hashcat’s rules, browse the rules directory /usr/share/hashcat/rules, where there are more than 20 password cracking rules, which you can use with the -r parameter. Or you can try password protecting one of your Office files and feed that in Hashcat to see how it copes with cracking your password.

CAUTION   Be mindful of system resources when you use password cracking tools, as they quickly consume a lot of CPU and memory cycles. If you want to test these techniques, create a few accounts on your VM and don’t assign overly complex passwords, as that will cause the tools to run for hours and even days.

Defending Against Password Cracking

Creating strong passwords is a great starting point. Don’t make attackers’ lives easier by using weak passwords. Try to use passphrases like Appl3$And0rang3$ that can be easier for you to remember and at the same time enhance security. Ensure you create a robust password policy and enforce password complexity at a group policy level (configure account lockouts and password inactivity, expiration, and minimum number of days between password changes). Remember that the more characters you use, the more difficult it becomes to crack a password. Perform password audits frequently to ensure no weak passwords are present. Also, prompt users to change passwords regularly. Consider changing the default names of privileged accounts from Admin or Administrator to something less conspicuous.

Encrypt all of your backups and any removable media that contain password files. Consider using the SYSKEY utility to encrypt the Windows SAM database, which will make Windows request a password before accessing it. That protects any hashes stored in the registry. Note that SYSKEY is not supported from Windows 10 onward.

Disable LM and LM challenge-response due to their inherent weaknesses. These are commonly used for compatibility with previous Windows versions, so it might create issues, but if you prefer the safer choice, enable the use of NTLM hashes on a local system and NTLMv2 as a network authentication mechanism.

On Linux systems, in addition to prompting users to comply with a robust password policy, ensure that a shadow file is always in use to restrict unauthorized individuals from getting a copy of the password hashes. Also, enable multifactor or certificate-based authentication wherever possible and use Pluggable Authentication Modules (PAM), which will allow you to implement strong authentication.

Don’t forget to train your staff not to divulge passwords to anyone, especially people calling and posing as IT. If that happens, encourage them to report anything out of the ordinary so you get an opportunity to review what’s going on and possibly change passwords before any damage occurs.

Pass the Hash

As you noticed earlier, cracking hashes can take a lot of time. But keep in mind that, attackers can use those hashes to try and authenticate to network resources without having to crack them first. This is known as a pass-the-hash attack.

It takes advantage of the fact that password hashes are stored in the running Local Security Authority Subsystem Service (LSASS) process. The attacker can compromise a target machine and get the hashed password values straight from that process. After that, the values can be injected on a Windows machine the attacker owns and try to authenticate to an organizational resource. The attacker is thus trying to mirror the victim’s machine and trick the end resource into thinking a legitimate user is trying to authenticate. Mimikatz and Metasploit’s psexec module both support this type of attack and are often used. The Pass-The-Hash Toolkit (https://www.coresecurity.com/corelabs-research-special/open-source-tools/pass-hash-toolkit) and Windows Credentials Editor (https://github.com/xymnal/wce) can also be used to perform this attack.

Defending Against Pass-the-Hash Attacks

Host hardening needs to be performed so you protect against any inherent vulnerabilities that may be susceptible to exploits leveraged against endpoints that attackers can use to get password hashes. Ensure you apply OS updates and patches as soon as possible. Install endpoint AV, firewalls, and HIPS to offer additional protection to your systems. Review your network architecture, define appropriate boundaries, and limit Administrator account use on endpoints to make it harder for attackers to obtain hashes (since that requires Administrator permissions). Use account delegation to limit the permissions administrators have over the domain. If you do that, even if an Administrator account is compromised, the attacker only gets a part of superuser permissions and not all of it (which would be the case if you just create multiple superuser accounts). Don’t allow administrators to perform their tasks from any ordinary company machine (which may have a variety of other applications installed). Instead, use specifically purposed jump boxes that you have adequately hardened and that are only used for these tasks.

Buffer Overflows

When a program runs, the CPU constantly retrieves instructions from memory. Each time, the position in memory where the next instruction can be found is stored in a register, which is called the instruction pointer (also known as EIP). Machines use an object known as a stack to store information like function calls and variable values. Items get added at the top of the stack, and when they aren’t required, they get removed in what is known as a Last In, First Out (LIFO) structure . Imagine a stack of books. When you read a book, you place it at the top of the stack. If you need it again, you remove it from the top.

As programs execute, when a function is encountered, a stack frame is allocated to it, which is basically a part of the stack provided to that function for its execution. The memory boundaries that act as the delimiters for this stack frame are stored in the stack pointer (also known as ESP, which acts as the top of the stack frame) and base pointer (also known as EBP, which acts as the stack frame’s bottom). Figure 6-4 shows what happens once a function is called (remember to read it from the bottom toward the top, which is how the stack grows).

Figure 6-4  Generic stack operation

1.  Gets any associated parameters from the primary function that called it (commonly in C, main would be the primary function doing the first call to another function).

2.  Stores the value of the return pointer so it knows where in memory it needs to go after its execution finishes.

3.  Stack space is allocated for its local variables that perform the function’s tasks. In Figure 6-4, the function has three variables.

4.  After the function’s execution is finished, items get removed from the top of the stack space and return program execution to the primary function.

When the function finishes its execution, the stack frame gets released for reallocation.

Let’s see how this is applied in a very short C program.

Under normal conditions, this program does the following:

1.  The main function executes and calls another function named User_Input.

2.  As per Figure 6-4, User_Input starts its execution, and once that finishes, control will be handed over back to main. Note that the function is called by main without passing it any parameters, and it will use one variable (instead of the three that were mentioned in Figure 6-4).

3.  User_Input displays a message asking the user to type the current day of the week. Once a response is provided, the program stores the answer in a variable named day and displays the value to the user.

4.  Execution is then handed over to main, and the program terminates, since there’s no other code to execute.

You can use this source code in your Kali machine and compile it using

After buffer-overflow.c has been compiled to buffer-overflow, you can execute it and test the application:

This execution shows the results when the user types Monday. Figure 6-5 shows how the stack space looks like in that case.

Figure 6-5  Stack operation during normal execution of buffer-overflow

However, the program is vulnerable to buffer overflows. During such an attack, the goal is to overwrite stack space information and be able to point the return pointer to malicious code injected by the attacker. So, in the previous analogy of the book stack, it’s like trying to point to an arbitrary set of pages to read that will cause the program to perform an action the attacker desires.

That happens because the program uses scanf () to obtain user input and doesn’t perform any boundary checking. As such, the user’s data might be so much that won’t fit the allocated stack space for the variable day. What will that do? Let’s take a look.

This time, instead of providing a regular day of the week, the phrase ThisIsAVeryEvilDay was provided. However, that caused the program to crash with a segmentation fault, as that entry wasn’t enough to fit in the variable’s allocated space. But how does a crash exactly happen? Figure 6-6 shows the stack space status.

Figure 6-6  Instruction pointer overwritten

Since the user input was larger than expected, those extra characters went out of the allocated space and overwrote the return pointer. After User_Input finishes its execution, it will try to copy the current return pointer’s value to the instruction pointer so the program can continue its normal execution. But now, this is just a random value (since the actual value was overwritten), so the program crashes with a Segmentation Fault error, as it’s unable to access that random memory area.

So far, you have seen that random input can cause unexpected program behavior. But how can that be leveraged to exploit this vulnerability? Even if you know the previous application is susceptible to buffer overflows, you don’t know what the trigger is. Is it 5, 15, or 500 characters? Also, even if you identify that, you don’t know how to add code of interest onto the stack or how the instruction pointer can be pointed to the exact location where the malicious code is placed.

Identifying Buffer Overflows

Let’s start with the easiest way. If you have the source code (like in the previous example), you can review it for signs of vulnerable functions being present (like scanf). Other examples include gets(), strcpy(), strcat(), sprintf(), getwd(), fscanf(). All those present good indications of a buffer overflow vulnerability being present.

Of course, having the source code rarely happens (unless the application is open source). Instead, you can try to manually inspect various application fields and inject arbitrary input. For example, if there’s a website passing data to a backend application, choose any form fields, URI parameters, or any other type of input field that allows entering data and add large sequences of text, such as 300 characters. If the application crashes, similarly to what happened in the previous program execution, a vulnerability is present.

To make it more distinguishable, those fields can each be injected with different character sequences so the vulnerable input field can be identified easily. Special debuggers can also be used, like gdb (https://www.gnu.org/software/gdb) or IDA (https://www.hex-rays.com/products/ida/debugger/index.shtml) that allow you to analyze the execution of a program by interrupting its flow or manipulating the arguments.

Adding Code in Memory

So, a buffer overflow vulnerability has been identified. The next step is to add exploit code in memory that will be able to take advantage of that vulnerability to allow the attacker to execute arbitrary code.

Attackers can use already existing exploits, like the ones present in Metasploit. More skilled attackers will often write their own exploits and will keep an eye out on what types of vulnerabilities vendors publish, so they can develop exploits targeting them or perform analysis themselves and write exploits for vulnerabilities vendors don’t even know exist. Offensive Security’s Metasploit Unleashed has an example on how to use Metasploit and Immunity Debugger to perform stack-based buffer overflows at https://www.offensive-security.com/metasploit-unleashed/writing-an-exploit. You can also use Exploit DB’s buffer overflow tag (https://www.exploit-db.com) to check all existing buffer overflow exploits.

EXAM TIP   Buffer overflow exploits leverage the vulnerable program’s permission levels. That means if a vulnerable program is running with Administrator permissions, the attacker will gain Administrator access. Another thing to keep in mind is the targeted architecture of an exploit. Since they relate to machine code execution, they can only be created for a specific system architecture. So, an exploit for a 32-bit Windows machine will not run on a 32-bit Linux machine.

Running the Code

As mentioned earlier, even if an attacker manages to identify a vulnerable program and is able to insert malicious code, a way to execute it is still required. Since the instruction pointer guides program execution, that means a way to manipulate it will be required. Using a combination of Metasploit and a debugger is one good way of doing this. A preferred technique is using a sequence of No Operation (NOP) instructions preceding the malicious code (signified with an opcode of 0x90 in Intel CPUs), which tell the program to do nothing (NO Operation) and just continue to the next instruction. The attacker aims to run through that NOP segment (also known as NOP sled) until the malicious code is reached and executed.

Defending Against Buffer Overflows

The basic reason for a buffer overflow vulnerability to be present in an application is due to the developer not performing appropriate input validation. As such, prompt developers to not use inherently vulnerable functions and perform careful source code review in addition to ensuring they adhere to industry best practices when writing code. They should attend specific courses and get up to speed on methods of writing code securely. Using automated tools for code review can also help. OWASP has some great recommendations at https://www.owasp.org/index.php/Source_Code_Analysis_Tools. Combining that with patching any vulnerable applications and exhaustively testing them after development are great first steps to mitigating any associated risks. Also, using a HIPS can aid in defending the endpoint against these attacks.

There are also tools that can perform code analysis during compilation time, like Flawfinder, Code Wizard, RATS, Pscan, Fortify static code analyzer, and many more.

Using hardware or software Windows Data Execution Prevention (DEP) will prevent applications from directly running code from a part of the stack that should only contain data. This a Windows feature that dates back to Windows XP. Attackers often try to bypass it by using return-oriented programming techniques, which focus on valid system libraries in an effort to trick the OS into thinking this is a legitimate function.

Address Space Layout Randomization (ASLR) is another good feature that tries to make address guessing for attackers more difficult by randomizing a program’s process address space (focusing on library positions and the stack frame).

Another option is marking all of the stack as nonexecutable space, which may cause some problems with legitimate applications that for some reason place executable code in the data area of the stack. However, it does prevent a good portion of related attacks, since it doesn’t allow them to run any executable code from the stack.

Using canaries is another method. A canary is a known value that is inserted between the EBP pointer and local variables. Once the function finishes its execution, a check is performed to identify if the canary is still intact. If it isn’t, it is indicative of a buffer overflow.

NOTE   Protocol parsers are common targets for attackers due to the high permission levels required to run associated applications. For example, you commonly require Administrator permission to run a packet capture using Wireshark or tcpdump, so finding a vulnerability in those is the ultimate goal for an attacker.

Bypassing Endpoint Security

How do attackers bypass most defenses? The easiest way is with user consent or maybe user manipulation and subsequent consent. Social engineering techniques have a high degree of success, as you may also remember from the previous chapter where SET was discussed. But when endpoint security programs exist, things can get more difficult for the attacker. Let’s look at an example of using MSFvenom to create a binary that can be used against a Windows target and see how endpoint security tools might cope with it.

The goal here is to get a Meterpreter session on the target system. For that purpose, a reverse_tcp payload will be used (found in windows/meterpreter/reverse_tcp). Various Windows binaries can be used to mimic a legitimate application (found in /usr/share/windows-binaries). Let’s use radmin.exe, which will make the user think a remote administration client is being used for a legitimate connection. Feel free to experiment with other Windows binaries of your choice. Using the -f parameter will be used to designate an executable as the target file type:

Copy the executable to your Windows machine (the attacker would normally send this to the target via an e-mail or have them download it via an external server under the attacker’s control).

Start Metasploit in Kali and run an exploit to accept the incoming session and use the reverse shell:

Now go to your Windows machine and run the executable (like any normal user would do) and review Metasploit for the magic to happen.

Figure 6-7 shows what the victim is experiencing. Just a regular Radmin Viewer window as far as they can tell.

Figure 6-7  Radmin viewer execution

However, in Kali a Meterpreter session is now open for the attacker:

Okay, so the malicious file works fine. Uploading it to an online sandbox is an easy way to see how many AV vendors can detect this as malicious. Hybrid Analysis (https://www.hybrid-analysis.com) and Virus Total (https://www.virustotal.com) are two great tools for this purpose. Hybrid Analysis identifies this sample as malicious, as seen in Figure 6-8.

Figure 6-8  Hybrid Analysis report for remote-admin-tool.exe

The Virus Total report is shown in Figure 6-9.

Figure 6-9  Virus Total report for remote-admin-tool.exe

At this time, 51/68 engines identify this sample as malicious, which is about 75 percent. Now for the bad news. Figure 6-10 shows a summary of the vendors unable to identify this sample as malicious. That means if a victim is using any of those, the file would run just fine on their machine.

Figure 6-10  Virus Total report: vendors that identify remote-admin-tool.exe as benign

An attacker could further try to encode the executable using MSFvenom. Use the command msfvenom -l encoders for a list of all encoders and choose one of the x86 ones. Trying to encode the previous file using opt_sub resulted in 41 detections, which is 20 percent less than before, as seen in Figure 6-11.

Figure 6-11  Virus Total detection rate after using an MSFvenom encoder

Attackers can continue encoding the file multiple times, which can also help improve the results. Another option is to use the Veil framework, which you can install in Kali using the command apt-get install Veil. It will ask you to install various modules, like support for Python and Ruby scripts and Wine.

Start the tool using veil. If you want to build a payload for AV evasion, type use Evasion and then list to check all available options (currently 41 modules are listed). Choose what module you want to use (for example, using 22 will select powershell/meterpreter/rev_tcp.py):

Set Kali as your local host and choose a local port for the exploit’s connection and then generate the file:

Veil will ask you to give your output file a name (radmin-new was used) and will generate two files:

The bat file is the one that will be used on the Windows machine, while the resource file can be added in Metasploit using:

You can transfer the bat file and run it in Windows to test for proper operation, but the more important thing is to see how many AV engines detect this new file. Figure 6-12 shows 30 detections, which is a 50 percent detection rate (and 11 fewer than what was seen in Figure 6-11).

Figure 6-12  Virus Total detection rate after using Veil evasion

When creating malicious files aimed at a target, attackers try to have those mimic regular applications and associated tasks. For example, most organizations use Windows, which is why lots of attackers target that OS. Microsoft Office is also heavily used and with it come macros. Although the feature offers added application functionality and task automation, it can have severe effects when untrusted macro commands are run in the environment. Attackers know that and use Metasploit’s modules and tools like Unicorn, which can perform various attacks, including PowerShell downgrade, macro, and shellcode payload generation.

Another way to evade endpoint security detection is to create a source code file and fill in the related exploit sections of it with code generated from MSFvenom (or other similar tools). That program can be compiled and then sent to the target, which might help bypass some security programs. A similar method entails modifying an executable’s machine code (instead of the source code) and then converting that back to an executable file to confuse security applications.

Encoding was mentioned earlier and can often be accompanied with encryption to make it even harder to detect malicious payloads.

Application whitelisting bypass is also a famous method. Any whitelisted applications are allowed for execution, and the AV disregards them. Attackers will try to mimic those by modifying a malicious file’s attributes (for example, installation path, name, and even the hash, assuming a weak algorithm is being used, which is susceptible to collisions) or even compromise signing certificates so they can sign malicious applications as legitimate ones and disseminate them to unsuspected victims.

Chapter Review

Well this was interesting, right? Attackers will try to target pretty much anything they can get their hands on. Having an attacker posing as a prospective salesperson and waiting in a meeting room with an active Ethernet socket or accessing a receptionist’s unlocked workstation with a rubber ducky might be all that it takes to compromise your infrastructure.

Password files are another holy grail for attackers. They will grab them the first chance they get and try to crack those passwords later using their own infrastructure, or they will rent a cloud server and hammer those password files until they crack. They can also get passwords from the LSA cache, Windows Credential Manager, SAM database, and various other locations. Tools like John the Ripper, Cain, and Hashcat can be used to crack a variety of supported formats to get the original passwords. Unencrypted traffic can also work as a good candidate for that purpose. Remember that LM use should be banned from your network. NTLM is highly recommended for your local SAM database and NTLMv2 for network authentication. In Linux systems, always use a shadow file to restrict unauthorized access.

Buffer overflows can prove very painful, and they are still present in various applications. The best way to protect against them is developer education and source code analysis. That will help stop the problem at the beginning, before it finds its way in an application.

AV evasion can be achieved through a variety of tools, like MSFvenom and Unicorn. Attackers can also choose to compile their own source code or modify machine code and convert it back to executable format in an effort to bypass endpoint security. Security vendors do a really good job of keeping up, but attackers also keep up-to-date and are often very well educated and highly skilled, which make it quite hard to prevent exploitation.

Questions

1.  Tony is trying to review the /etc/passwd file to identify his password’s hash:

Tony:x:1003:1004::/home/Tony:/bin/sh

Which of the following statements is correct?

A.  The hash is x.

B.  The hash is ::.

C.  The hash is 1003.

D.  The hash is not present.

2.  Which mode would you choose if you want John the Ripper to include Maria’s login name in tested passwords when trying to crack her password?

A.  Single crack

B.  Wordlist

C.  Incremental

D.  External

3.  Which of the following options would you choose for protecting SAM database passwords?

A.  LM

B.  NTLM

C.  LM challenge-response

D.  NTLMv2

4.  Which of the following passwords can’t have an LM representation?

A.  Apples123

B.  Orangesuy!251

C.  Baby

D.  StrongPhrase197

5.  Which of the following tools would you use to crack an FTP server’s password, located at 172.16.197.136?

A.  John the Ripper

B.  MSFvenom

C.  Hydra

D.  Veil

6.  You are reviewing security logs and notice the sequence 0x90 0x90 0x90 is constantly repeating. Which of the following statements is correct?

A.  Indicates a DoS attack.

B.  This is just normal machine language.

C.  Indicates a directory traversal attack.

D.  Indicates a buffer overflow attack.

7.  Which of the following would you use to crack an NTLM password using Hashcat?

A.  hashcat -a 0 -m 0 list /usr/share/john/password.lst

B.  hashcat -a 0 -m 1000 list /usr/share/john/password.lst

C.  hashcat -a 0 -m 3000 list /usr/share/john/password.lst

D.  hashcat -a 0 -m 100 list /usr/share/john/password.lst

8.  An attacker managed to breach a Windows domain controller and needs to get a copy of the password file for later offline password cracking. Which of the following locations would they have to navigate to?

A.  systemroot\NTDS\ntds.dit

B.  C:\Windows\System32\Config\SAM

C.  etc/passwd

D.  etc/shadow

9.  Which of the following user accounts would most likely be targeted by an attacker?

A.  Jade:500:A961C20FC7082CA0D574F42EA9E292BF

B.  Bob:501:10231AF3596FB98A0CBD839743050DE9

C.  Dean:1003:5A2F17A7ACD65750434B81B866C36CDE

D.  Kate:1004:D616CC11E1328E7985B2546FF971B059

10.  Which of the following can be used to protect against buffer overflow attacks?

A.  PAM

B.  MDM

C.  Canary

D.  Rainbow tables

11.  An attacker is using the following command:

What is most likely the end goal?

A.  Install Radmin

B.  Create a keylogger

C.  Bypass the AV

D.  Exfiltrate data

12.  An attacker is using rainbow tables to crack user passwords. Which of the following would be least affected by this attack?

A.  Windows XP

B.  Windows 7

C.  Windows 10

D.  Ubuntu 19

Answers

1.  D. The x character indicates there’s a shadow file in use. As such, any password hashes would be stored in that file and wouldn’t be present in /etc/passwd.

2.  A. Using single crack mode includes user login name and GECOS information when password cracking is underway and is the best option for this scenario.

3.  B. SAM uses LM and NTLM hashes. From these two, NTLM is the best option, as LM is susceptible to being cracked quite easily, especially for shorter passwords. That’s because it splits passwords into two 7-character portions and converts them to uppercase, thus reducing the possible combinations an attacker has to run through to find the right password.

4.  D. The password StrongPhrase197 has 15 characters and can’t be represented using LM, as that supports a maximum of 14 characters.

5.  C. From the provided options, only John the Ripper and Hydra relate to password cracking. However, from those two, only Hydra can perform online password cracking. John the Ripper requires the password and dictionary files to be provided to start testing the dictionary entries until a match is found in the password file, which is all done offline.

6.  D. 0x90 is the opcode for NOP (NO Operation) in x86 architecture systems. If you see that at random intervals, it can indeed indicate normal machine code. However, if you see it constantly repeating, it most likely means that someone is trying to perform a buffer overflow attack and is using a NOP sled to direct the instruction pointer to arbitrary code for execution.

7.  B. Setting the -m parameter to 1000 will tell Hashcat to crack NTLM hashes.

8.  A. A Windows domain controller would store passwords in systemroot\NTDS\ntds.dit. Note that only local passwords are stored in the local SAM database (C:\Windows\System32\Config\SAM).

9.  A. A SID of 500 next to Jade’s username denotes she’s an administrator, which is what an attacker would primarily focus on.

10.  C. A canary is a known value that is inserted between the EBP pointer and local variables. Once a function finishes its execution, a check is performed to identify if the canary is still intact. If it isn’t, this indicates a buffer overflow attack is taking place.

11.  C. The attacker is trying to place a reverse TCP shell payload in a seemingly harmless copy of Windows radmin.exe and is encoding the output file using MSFvenom’s opt_sub encoder. This indicates the attacker’s goal is to evade AV detection by encoding the output file.

12.  D. Rainbow tables are really effective against unsalted passwords. Remember that a salt is a random sequence of bits, which is added to a password before it gets hashed to make it more resilient against dictionary attacks. Since Windows doesn’t salt passwords, the attack would have the most effect on those systems. However, Linux uses salt, so this attack would be less effective against Ubuntu.

References and Further Reading